/*	*******************************************************	*/
/*	Identifies the beginning and end of the map pin loop	*/
/*	Used for full & detail page								*/
/*	Once it identifes the start and end then kicks off map	*/
/*	******************************************************* */
	function getMapLoadVariables( mapDiv ) {
		// alert('loading map variables...');
		var resultStartNum = $$( 'abbr.resultStartNum' ).first() != null ? $$( 'abbr.resultStartNum' ).first().title : null;
		var resultEndNum = $$( 'abbr.resultEndNum' ).first() != null ? $$( 'abbr.resultEndNum' ).first().title : null;
		var searchKey = $$( 'abbr.searchKey' ).first() != null ? $$( 'abbr.searchKey' ).first().title : null;
		var skin = $$( 'abbr.skin' ).first() != null ? $$( 'abbr.skin' ).first().title : null;

		var debug = debug+'resultStartNum:'+resultStartNum+'\n';
		debug = debug+'resultEndNum:'+resultEndNum+'\n';
		debug = debug+'searchKey:'+searchKey+'\n';
		debug = debug+'skin:'+skin+'\n';
		debug = debug+'mapDiv:'+mapDiv+'\n';
		// alert(debug);

		if( resultStartNum && resultEndNum && searchKey ) {
			lowProMapLoad( resultStartNum, resultEndNum, searchKey, skin, mapDiv );
		}
	}

/*	******************************************************* */
/*	Gets map, builds pin array, and loops through results	*/
/*	to create pushpins & then sets map zoom & centers		*/
/*	******************************************************* */
	function lowProMapLoad( sNum, numResults, searchKey, skin, mapDiv ) {
		map = new GMap2( $(mapDiv) );

		var pins = new Array;
		var pinIndex = 0;

		var resultNum = null;
		var title = null;
		var address = null;
		var lat = null;
		var lng = null;
		var img = null;
		var score = null;
		var ypDirAff = null;
		var userLoc = null;
		var siteId = null;

		var test = $('mapDebug') == null ? false : true;

		var debug = '';

		// skip walking the dom to find pins if we already have items in the
		// pdLatLong and pdMarkers arrays
		if ( pdLatLongs.length == 0 || pdMarkers.length == 0 ) {

			for ( var i = numResults; i >= sNum; i-- ) {
				resultNum = i;

				var result = $( searchKey + '-result-' + i.toString() ); // specify from which result li to retrieve data

				if( mapDiv == 'myMoreInfoMap' ){
					title = result.down( '.fn' ) != null ? result.down( '.fn' ).innerHTML : '';
				} else if( mapDiv == 'myMap' ) {
					title = result.down( '.title-url' ) != null ? result.down( '.title-url' ).title : '';
				}

				address = buildAddr( result ); // builds out address
				debug = debug + 'address:'+address+'\n';
				lat = result.down( '.lat' ) != null ? result.down( '.lat' ).title : '';
				debug = debug + 'lat:'+lat+'\n';
				lng = result.down( '.lng' ) != null ? result.down( '.lng' ).title : '';
				debug = debug + 'lng:'+lng+'\n';
				score = result.down( '.score' ) != null ? result.down( '.score' ).title : '';
				debug = debug + 'score:'+score+'\n';
				siteId = result.down( '.siteId' ) != null ? result.down( '.siteId' ).title : '';
				debug = debug + 'siteId:'+siteId+'\n';
				ypDirAff = result.down( '.ypDirAff' ) != null ? result.down( '.ypDirAff' ).title : '';
				debug = debug + 'ypDirAff:'+ypDirAff+'\n';

				// Logic to determine what page we're on to know what image to pull
				if( mapDiv == 'myMap' ) {
					img = result.down( '.logo' ) != null ? result.down( '.logo' ).src : '';
				} else if( mapDiv == 'myMoreInfoMap' ) {
					img = result.down( '.logo' ) != null ? result.down( '.logo' ).src : '';
				}
				debug = debug + 'img:'+img+'\n';
				//userLoc = result.down( '.userLoc' ) != null ? result.down( '.userLoc' ).title : '';

				//alert(debug);

				pins = AddPushpin( resultNum, title, address, lat, lng, img, score, 'false', siteId, skin, pins, pinIndex, ypDirAff );
				if (test) {
					debugMap( resultNum, title, address, lat, lng, img, score, 'false', siteId, skin, pins, pinIndex, ypDirAff );
				}

				pinIndex++;
			}
		}

		fitMap( map, pdLatLongs );
		addMarkers( map, pdMarkers );
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
	}

