<!-- 
//<![CDATA[

/**************** searching functuon ******************************/
var mapviewer, searcher, markers, search, marker;
var searchAddress,distanceUnits,productLineTitle,mapPageLink;
var filterCode, filterDistance, filterCountry, filterType, filterProduct; 
var funcRef = resultsLoaded;
var hasRan = false;
var iteration = 0;

function searchDealers(para1,para2,para3,para4,para5){

    filterCode=para1;
    filterDistance= para2;
    filterCountry = para3; 
    filterType = ""; 
    filterProduct=para5;
    distanceUnits="km"; 
    initSearch();
   
}

function initSearchOveride(isMaster, search, searcher) {
     
    search.radius_units = 'km';
    var address_qs = '';
    var my_country_code = filterCountry;
    search.address = new MMAddress({ qs : my_country_code, country_code : 'uk'});
    search.result_set_size = 800;
    search.count = 100;
    search.max_distance = filterDistance;
    search.data_source = "mm.clients.briggs1_alt";
        //Apply type filter,
    search.filters = new Array();
    var filterField="DealerType";
    mapPageLink='<a href="showMap.aspx?';
    var productFilter;
    
    if(filterProduct=="en"){
        productFilter="dl_usengines";
        filterType = "Engine";
    }
    else if(filterProduct=="pg"){
        productFilter="dl_usportablegenerators";
        filterType = "Portable Generator";   
    }
    else if(filterProduct=="hg"){
        productFilter="dl_usstandbygenerators";
        filterType = "Stand-by Generator"  
    }
    else if(filterProduct=="pw"){
        productFilter="dl_uspressurewashers"; 
        filterType = "Pressure Washers"   
    }
    else if(filterProduct=="om"){
        productFilter="dl_usoutboardmotors";  
        filterType = "Outboard Motor"  
    }

    if (filterProduct != "") {
        search.filters.push( new MMSearchFilter(productFilter, 'in', '1') ); 
    }
    
    var searchValues="ARSD";

    if (isMaster) {
        search.filters.push( new MMSearchFilter(filterField, 'in', 'MSSD*'));
    } else {
        search.filters.push( new MMSearchFilter(filterField, 'in', 'ARSD,BSDRSD,ARSD+,GGRSD,SBSSD,GPRSD,'));
    }
    
    // Apply distance filters, 
    search.distance_units = distanceUnits.value;
    search.max_distance = Number(filterDistance);
    
    search.data_source="mm.clients.briggs1_alt";

    var orderBy = new Array();
    orderBy[0] = "distance";
    orderBy[1] = "DealerType";
    search.order_by_fields = orderBy;
    searcher.search( search );
}

function initSearch () {
    markers = new Array(); 
    searcher = new MMSearchRequester( funcRef );
    
    search = new MMSearch();  
    
    //First search for Master Dealers
    initSearchOveride(true, search, searcher);
    
    //Wait a sec (let's not create a race condition) and search for all other types of dealers
    setTimeout("initSearchOveride(false, search, searcher)",1500);
} 

