var MAX_DEALER_DISPLAY = 25;
var searchResultsUpdater = new SearchResultsUpdater();
var dealers = new Array();
var dealerSearchResults = "";
var onloads = new Array();
var selectedDealerIndex = -1;
var q;
var map;
var map_markers=[];
onloads.push(initPage);
function bodyOnLoad() {
	if (GBrowserIsCompatible()===false) {
		alert("We're sorry.  We do not support your web browser.  Please use FireFox or Internet Explorer 6 or above.");
	}
	$("searchForm").style.width=getDocumentWidth()-20;
	 new Rico.Effect.Round( null, 'roundNormal' );
	 new Rico.Effect.Round( null, 'roundCompact', {compact:true} );
	 for ( var i = 0 ; i < onloads.length ; i=i+1 ) {
	 	onloads[i]();
	 }
	 
}
    	
function initPage() {
	var findByZipBtn = document.getElementById("findByZip");
	var findByAddressBtn = document.getElementById("findByAddress");
 	Rico.Corner.round("searchForm");
 	ajaxEngine.registerRequest('dealerSearchResults', "service/locator.jsp");	// register service request
 	ajaxEngine.registerAjaxObject('dealerSearchResults', searchResultsUpdater);	// register object handler
 	/**
 	var zipRouter = new jsEvent.EventRouter(findByZipBtn,"onclick");
 	var addressRouter = new jsEvent.EventRouter(findByAddressBtn,"onclick");
 	zipRouter.addListener(doDealerFindByZip);
 	addressRouter.addListener(doDealerFindByAddress);
 	**/
}