/*	*******************************************************	*/
/*	Concatenates all address pieces as they are in separate	*/
/*	html blocks. returns a string of the full address		*/
/*	******************************************************* */
	function buildAddr( result ) {
		var fullAddress = '';

		if( result.down( '.street-address' ) ) {
			fullAddress += result.down( '.street-address' ) != null ? result.down( '.street-address' ).innerHTML + '<br/>': '';
		}
		if( result.down( '.extended-address' ) ) {
			fullAddress += result.down('.extended-address') != null ? result.down( '.extended-address' ).innerHTML + '<br/>' : '';
		}
		if( result.down( '.locality' ) ) {
			fullAddress += result.down('.locality') != null ? result.down( '.locality' ).innerHTML + ', ': '';
		}
		if( result.down( '.region' ) ) {
			fullAddress += result.down( '.region' ) != null ? result.down( '.region' ).innerHTML + ', ': '';
		}
		if( result.down( '.postal-code' ) ) {
			fullAddress += result.down( '.postal-code' ) != null ? result.down( '.postal-code' ).innerHTML: '';
		}

		return fullAddress;
	}


/*	*******************************************************	*/
/*	Creates pushpins & pop-up details - 					*/
/*	******************************************************* */
	function AddPushpin( resultNum, title, address, lat, lng, img, score, userLoc, siteId, skin, pins, pinIndex, ypDirAff ) {

	  	var latlong = new GLatLng(lat,lng);
	  	pdLatLongs.push( latlong );

		var icon;
		icon = new GIcon(G_DEFAULT_ICON);
		if ( resultNum < 100 ) {
			icon.image = '/sf_modules/yp/images/markers/marker'+resultNum+'.png';
		}
		var toolTipTitle = resultNum+': '+title.replace(/<.*?>/gi,'');
	  	var marker = new GMarker( latlong, { title:toolTipTitle, icon:icon } );
	  	var infoHtml = buildTitle( resultNum, title, img ) + buildDescription( address, resultNum, siteId, skin, ypDirAff );
	  	marker.bindInfoWindow( infoHtml, { maxWidth:150 });
	  	pdMarkers.push( marker );

		return pins;
	}

/*	*******************************************************	*/
/*	Builds title for html Pop-up for pushpin				*/
/*	******************************************************* */
	function buildTitle( resultNum, title, img ) {
		var siteTitle = '';

		//if( img != '' ) {
		//	siteTitle += '<div align="center" style="padding: 0px 0px 10px;"><img src="' + img + '"/></div>';
		//}

		if( title != '' ) {
			siteTitle += '<div><b>' + resultNum + '. ' + title + '</b></div>';
		}

		return siteTitle;
	}

/*	*******************************************************	*/
/*	Builds description for html Pop-up for pushpin			*/
/*	******************************************************* */
	function buildDescription( address, resultNum, siteId, skin, ypDirAff ) {
		var description = address;

		if( address != '' ) {
			description += "<div style=\"padding: 8px;\"></div>";
			description += "<form action=\"/sp?\" name=\"frmMapDirections\">";
			description += 	"<input type=\"hidden\" name=\"aff\" value=\"" + ypDirAff + "\"/>";
			description += 	"<input type=\"hidden\" name=\"siteId\" value=\"" + siteId + "\" />";
			description += 	"<input type=\"hidden\" name=\"skin\" value=\"" + skin + "\" />";
			description += 	"<b>Directions</b>";
			description += 	"<div style=\"padding: 3px;\"></div>";
			description += 	"<div id=\"dirTo" + resultNum + "\" style=\"display:block;\">";
			description += 		"Starting Point: <div style=\"padding: 3px;\"></div>";
			description += 		"<input type=\"text\" name=\"begin\" value=\"\" size=\"20\"/>";
			description += 		"<div align=\"center\" style=\"padding: 5px 0 0 0;\">";
			description += 			"<input type=\"submit\" value=\"Get Directions\"/>";
			description += 		"</div>";
			description +=	"</div>";
			description += "</form>";
		}

		return description;
	}