function resultsLoaded ( ) {
    var results_returned = 1;
    var  start_index_value = 1;    
    var resultTable='';

    if (searcher.error_code ) {
        var err =  '';
        if (searcher.error_explanation ) {
            err =  searcher.error_explanation;
        } 
        else 
        {
            err='Sorry!!!, I could not locate any ' + filterType+productLineTitle + ' in the vicinity, Please try again.'; 
        }
        
        if (hasRan == false) {

            hasRan = true;
            resultTable=err;
        }
    } 

    for ( var count=0, r = searcher.record_sets.length; count < r; count++ ) {// Loop through each record set
        if ( searcher.record_sets[count].error ) {//an error was returned for the record set, display details and return:
            var err =  '';
            if ( searcher.record_sets[count].error.error_explanation ) {
                err =  searcher.record_sets[count].error.error_explanation;
            } 
            else {
                err =  'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
                //err= 'Sorry, I could not locate any '+filterType+productLineTitle+' in the vicinity, Please try again.'; 
            }
            resultTable+=err;
            return;  
        }
        
        if ( searcher.record_sets[count].records ) {//If not, check to see if individual records have been returned:
            
            //check for master dealer - charlie
            var dealerType = 'Dealer';
            if (searcher.record_sets[count].records[0].DealerType == "MSSD*") {
                dealerType = 'Master Dealer';
            }
            
            var checkString = "";
            var realCount = 0;
            for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
                var record = searcher.record_sets[count].records[record_count]; 
                if (checkString.match(record.addr1) != null) {
                    //skip and do nothing
                } else {
                    realCount++;
                    checkString += " " + record.addr1;
                }
            }

            realCount = searcher.record_sets[count].records.length;
            resultTable+='<br /><b><font size=2>' + dealerType + '&nbsp;Locator Results:</b>&nbsp;'+ realCount + ' '+filterType +' ' + dealerType + 's Found</font><br><br>' +
                        '<table>'+
                            '<tr>'+
                                '<td style="border-bottom:1px solid #808080" width="5%">'+
                                    ' '+
                                '</td>'+
                                '<td style="border-bottom:1px solid #808080" width="30%">'+
                                    '<b>Name: </b>'+
                                '</td>'+
                                '<td style="border-bottom:1px solid #808080" width="30%">'+
                                    '<b>Address: </b>'+
                                '</td>'+
                                '<td style="border-bottom:1px solid #808080" width="15%">'+
                                    '<b>Telephone: </b>'+
                                '</td>'+
                                '<td style="border-bottom:1px solid #808080" width="10%">'+
                                    '<b>Distance: </b>'+
                                '</td>'+
                                '<td style="border-bottom:1px solid #808080" width="10%">'+
                                    '<b>Map: </b>'+
                                '</td>'+
                            '</tr>';       
            //need to create a new counter as we are filtering out duplicates // charlie
            var realTimeCount = 1; 
            
            for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
                var record = searcher.record_sets[count].records[record_count]; 
                
                /*
                resultTable+=("-----------------------------------     <br /> ");
                for (x in record) {
                    resultTable+=("<br />" + x + ": " + record[x] + "</br>");
                }
                */

                var thisID=record.id;
                var thisName=record.name;
                var thisStreet=record.street;
                var thisCity=record.town;
                var thisPC=record.pc;
                var thisCountry=record.country;
                var thisDistance=record.distance.km;
                var thisPhone="n/a";
                var thisDealerType=record.DealerType;
                if(record.telephone!=null){
                   thisPhone=record.telephone;
                }
                var thisFax="n/a";
                if(record.fax!=null){
                   thisFax=record.fax;
                }
                var thisSite="n/a";
                if(record.url!=null){
                   thisSite=record.url;
                }
                var thisType="n/a";
                if(record.DealerType!=null){
                   thisType=record.DealerType;
                }
                
                if (resultTable.match(thisStreet) != null) {
                    //skip and do nothing
                } else {
                    if (thisDealerType == "MSSD*") {
                        thisName = "<div style='width: 200px; padding-bottom: 20px;'>" + thisName + "&nbsp;<br /><img style='float: left; padding-left: 1px; padding-top: 3px;' src='../../images/corp/master_dealer_icon.jpg' /></div>";
                    }
                    resultTable+='<tr>'+
                                     '<td valign="top">'+ (realTimeCount++) + '</td>'+
                                     '<td valign="top">'+thisName+'</td>'+
                                     '<td valign="top">'+thisStreet+"<br>"+thisCity+", "+thisPC +'</td>'+
                                     '<td valign="top">'+thisPhone+'</td>'+
                                     '<td valign="top">'+thisDistance+' Kilometers</td>'+
                                     '<td valign="top">'+mapPageLink+
                                                       'id='+thisID+
                                                       '&searchFor=service'+ //filterType+
                                                       '&name='+thisName+
                                                       '&phone='+thisPhone+
                                                       '&type='+thisType+
                                                       '&street='+thisStreet+
                                                       '&city='+thisCity+
                                                       '&country='+thisCountry+
                                                       '&pc='+thisPC+
                                                       '&site='+thisSite+
                                                       '&distance='+thisDistance+
                                                       '&fax='+thisFax+
                                                       '">View Map</a></td>'+
                                 '</tr>';
                }
            }
            resultTable+='</table>';
            if (dealerType == 'Master Dealer') {
                resultTable+='<div id="masterDealerInfo" style="border: solid 1px #000000; padding: 10px;  padding-bottom: 20px; background-color: #F4F4F4"><p><img src="../../images/corp/master_dealer_icon_large.jpg"/></p><br /><p>A Briggs & Stratton Master Sales and Service Dealer is required to staff a qualified service technician who performs Engine and/or product warranty repairs on all Briggs & Stratton product lines.  To ensure quality of service, the owner or technician employed must meet certain Briggs & Stratton training requirements.</p></div>';
            }
        } 
        else {
            //charlie 11-15-2007
            //resultTable+='Sorry, I could not locate any '+filterType+' in the vicinity, Please try again.!'; 
            results_returned = 0;
            iteration = iteration + 1;
        }
    }
    if (iteration == 2) {
        document.getElementById("showMapResults").innerHTML += "Sorry, there are no dealers within this many miles of your selected zip code. Please select a larger radius to search.";
    }
    //charlie 11-15-2007
    document.getElementById("showMapResults").innerHTML += resultTable; 
}

