/*	*******************************************************	*/
/*	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 = '';

		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 using mapPinYP
			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());
	}

/*	*******************************************************	*/
/*	Loads Virtual Earth Map - straight from VE SDK			*/
/*	******************************************************* */
	function GetMap( mapDiv ) {
		map = new VEMap( mapDiv );
		map.LoadMap();
	}

	/*	*******************************************************	*/
	/*	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( '.address' ) ) {
				fullAddress += result.down( '.address' ) != null ? result.down( '.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 = '/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;
		var end = address.replace("<br/>"," ");
		end = address.replace("<br/>"," ");

		if( address != '' ) {
			description += "<div style=\"padding: 8px;\"></div>";
			description += "<form action=\"/sp?\">";
			description +=  "<input type=\"hidden\" name=\"directions\" value=\"true\" />";
			description += 	"<input type=\"hidden\" name=\"aff\" value=\"9\" />";
			description +=  "<input type=\"hidden\" name=\"section\" value=\"map\" />";
			description += 	"<input type=\"hidden\" name=\"siteId\" value=\"" + siteId + "\" />";
			description +=  "<input type=\"hidden\" name=\"wId\" value=\"" + siteId + "\" />";
			description += 	"<input type=\"hidden\" name=\"skin\" value=\"" + skin + "\" />";
			description += 	"<input type=\"hidden\" name=\"end\" value=\"" + end + "\" />";			
			description += 	"<input type=\"hidden\" name=\"show\" value=\"directions\" />";			
			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=\"start\" id=\"startingAddress" + resultNum + "\" 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 directions;

	function getDirectionsMap(){
		form = $('directions');
		startAddy = form['start'];
		endAddy = form['end'];

		// 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 = '';
		if ( $F(startAddy) == $F(endAddy) ) {
			var marker = new GMarker( new GLatLng(lat,lng) );
			map.addOverlay(marker);
		} else {
			directions = new GDirections(map, directionsPanel);
			var dirString = "from: "+$F(startAddy)+" to: "+$F(endAddy);
			directions.load( dirString );
		}
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
	}

	function swapEndPoints() {
		form = $('directions');
		startAddy = form['start'];
		endAddy = form['end'];
		activeDirection = form['toorfrom'];
		startPoint = $F(startAddy);
		startPointTxt = $('user-address').innerHTML;
		tempEndPoint = $F(endAddy);
		tempEndPointTxt = $('pd-business-address').innerHTML;


		if($F(activeDirection) == 'fromLink1') {
			newDirection = 'toLink1';
		} else if($F(activeDirection) == 'toLink1') {
			newDirection = 'fromLink1';
		}

		$(activeDirection).value = newDirection;
		$(endAddy).value = startPoint;
		$(startAddy).value = tempEndPoint;
		$('user-address').innerHTML = tempEndPointTxt;
		$('pd-business-address').innerHTML = startPointTxt;
	}

	function updateLocations() {
		$('user-addy').update($F('startingAddress1'));
		$('user-addy').innerHTML;
		$('pd-business-addy').update($F('endingAddress1'));
		$('pd-business-addy').innerHTML;
	}

	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));
	}