function formatDecimal(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function trim(str) {
	str = str.replace(/^\s*|\s*$/g,"");
	return str;
}
		
function showWait() {
	var statusObj = document.getElementById("transportStatus");
	statusObj.innerHTML="<IMG src='images/indicator.gif' alt='status' /> Please wait...";
}
function hideWait() {
	statusObj = document.getElementById("transportStatus");
	statusObj.innerHTML="";
}
		
function doDealerFindByZip() {
	var zipCode = document.getElementById("byZip_zip").value;
	var distance = "25";
	showWait();
	q = zipCode;
	setTimeout("sendSearchRequest(" + distance + ")",500);
}
		
function sendSearchRequest(distance) {
	ajaxEngine.sendRequest('dealerSearchResults',"q="+q, "d=" + distance);
}
		
function doDealerFindByAddress() {
	var address = $("byAddress_address").value;
	var city = $("byAddress_city").value;
	var state = $("byAddress_state").options[document.getElementById("byAddress_state").selectedIndex].value;
	var zipCode = $("byAddress_zip").value;
	var distance = "25";
	q = address + " " + city + " " + state + ", " + zipCode;
	showWait();
	setTimeout("sendSearchRequest(" + distance + ")",500);
}
		
function showMap(i) {
	//<![CDATA[
	var dealerAddress = dealers[i].address + " " + dealers[i].city + ", " + dealers[i].state + " " + dealers[i].zipcode;
  	var dealerAddressTxt = dealers[i].name + "<br/>" + dealers[i].address + "<br/>" + dealers[i].city + ", " + dealers[i].state + " " + dealers[i].zipcode;
  
	dealerSearchResults = $("dealerSearchResults").innerHTML;
	$('data_grid_header').style.display="none";
	strMapInfo  = "<TABLE width='99%'><TR style='font-size:11px;' valign='top'><TD><DIV id='companyInfo'>";
	strMapInfo += "<b>"+ dealers[i].name +"</b><BR/>";
	strMapInfo += dealerAddressTxt + "<br/>";
	strMapInfo += "<A target='_blank' href=\"http://maps.google.com/maps?saddr=" + q + "&daddr=" + dealerAddress + "\">Driving Directions</A><br/><br/>";
	strMapInfo += "Phone: " + dealers[i].phone +"<BR/>";
	strMapInfo += "Fax: " + dealers[i].fax +"<BR/>";
	
	
	strMapInfo += "</DIV>";
	strMapInfo += "</TD><TD><DIV id='map'></DIV></TD></TR></TABLE>";
	
	$("dealerSearchResults").innerHTML = strMapInfo;
    
    //$("companyInfo").innerHTML = strCompanyInfo;
	
	$("companyInfo").style.height=getDocumentHeight()-115;
	var icon = new GIcon(getBaseIcon());
    $("map").style.height=getDocumentHeight()-115;
    $("map").style.width=(getDocumentWidth()-235)*.97;
    map = new GMap2(document.getElementById("map"));
    addMapControls(map);
	
	var point = new GLatLng(dealers[i].latitude, dealers[i].longitude)
	var marker = createMapMarker(point, dealers[i]);
	map.setCenter(point, 13);
	map.addOverlay(marker);
	var ovMap=new GOverviewMapControl();
	map.addControl(ovMap); 
	if (dealers.length > 0) setStatus("<b>" + dealers.length + "</b> dealers found near <b>" + q + "</b> - <A href='javascript:returnToSearchResults()'>Return to List</A> or <A href='javascript:document.location.reload()'>Search Again</A>");
	else setStatus("<b>No dealers found in your area</b> <A href='javascript:document.location.reload()'>Search Again</A>");
	//]]>
}
		
function showAllInMap() {
	//<![CDATA[
	selectedDealerIndex = -1;
	dealerSearchResults = $("dealerSearchResults").innerHTML;
	$('data_grid_header').style.display="none";
	strMapInfo  = "<TABLE width='99%'><TR style='font-size:11px;' valign='top'><TD><DIV id='companyInfo'></DIV></TD><TD><DIV id='map'></DIV></TD></TR></TABLE>";
	$("dealerSearchResults").innerHTML = strMapInfo;
    
    strCompanyInfo = "";
    var dCounter = 0;
    for (var i = 0; i < dealers.length && i < MAX_DEALER_DISPLAY; i= i +1) {
    	if (trim(dealers[i].address).length > 0) {
	    	strCompanyInfo += "<DIV id='companyInfo_"+dealers[i].id+"' class='companyInfoItem' style='cursor:pointer;' " +
	    	"onclick='showInfoWindowAndMap(" + dealers[i].id +", " + dCounter + ")' " +
	    	"onmouseover=\"if(selectedDealerIndex!=" + dealers[i].id + ") this.className='highlight'\" " +
	    	"onmouseout=\"if(selectedDealerIndex!=" + dealers[i].id + ") this.className='noHighlight'\">"+dealers[i].name+"</DIV>";
	    	dCounter++;
	    }
	}
	$("companyInfo").innerHTML = strCompanyInfo;
	
	$("companyInfo").style.height=getDocumentHeight()-115;
	var icon = new GIcon(getBaseIcon());
    $("map").style.height=getDocumentHeight()-115;
    $("map").style.width=(getDocumentWidth()-235)*.97;
    map = new GMap2(document.getElementById("map"));
    
    addMapControls(map);
    map.setCenter(new GLatLng(dealers[0].latitude, dealers[0].longitude), 13);
    var points = new Array();
    var points_counter = 0;
    var bounds = new GLatLngBounds();
    for (var i = 0; i < dealers.length && i < MAX_DEALER_DISPLAY; i++) {
    	if (trim(dealers[i].address).length > 0) {
	    	points[points_counter] = new GLatLng(dealers[i].latitude, dealers[i].longitude);
	    	bounds.extend(points[points_counter]);
	    	icon.image = "images/marker" + (points_counter+1)+".png";
		    marker = createMapMarker(points[points_counter], dealers[i], true, icon);
		    map_markers[points_counter] = marker;
			map.addOverlay(marker);
			points_counter++;
		}
	}
	
	// center and zoom on the bounds. 
	map.centerAndZoomOnBounds(bounds); 
	var ovMap=new GOverviewMapControl();
	map.addControl(ovMap);
	if (dealers.length > 0) setStatus("<b>" + dealers.length + "</b> dealers found near <b>" + q + "</b> - <A href='javascript:returnToSearchResults()'>Return to List</A> or <A href='javascript:document.location.reload()'>Search Again</A>");
	else setStatus("<b>No dealers found in your area</b> <A href='javascript:document.location.reload()'>Search Again</A>");
	//]]>
}

function createMapMarker(point, dealer, showInfo, icon) {
	var marker;
	if (icon) marker = new GMarker(point, icon);
  	else marker = new GMarker(point);
  var dealerAddress = dealer.address + " " + dealer.city + ", " + dealer.state + " " + dealer.zipcode;
  var dealerAddressTxt = dealer.name + "<br/>" + dealer.address + "<br/>" + dealer.city + ", " + dealer.state + " " + dealer.zipcode;
  GEvent.addListener(marker, 'click', function() {
	
	marker.openInfoWindowHtml("<DIV style='width:240px;height:50px;'>" +  dealerAddressTxt + "<br/><A target='_blank' href=\"http://maps.google.com/maps?saddr=" + q + "&daddr=" + dealerAddress + "\">Driving Directions</A></DIV>");
	if (showInfo) {
		showInfoWindow(dealer.id);
	}
  });

  return marker;
}

GMap2.prototype.centerAndZoomOnBounds = function(bounds) {
   var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0;
   var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0;
   var center = new GLatLng(center_lat,center_lng)
   map.setCenter(center, map.getBoundsZoomLevel(bounds));
}

function getBaseIcon() {
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	return baseIcon;
}

function addMapControls(m) {
	m.addControl(new GLargeMapControl());
	m.addControl(new GMapTypeControl());
	m.addControl(new GScaleControl()); 
}

function showInfoWindowAndMap(dealerId, markerId) {
	GEvent.trigger(map_markers[markerId],'click');
	showInfoWindow(dealerId);
}

function showInfoWindow(dealerId) {
	var dealer;
	for (var i = 0; i < dealers.length; i++) {
		if(dealerId == dealers[i].id) dealer = dealers[i];
	}
	var dealerAddress = dealer.address + " " + dealer.city + ", " + dealer.state + " " + dealer.zipcode;
  	var dealerAddressTxt = dealer.name + "<br/>" + dealer.address + "<br/>" + dealer.city + ", " + dealer.state + " " + dealer.zipcode;
	var dealerInfo = "";
	if (selectedDealerIndex!=-1) {
		$("companyInfo_"+dealers[selectedDealerIndex].id).innerHTML=dealers[selectedDealerIndex].name;
		$("companyInfo_"+dealers[selectedDealerIndex].id).className="dealerInfoBox_hidden";
	}
	dealerInfo += "<b>" + dealer.name + "</b><br/>";
	dealerInfo += dealer.address + "<br/>";
	dealerInfo += dealer.city + ", " + dealer.state + " " + dealer.zipcode + "<br/><A target='_blank' href=\"http://maps.google.com/maps?saddr=" + q + "&daddr=" + dealerAddress + "\">Driving Directions</A><br/><br/>";
	dealerInfo += "<b>Phone:</b> " + dealer.phone + "<br/><b>Fax:</b> " + dealer.fax + "<br/>";
	dealerInfo += "<b>Distance:</b> approx. <b>" + formatDecimal(dealer.distance) + " miles</b>";
	$("companyInfo_"+dealer.id).innerHTML=dealerInfo;
	$("companyInfo_"+dealer.id).className="dealerInfoBox_display";
	
	scroll_element(document.getElementById("companyInfo_"+dealer.id));
	Rico.Corner.round(document.getElementById("companyInfo_"+dealer.id));
	selectedDealerIndex = dealer.id;
}


function returnToSearchResults() {
	$("data_grid_header").style.display=(document.all?"block":"table");
	$("dealerSearchResults").innerHTML = dealerSearchResults;
	if (dealers.length > MAX_DEALER_DISPLAY) setStatus("<b>" + dealers.length + "</b> dealers found near <b>" + q + "</b> - <A href='javascript:showAllInMap()'>Show nearest " + MAX_DEALER_DISPLAY + " in Map</A> or <A href='javascript:document.location.reload()'>Search Again</A>");
	else if (dealers.length > 0) setStatus("<b>" + dealers.length + "</b> dealers found near <b>" + q + "</b> - <A href='javascript:showAllInMap()'>Show All in Map</A> or <A href='javascript:document.location.reload()'>Search Again</A>");
	else setStatus("<b>No dealers found in your area</b>");
}

function setStatus(s,n) {
  $('statusContainer').style.visibility = "visible";
  $('statusMsg').innerHTML = s;
  if (n) setTimeout( "$('statusContainer').style.visibility = 'hidden';", n );
}
		
function scroll_element(theelement){ 
	if(theelement.scrollIntoView){ 
		theelement.scrollIntoView(true); 
	} 
}
function displayDealerSearchResults() {
	var xmlNodes = searchResultsUpdater.dealerXMLNodes;
	dealers = new Array();
	$("data_grid_header").style.display="inline";
	var strDealerLines = "<TABLE class='fixedTable' cellspacing='0' cellpadding='0'>";
	var color="#FFFFCC";
	for (var i = 0; i < xmlNodes.length; i++) {
		
		var strDealerLine = "";
		d = {
				id			:	i,
  				name		:	xmlNodes[i].getAttribute("name"),
  				address 	: 	xmlNodes[i].getAttribute("address"),
  				city		:	xmlNodes[i].getAttribute("city"),
  				state		:	xmlNodes[i].getAttribute("state"),
  				zipcode		:	xmlNodes[i].getAttribute("zipcode"),
  				phone		:	xmlNodes[i].getAttribute("phone-area") + xmlNodes[i].getAttribute("phone-number"),
  				fax			:	xmlNodes[i].getAttribute("fax-area") + xmlNodes[i].getAttribute("fax-number"),
  				email		:	xmlNodes[i].getAttribute("email"),
  				url			:	trim(xmlNodes[i].getAttribute("url")),
  				distance	:	xmlNodes[i].getAttribute("distance"),
  				longitude 	:	xmlNodes[i].getAttribute("longitude"),
  				latitude	:	xmlNodes[i].getAttribute("latitude")
		}
		if (d.fax.indexOf("0000000")!=-1) d.fax = "";
		dealers[i] = d;
		if (i%2!=0) color="#FFFFCC";
		else color="white";
		strDealerLine +="<TR class='dealerSearchResultsRow' style='background-color:" + color + "'>" +
			"<TD class='cell first' style='width:224px'>" + d.name + "</TD>" +
			"<TD class='cell' style='width:214px'>" + d.address + "<BR/>" + d.city + ", " + d.state + " " + d.zipcode + "</TD>" +
			"<TD class='cell' style='width:114px'>Ph:&nbsp;" + d.phone + "<br/>Fax:" + d.fax + "</TD>" +
  			"<TD class='cell' style='width:40px'>";
		if (d.email.length>4) strDealerLine += "<A href='mailto:" + d.email + "'>Email</A>";
		else strDealerLine +="&nbsp;" 
		strDealerLine += "</TD>" +
			"<TD class='cell' style='width:50px'>";
		if (d.url.length >4) strDealerLine += "<A target='_blank' href='http://" + d.url + "'>Website</A>";
		else strDealerLine += "&nbsp;";
		strDealerLine += "</TD>";
		strDealerLine += "<TD class='cell' style='width:30px'>" + 
		((d.address.length > 6)?
		("<A href='javascript:showMap(" + i + ")'>Map</A>"):"&nbsp;")
		+ "</TD>";
		strDealerLine += "<TD class='cell' style='width:55px'>" + formatDecimal(d.distance) + " mi</TD>"+
		"</TR>";
		strDealerLines += strDealerLine;
	}
	strDealerLines += "</TABLE>";
	$("searchForm").style.display="none";
	$("dealerSearchResults").style.height=getDocumentHeight()-115;
	$("dealerSearchResults").innerHTML=strDealerLines;
	
	if (dealers.length > MAX_DEALER_DISPLAY) setStatus("<b>" + dealers.length + "</b> dealers found near <b>" + q + "</b> - <A href='javascript:showAllInMap()'>Show nearest " + MAX_DEALER_DISPLAY + " in Map</A> or <A href='javascript:document.location.reload()'>Search Again</A>");
	else if (dealers.length > 0) setStatus("<b>" + dealers.length + "</b> dealers found near <b>" + q + "</b> - <A href='javascript:showAllInMap()'>Show All in Map</A> or <A href='javascript:document.location.reload()'>Search Again</A>");
	else setStatus("<b>No dealers found in your area</b> <A href='javascript:document.location.reload()'>Search Again</A>");
	
	hideWait();
}

function getDocumentHeight() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}



function getDocumentWidth() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}