var para;
function setPara(inPara){
    para=inPara;
}

function getPageName(){
    var path = location.href.match(/\/([a-z0-9_-]+\.\w+)/i);
    if (path != null) {
        path = path.toString();
        return path.substr(path.lastIndexOf(",") + 1, path.length);     
    }
    return "";
}   
    
//emulate the request.getParameter
function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }	
}

function getMap(){
    mapviewer = new MultimapViewer(document.getElementById('myMapViewer'));
    mapviewer.addEventHandler( 'startSearchRequest', updateSearchStatus );
    mapviewer.addEventHandler( 'endSearchRequest', updateSearchStatus );
    mapviewer.addEventHandler( 'endSearchRequest', endSearch );

    var page = new PageQuery(window.location.search); 
    var country = unescape(page.getValue('country'));
    country = 'uk';
    //alert(country);

    search = new MMSearch(new MMSearchFilter('id','eq',para)); 
    
    search.data_source="mm.clients.briggs1_alt";
    
    mapviewer.goToPosition( new MMLocation (search, 16));
}

function isShowMap() {
	var loc = location.href;
	loc = loc.toString();
	var showMap = loc.indexOf("showMap.aspx");
	if (showMap < 1) {
	    return false;
    }
	return true;
}

if (isShowMap() == true) {
    MMAttachEvent( window, 'load', getMap );
}

function updateSearchStatus( type ) {
    var gs = document.getElementById( 'searchStatus' );
    if( type == 'startSearch' ) {
        //if we are starting a search request, display the flashing "Searching..." message
        gs.style.display = 'block';
    } 
    else {
        //if we are ending a search request, hide the flashing "Searching..." message
        gs.style.display = 'none';
    }
}

//browser = new Browser(); 
function endSearch( type, target, results, error_code ) {
    if( error_code ) {
        return;
    } 
    mapviewer.removeOverlay( marker );
    marker = mapviewer.createMarker( results[0].records[0].point, {'label' : '#' + results[0].records[0].id.toString(), 'text' : 'x'} );

    var html = '<h1>'+ results[0].records[0].name.toString() + '<' + '/h1>'; 
    var addr = '';
    if ( results[0].records[0].street.toString() != '' ) addr += results[0].records[0].street;
    if ( results[0].records[0].town.toString() != '' ) addr += ( (addr != '') ? ', ' : '' ) + results[0].records[0].town.toString();
    if ( results[0].records[0].pc.toString() != '' ) addr += ( (addr != '') ? ', ' : '' ) + results[0].records[0].pc.toString();  
    html += '<p>' + addr + '<' +  '/p>';
    marker.setInfoBoxContent( html );
    marker.openInfoBox () ; 
    
    //Reposition map after opening Infobox, and then move map 30pixels down:
    this.ie = (navigator.appName == "Microsoft Internet Explorer");
    if(this.ie){
        mapviewer.goToPosition( results[0].records[0].point, 16 );
        //mapviewer.moveMap( new MMPoint( 0,-512) );
    }
}

function getStartAddress(){
    var startLocation='<table border="0">'+
                            '</tr>'+
                                '<td width="25%" colspan="2" style="border-bottom:1px solid #808080">'+
                                    '<font size="2"><b>Start Location: </b></font>'+
                                '</td>'+
                            '</tr>'+
                            '</tr>'+
                                '<td width="25%">'+
                                    '<b>Address: </b>'+
                                '</td>'+
                                '<td width="25%">'+
                                    '<input type=text id=startStreet name=startStreet />'+
                                '</td>'+
                            '</tr>'+
                                '<td width="25%">'+
                                    '<b>City/Town: </b>'+
                                '</td>'+
                                '<td width="15%">'+
                                    '<input type=text id=startCity name=startCity />'+
                                '</td>'+
                            '</tr>'+
                            '</tr>'+
                            '</tr>'+
                         '</table>';
         
    document.getElementById("startLocationDiv").innerHTML = startLocation; 
    document.getElementById("directionLabelDiv").innerHTML = "<center><h4><a href='javascript:getDirection();'><img src=\"../../images/corp/btn_driving-directions.gif\" /></a></h4></center>";
    document.getElementById("endLocationTitleDiv").innerHTML = "<font size=2><b>End Location:</b></font>";
}


