// ############################################################################
// map_funcs.js -- universal map methods/objects
// ============================================================================
// CREATED BY:	Zander Waldman -- zwaldman@organic.com
//			Organic Det
//
// CREATED ON: 08/27/06
// ############################################################################

// IE hack for directions ************ Necessary to include
if (document.namespaces) { // only exists in IE, only needed in IE
    document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
}

	// ======================================================
	// showMenu() - animation for select menus
	// ======================================================
	function showMenu(whichMenu) {
		
		// collapse all open menus
		collapseMenus();
		
		// create slider object to menu
		mySlider = new Fx.Style($(whichMenu), 'height',{duration:500});
		
		// get the height of the child contents
		var childHeight = $(whichMenu).getFirst().getStyle('height').toInt();
		
		// if the height of the box is already larger then 1 we need to collapse
		if($(whichMenu).getStyle('height').toInt() >= 1) {
			
			// collapse menu and remove the overflow
			mySlider.start($(whichMenu).getStyle('height').toInt(), 0);
			$(whichMenu).setStyle('overflow','hidden');
			
		// we need to open menu
		} else {
			
			// if the child height is less the our max height we can show full box
			if(childHeight <= 200) {
			
				mySlider.start($(whichMenu).getStyle('height').toInt(), childHeight);
			
			// otherwise we need to set to a max height and show a scrollbar
			} else {
				mySlider.start($(whichMenu).getStyle('height').toInt(), 200);
				$(whichMenu).setStyle('overflow','auto');
			} 
		}
	}
	
	// ======================================================
	// collapseMenus() - collapse all
	// ======================================================
	function collapseMenus() {
		
		// get list of menus
		var menuList = $$('div.select-list');
		
		// loop on all fo them
		for(var i = 0; i < menuList.length; i++) {
			
			// if any are open
			if(menuList[i].getStyle('height').toInt() >= 1) {
				
				// call show menu to close it
				//showMenu(menuList[i].getAttribute('id'));
				mySlider = new Fx.Style($(menuList[i].getAttribute('id')), 'height',{duration:500});
				// collapse menu and remove the overflow
				mySlider.start($(menuList[i].getAttribute('id')).getStyle('height').toInt(), 0);
				$(menuList[i].getAttribute('id')).setStyle('overflow','hidden');
			}
		}
		
	}
	
	// ======================================================
	// showInfo() - 
	// ======================================================
	function showInfo(id) {
		markerArray[id].showDetailWin();
	}
	
	// ======================================================
	// plotPoint() - plot point on map
	// ======================================================
	function plotPoint(upfitter) {
		
		
		// create point
		var point = new GLatLng(parseFloat(Number(upfitter.lat)),	parseFloat(Number(upfitter.longitude)));
		
		// add new marker
		marker = new PdMarker(point, icon);
	
		// creat the html contents
		createInfoWindowContents(upfitter, marker);
		
		// add overlay to map
		map.addOverlay(marker);
		
		// push ino array for clean up later
		markerArray.push(marker);
		
		// zoom to markers
		map.zoomToMarkers();
		
		if(map.getZoom() > 14) map.setZoom(14);
	
	}
	
	// ======================================================
	// toggleToFrom() -
	// ======================================================
	function toggleToFrom(element) {
		
		if(element == "to-here") {
			linkTrack("map", "to-here");
			$('address-title').setText('Start Address');
			$('to-here').setProperty('class', 'off');
			$('from-here').setProperty('class', 'on');
		} else {
			linkTrack("map", "from-here");
			$('address-title').setText('End Address');
			$('to-here').setProperty('class', 'on');
			$('from-here').setProperty('class', 'off');
		}
		
	}
	
	// ======================================================
	// getDirections -
	// ======================================================
	function getDirections(start, end) {
		linkTrack("map", "enter_directions");
		if(start != "Enter Address" && start != "") {
			if($('address-title').getText() == 'Start Address') {
			
				directions.load("from " + start + " to " + end);
				
			} else {
				
				directions.load("from " + end + " to " + start)
				
			}
		}
	}
	
	// ======================================================
	// handleErrors - handles imporper directions calls
	// ======================================================
	function handleErrors() {
		  if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		  if($('error') == undefined) {
		  	var error = new Element('span', {'id': 'error'}).injectInside($('directions-wrapper'));
			error.setHTML("Please Try Again. The address you entered can not be found, this may be due to the fact that the address is relatively new, or it may be incorrect."); 
			
		  }
                //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.\nError code: " + directions.getStatus().code);
        		//	else if (directions.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.\n Error code: " + directions.getStatus().code);
       		 //	else if (directions.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.\n Error code: " + directions.getStatus().code);
        		//else if (directions.getStatus().code == G_GEO_BAD_KEY)
               // alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
        		//	else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
      		//          alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
       		// else alert("An unknown error occurred.");  
	
	} 
	
	// ======================================================
	// onGDirectionsLoad - success
	// ======================================================
	function onGDirectionsLoad() {
		clearInterval(intervalID);
		$('directions').setStyle('display', 'none');
		clearPoints();
		map.enableDragging();
		intervalID = setInterval(checkDirections, 1000);
	}
	
	// ======================================================
	// checkDirections() -
	// ======================================================
	function checkDirections() {
		
		if($('directions').getFirst() != null) {
			clearInterval(intervalID);
			var directionsElement = $('directions').getFirst().getFirst().getFirst().getFirst().getNext();
			if(mapType == "upfitters") {
				directionsElement.setStyles('overflow: auto; height: 320px; padding-right: 5px;');
			} else {
				directionsElement.setStyles('overflow: auto; height: 140px; padding-right: 5px;');
			}
			$$('table').setStyle('border', 'none');
			$('results-box').setStyle('display', 'none');
			$('directions').setStyle('display', 'block');
			$('back-print-box').setStyle('display', 'block');
			$('directions').getFirst().getFirst().getFirst().setStyles('border-top: solid 1px #333; border-bottom: solid 1px #333;');
			$('directions').getFirst().getFirst().getFirst().getFirst().setStyles('border-bottom: solid 1px #333; margin: 0 0 5px 0; padding: 0;');
			$('directions').getFirst().getFirst().getFirst().getNext().getFirst().setStyles('border-bottom: solid 1px #333; margin: 0; padding: 0;');
			
		}
		
	}
	
	// ======================================================
	// focusForm() - focusForm
	// ======================================================
	function focusForm(form) {
		form.focus();
		if(form.value == "Enter Address") form.value = "";
	}
	
	// ======================================================
	// focusForm() - focusForm
	// ======================================================
	function focusAllForm(form) {
		form.focus();
		form.select();
	}
	
	// ======================================================
	// printDirections() - 
	// ======================================================
	function printDirections() {

	  var directionsObject = $('directions').clone();
	  directionsObject.getFirst().getFirst().getFirst().getFirst().getNext().setStyles('overflow: visible; height: auto;');
	  directionsObject = directionsObject.innerHTML;
	  link = "about:blank";
	  var pw = window.open(link, "_new");
	  pw.document.open();
	  pw.document.write(makepage(directionsObject));
	  pw.document.close();
		
	}
	
	function makepage(src) {
  // We break the closing script tag in half to prevent
  // the HTML parser from seeing it as a part of
  // the *main* page.

		return "<html>\n" +
	    "<head>\n" +
	    "<title>Temporary Printing Window</title>\n" +
	    "<scr" + "ipt language=\"JavaScript\" type=\"text/javascript\" src=\"/shared/javascripts/mootools.js\"></scr" + "ipt>" +
	    "<script>\n" +
	  "function step1() {\n" +
	   // " var myDiv = " + src +";" +
	  // "myDiv.injectInside($('temp'));" +
	    "  setTimeout('step2()', 10);\n" +
	    "}\n" +
	    "function step2() {\n" +
	    "  window.print();\n" +
	   "  window.close();\n" +
	    "}\n" +
	    "</scr" + "ipt>\n" +
	    "</head>\n" +
	    "<body id=\"temp\" onLoad='step1()'>\n" +
	    src +
	    "</body>\n" +
	    "</html>\n";
	}
	
	// ======================================================
	// clearPoints() - clean points
	// ======================================================
	function clearPoints() {
		
		// loop through and clean points up
		for(var i=0; i<markerArray.length; i++) {
			
			markerArray[i].remove();
			
		}
		
		markerArray = new Array();
		
	}
	
	// ======================================================
	// emptySelect() - clean select list
	// ======================================================
	function emptySelectList(selectList) {
		
		// the array of li's
		var optionList = $$("#" +selectList +" li");
		
		// set opacity back disabled
		$(selectList).getParent().getPrevious().setOpacity(0.5);
		//$(selectList).getParent().getPrevious().setProperties({onmouseover: '',onmouseout: ''});
		
		// get the span with default data and set the text back to original
		var span = $(selectList).getParent().getPrevious().getPrevious();
		span.setStyle('display', 'block');
		span.getNext().getFirst().setText(span.getText());
		span.setStyle('display', 'none');

		// remove li's
		for(var i = 0; i < optionList.length; i++) {
			optionList[i].remove();
		}
		
	}
	
	// ======================================================
	// rollMe() - action behavior for select list
	// ======================================================
	function rollMe(element) {
		
		if($(element.id).getStyle('opacity') == 1) {
			$(element.id).toggleClass('hover');
			$(element.id).getFirst().toggleClass('hover');
			$(element.id).getFirst().getNext().toggleClass('hover');
		}
		
	}
	
	// ======================================================
	// swapView() -
	// ======================================================
	function swapView() {
		
		directions.clear();
		$('directions').setStyle('display', 'none');
		$('results-box').setStyle('display', 'block');
		$('back-print-box').setStyle('display', 'none');
		if(resultsArray.length >= 1) {
			showResults();
		}
		
		
	}