/*	*******************************************************	*/
/*	Adds debug code for mapping pins in mapDebug div		*/
/*	******************************************************* */
	function debugMap( resultNum, title, address, lat, lng, img, score, userLoc, siteId, skin, pins, pinIndex ){
		var element = '<p>result number = ' + resultNum + '<br/>title = ' + title + '<br/>address = ' + address + '<br/>latitude = ' + lat + '<br/>longitude = ' + lng + '<br/>score = ' + score + '<br/>siteId = ' + siteId + '<br/>skin = ' + skin + '<br/>pin index = ' + pinIndex + '</p><br/>';
		$( 'mapDebug' ).innerHTML += element;
	}



// ****************************************************************************************************** //
// ********************************* Javascript for Driving Directions ********************************** //
// ****************************************************************************************************** //
	var map 			= null;
	var form 			= null;
	var startAddy 		= null;
	var endAddy 		= null;
	var startPoint 		= null;
	var tempEndPoint 	= null;
	var tempEndPointTxt = null;
	var legs			= null;
	var leg				= null;
	var pdLatLongs      = new Array();
	var pdMarkers       = new Array();
	var gdir;

	function getDirectionsMap(){
		form = $('directions');
		startAddy = form['begin'];
		endAddy = form['end'];

		if (startAddy.value.strip()=='') {
			alert('Please provide a starting address.');
			$('myDirectionsMap').update('');
			return;
		}

		// get initial lat and lng
		var lat = $$('.lat').first().title;
		var lng = $$('.lng').first().title;

		// alert('getting directions map...');
		map = new GMap2($('myDirectionsMap'));
		map.setCenter(new GLatLng(lat,lng), 15);

		directionsPanel = document.getElementById("myRoute");
		directionsPanel.innerHTML = '';
		var startAddyValue = $F(startAddy);
		var endAddyValue = $F(endAddy);
		if ( startAddyValue == endAddyValue ) {
			var marker = new GMarker( new GLatLng(lat,lng) );
			map.addOverlay(marker);
		} else {
			gdir = new GDirections(map, directionsPanel);
			GEvent.addListener(gdir, "error", handleDirectionErrors);
			var dirString = "from: " + startAddyValue + " to: " + endAddyValue;
			gdir.load( dirString );
		}
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
	}

	function swapEndPoints() {
		form = $('directions');
		startAddy = form['begin'];
		endAddy = form['end'];

		startPoint = $F(startAddy);
		startPointTxt = $('user-address').innerHTML;
		tempEndPoint = $F(endAddy);
		tempEndPointTxt = $('pd-business-address').innerHTML;

		$(endAddy).value = startPoint;
		$(startAddy).value = tempEndPoint;
		$('user-address').innerHTML = tempEndPointTxt;
		$('pd-business-address').innerHTML = startPointTxt;
	}

	function updateLocations() {
		form = $('directions');
		startAddy = form['begin'];
		endAddy = form['end'];

		$('user-address').update($F(startAddy));
		$('pd-business-address').update($F(endAddy));
	}

	function editStart(toggle) {
		if (toggle == 'show') {
			$('dirFrom1').removeClassName('hideme');
			$('user-address').addClassName('hideme');
			$('dirFromEdit').addClassName('hideme');
		} else if (toggle = 'hide') {
			$('dirFrom1').addClassName('hideme');
			$('user-address').removeClassName('hideme');
			$('dirFromEdit').removeClassName('hideme');
		}
	}

	function editEnd(toggle) {
		if (toggle == 'show') {
			$('dirTo1').removeClassName('hideme');
			$('pd-business-address').addClassName('hideme');
			$('dirToEdit').addClassName('hideme');
		} else if (toggle = 'hide') {
			$('dirTo1').addClassName('hideme');
			$('pd-business-address').removeClassName('hideme');
			$('dirToEdit').removeClassName('hideme');
		}
	}

	function onGotRoute(route) {
		// Unroll route
		legs         = route.RouteLegs;
		var turns    = "<p>Total Distance: " + route.Distance.toFixed(1) + " mi</p>\n<p>Total Time: " + secondsToMinutes(route.Time) + "</p>\n<ul>";
		var numTurns = 0;

		// Get intermediate legs
		for(var i = 0; i < legs.length; i++) {
			// Get this leg so we don't have to derefernce multiple times
			leg = legs[i];  // Leg is a VERouteLeg object

			// Unroll each intermediate leg
			var turn = null;  // The itinerary leg

			for(var j = 0; j < leg.Itinerary.Items.length; j ++) {
				turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
				numTurns++;
				turns += "<li onClick=\"zoomToPin(" + numTurns + ");\" class=\"route-step-item clearfix\"><span class=\"route-step-info\"><b class=\"route-step-number\" id=\"map-pin-" + numTurns + "\">" + numTurns + ".</b>\n" + turn.Text + " (" + turn.Distance.toFixed(1) + " mi)<br/>\n</span></li>\n";
			}
		}
		$('myRoute').update(turns.toString());
		$('myRoute').innerHTML;

		if ( map.GetZoomLevel() > 15 ) {
			map.SetZoomLevel( 15 );
		}
	}

	function secondsToMinutes(seconds) {
		var remainder = seconds % 60;
		var minutes = (seconds - remainder) / 60;
		var hours = 0;
		if (minutes > 60) {
			hours = minutesToHours(minutes);
		}
		if (hours != 0) {
			minutes = minutes % 60;
		} else {
			hours = "";
		}
		return hours + minutes + " minutes and " + remainder + " seconds.";
	}

	function minutesToHours(minutes) {
		var mRemainder = minutes % 60;
		var mHours = (minutes - mRemainder) / 60;

		return mHours + " hours ";
	}

	function zoomToPin(id) {
		var num = 0;
		while (num < leg.Itinerary.Items.length) {
			var pin = leg.Itinerary.Items[num];
			if (num == id) {
				map.SetCenterAndZoom(leg.Itinerary.Items[num].LatLong, 14);
				return;
			}
			num++;
		}
	}

	function debugDir( start, end, options ){
		var debug = '<p>start Address = ' + $F(start) + '<br/>end Address = ' + $F(end) + '<br/>route optimize = ' + options.RouteOptimize + '</p><br/>';
		$( 'dirDebug' ).innerHTML += debug;
	}

	/**
	* Returns the value of the selected radio button in the radio group, null if
	* none are selected, and false if the button group doesn't exist
	*
	* @param {radio Object} or {radio id} el
	* OR
	* @param {form Object} or {form id} el
	* @param {radio group name} radioGroup
	*/
	$RF = function(el, radioGroup) {
		if($(el).type && $(el).type.toLowerCase() == 'radio') {
			var radioGroup = $(el).name;
			var el = $(el).form;
		} else if ($(el).tagName.toLowerCase() != 'form') {
			return false;
		}
		var checked = $(el).getInputs('radio', radioGroup).find(
			function(re) {return re.checked;}
		);
		return (checked) ? $F(checked) : null;
	}

	function addMarkers( map, markers ) {
		for ( var i=0; i < markers.length; i++) {
			map.addOverlay(markers[i]);
		}
	}

	function fitMap( map, points ) {
	   var bounds = new GLatLngBounds();
	   for (var i=0; i< points.length; i++) {
	      bounds.extend(points[i]);
	   }
	   map.setCenter(bounds.getCenter());
	   map.setZoom(map.getBoundsZoomLevel(bounds));
	}

    function handleDirectionErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");

	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.");

	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.");

	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given.");

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.");

	   else alert("An unknown error occurred.");
	}