/**************************************** directing functuon ***************************************************/
var route_finder,route;
var directionFuncRef = directionResultsLoaded;
var max_zindex = 1000;
function getDirection(){
    cleanUp();

    var startStreet=document.getElementById("startStreet").value;
    var startCity=document.getElementById("startCity").value;
    var startCountry='uk';
    
    var endStreet=document.getElementById("endStreet").value;
    var endCity=document.getElementById("endCity").value;
    var endPC=document.getElementById("endPC").value;
    var endCountry='uk';
    
    if(startCity==""){
        alert("The field of City/Town is required");
    }
    else{
        var locations = new Array();
        
        //define start location
        var startAddress=new MMAddress();
        startAddress.street=startStreet;
        startAddress.city=startCity;
        startAddress.country_code='uk';
        var startLocation=new MMLocation(startAddress);
        
        //define end location
        var endAddress=new MMAddress();
        endAddress.street=endStreet;
        endAddress.city=endCity;
        endAddress.postal_code =endPC;
        endAddress.country_code='uk';
        var endLocation=new MMLocation(endAddress);
        
        locations.push(startLocation);
        locations.push(endLocation);
        
        route = new MMRoute(locations);
        
        route_finder = new MMRouteRequester( directionFuncRef );
        route_finder.request(route);
    }
}

function directionResultsLoaded(){
    if (route.error_code) {
        if (route.error_code == 'MM_ROUTE_GEOCODING_ERRORS') {
            processGeocodingErrors (route.geocoding_errors);
        } 
        else {
            alert(route.error_code + ': ' + route.error_explanation);
        }
    } 
    else {
        mapviewer.goToPosition( mapviewer.getAutoScaleLocation( route.bounds ) );
        displayStages(route);
        //alert("route length="+route.polyLine.length);
        for( var i = 0, l = route.polyLine.length; i < l; ++i ) {
            //alert("route length="+route.polyLine.length);
            route.polyLine[i].reset(route.polyLine[i].points, {'opacity':0.6, 'color':'#0000FF', 'thickness':2.0});
            mapviewer.addOverlay(route.polyLine[i]);
        }
    }
}

function processGeocodingErrors (errors) {
    for (var i = 0; i < errors.length; i++) {
        var errorLoc="";
        if(errors[i].input_id==1){
            errorLoc="Start Location";
        }
        else{
            errorLoc="End Location";
        }
        if (errors[i].error_code == 'MM_GEOCODE_NO_MATCHES') {
            alert('No matching location for '+errorLoc);
        } 
        else if (errors[i].error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
            alert('Multiple matching locations for '+errorLoc+', please enter a specific address');
        }
    }
}

function displayStages(route) {
    var curr_step = 1;
    var stages = route.stages; 
    var container = document.getElementById('routeSteps');
    
    var h2 = document.createElement('h2');
    h2.appendChild(document.createTextNode('Travel directions'));
    container.appendChild(h2);
    
    var summary = '';
    summary += 'Start: ' + stages[0].start_address;
    summary += '<br />End: ' + stages[stages.length - 1].end_address;
    summary += '<br />Total Distance: ' + route.distance.miles + ' mile(s)';
    summary += '<br />Estimated Total Time: ';
    if (route.duration.days > 0) { summary += route.duration.days + ' day(s) '; }
    if (route.duration.hours > 0) { summary += route.duration.hours + ' hour(s) '; }
    if (route.duration.minutes > 0) { summary += route.duration.minutes + ' minute(s) '; }
    var p = document.createElement('p');
    p.innerHTML = summary;
    container.appendChild(p);
    
    for (var count=0; count < stages.length; count++) {
        var stage_summary = '';
        stage_summary += '<strong>Stage ' + (count + 1) + '<' + '/strong>';
        stage_summary += '<br />Start: ' + stages[count].start_address;
        stage_summary += '<br />End: ' + stages[count].end_address;
        stage_summary += '<br />Stage Distance: ' + stages[count].distance.miles + ' mile(s)';
        stage_summary += '<br />Estimated Stage Time: ';
        if (stages[count].duration.days > 0) { stage_summary += stages[count].duration.days + ' day(s) '; }
        if (stages[count].duration.hours > 0) { stage_summary += stages[count].duration.hours + ' hour(s) '; }
        if (stages[count].duration.minutes > 0) { stage_summary += stages[count].duration.minutes + ' minute(s) '; }
        stage_summary += '<br />Summary: ' + stages[count].summary;
        var p = document.createElement('p');
        p.innerHTML = stage_summary;
        container.appendChild(p);
        var ol = document.createElement('ol');
        ol.id = 'stage_' + count;
        ol.start = curr_step;
        var steps = stages[count].steps;
        for (var stepCount=0; stepCount < steps.length; stepCount++) {
            var text = curr_step;
            var zindex = max_zindex - curr_step + 1;
            if (count == stages.length - 1 && stepCount  == steps.length - 1) {
                zindex = max_zindex; 
            }               
            var instruction = steps[stepCount].instruction;
            var roadname = steps[stepCount].road_name;
            var roadnumber = steps[stepCount].road_number; 
            if (roadname && roadnumber) {
                instruction += ' ' + roadname + ' (' + roadnumber + ') ';
            } 
            else if (roadname) {
                instruction += ' ' + roadname + ' ';
            } 
            else if (roadnumber) {
                instruction += ' ' + roadnumber + ' ';
            }
            var distance = '';                    
            if (steps[stepCount].distance.miles > 0) { 
                distance += steps[stepCount].distance.miles + ' mile(s) '; 
            }
            if (distance != '') { 
                distance = ' - ' + distance 
            };
            var li = document.createElement('li');
            li.innerHTML = instruction + distance;
            ol.appendChild(li);
            createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
            ++curr_step;
        }
        container.appendChild(ol);
    }            
    container.style.display = 'block'; 
    container.appendChild(p);            
}
function createStepMarker(location, instruction, text, zindex) {
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
}  

function cleanUp () {
    var stepsContainer = document.getElementById('routeSteps');
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    stepsContainer.style.display = 'none';
    mapviewer.removeAllOverlays();
    markers = new Array();
}

function validateFindLocationForm(frmname){
    var frm = eval(document.forms[frmname]);  
    var searchDistance = frm.searchdistance.value;
    var countryName = frm.countryname.value;
    var msg = "";
    if(searchDistance == null || searchDistance.length == 0){
        msg = "Search Distance is required.";
    }
    if(countryName == null || countryName.length == 0){
        msg = "Country is required.";
    }
    if(msg == "") {
        frm.submit();
    }
    else 
    {
        alert("msg="+msg);
    }
};

function isNumberic(s){ 
    for (var i = 0; i < s.length; i++) { 
        var c = s.charAt(i); 
        if((c < "0") || ("9" < c)) {
            return false
            break;
        } 
    } 
    return true; 
};
function doLogin(frmname){
    var thisfrm = eval(document.forms[frmname]);
    var emailFieldValue=thisfrm.emailAddr.value;
    var pwdFieldValue=thisfrm.passwd.value;
    var response=callHttp('GET','/my_briggs/do_login.aspx?passwd='+pwdFieldValue+'&emailAddr='+emailFieldValue,'lyr_header');
    if(response==""){
        document.location.replace("/my_briggs/index.aspx"); 
        //showLayerX('/my_briggs/index.aspx','lyr_mainpage');
        //showLayerX('/my_briggs/x_signintoggle.aspx','lyr_signintoggle');
    }
    else{
        showLayerX('/my_briggs/x_login.aspx?error='+response+'&emailValue='+emailFieldValue+'&pwdValue='+pwdFieldValue,'lyr_header');
    }
};
function doForgetPassword(frmname){
    var thisfrm = eval(document.forms[frmname]);
    var emailFieldValue=thisfrm.emailAddr.value;
    var securityQFieldValue=thisfrm.securityQuestionID.value;
    var securityAFieldValue=thisfrm.securityAnswer.value;
    var response=callHttp('GET','/my_briggs/do_forgotpassword.aspx?securityQ='+securityQFieldValue+'&securityA='+securityAFieldValue+'&emailAddr='+emailFieldValue,'lyr_header');
    if(response==""){
        showLayerX('/my_briggs/x_forgotpassword.aspx?sendok=1','lyr_header');
    }
    else{
        showLayerX('/my_briggs/x_forgotpassword.aspx?error='+response+'&emailValue='+emailFieldValue+'&securityAFieldValue='+securityAFieldValue+'&securityQFieldValue='+securityQFieldValue,'lyr_header');
    }
};

//]]> 
// -->
