var map = null;
var miniMap = null;
var loadStart = false;
var miniMap;
var points;
var bounds;
var ie6 = false;

// Check for IE6
if(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1)
//if(true)
{
	ie6 = true;
	
	try{
		// Upload CSS just for IE6
		var head = document.getElementsByTagName("head")[0];
		var style1 = document.createElement('link');
		style1.id = 'ie6_maptool';
		style1.type = 'text/css';
		style1.rel = 'stylesheet';
		style1.href = "css/ie6_maptools.css";
		head.appendChild(style1);
		
		// Put iframe inside div
		pushIframe('map_tools_slider');
		
	}catch(e)
	{
		alert("IE loading css: "+e.message);	
	}
}

// ONLY FOR IE6
function pushIframe(elID)
{
	var el = document.getElementById(elID);
	if( !el )
		setTimeout( function(){ pushIframe(elID) }, 200 ); // <-- Recursive call
	else
	{
		el.parentNode.style.width = '980px';
		el.parentNode.style.height = '515px';
		el.parentNode.style.overflow = 'hidden';
		el.className += ' selectFree';
		el.innerHTML += '<iframe></iframe>';
	}
}

function triggerMap()
{	
	if( !loadStart ){
		loadJS();
		setJQEvents();
	}
}

// Load Map Tools JS package only if they want to use map
function loadJS(){
	if( !loadStart )	{
		/* Load JS Files specific for this CFM page. */
		/* ----------------------------------------- */
		var head = document.getElementsByTagName("head")[0];  
		
		var script2 = document.createElement('script');
		script2.id = 'map_tools_JQ';
		script2.type = 'text/javascript';
		script2.src = "http://www.har.com/js/jquery.js";
		head.appendChild(script2);
		
		var script3 = document.createElement('script');
		script3.id = 'map_tools_LIBRARY';
		script3.type = 'text/javascript';
		script3.src = "/map_tools_library/map_tools.js";
		head.appendChild(script3);
		
		var script = document.createElement('script');
		script.id = 'har_google_api';
		script.type = 'text/javascript';
		script.src = "http://www.har.com/js/googleMap.js";
		head.appendChild(script);
		
		// Ok Loading has started
		loadStart = true;
	}
}

// This function will set all the JQ events
function setJQEvents(){
	
	if( typeof HAR != "undefined" )
	{
		// Set JQ Events: only when script have finished loading
		HAR.initialize({streetViewControl:false,mapTypeControlStyle:"DROPDOWN_MENU",callback:function(){
			// Register Map Tool Events
			mapToolsEvents();
			
			$("#map_tools_trigger").click(slideMap);
		
			// CHOOSE HOW TO CLOSE "MAP" IN YOUR IMPLEMENTATION 
			$('.closeMain').click(function(){ 
				// Check to see if you have any map options selected
				if(document.getElementById("map_tools_searchtype").value=='') 
					resetMapTools();
				else
				{
					// Create miniMap
					loadMiniMap();
					// Clear location Form
					fnClearLocation(document.forms['frmSearch']);
					// Finally Slide map to reveal the magic!
					slideMap();
				}
			});
			// END - CHOOSE HOW TO CLOSE "MAP" IN YOUR IMPLEMENTATION 
			
			// This is a one time occurance
			slideMap();
			
		}});// END Intialize Google Map
		
	}
	else
		setTimeout( setJQEvents, 100 );
	
}
// Create a mini map that will display the map tools criteria
function loadMiniMap()
{
	// Load the Mini Map
	var miniMap = new googleMapping();
	miniMap.initialize({domElement:"miniMap",navigationControl:false,scrollwheel:false,mapTypeControl:false,scaleControl:false,streetViewControl:false,draggable:false});
	
	try{
	// Show different centers depending on search type selected previously
	switch( document.getElementById("map_tools_searchtype").value )
	{
		case 'zip':
			// Finds the Zip Code and re-centers the map.
			var geo = new google.maps.Geocoder();
			geo.geocode( {address:document.getElementById("map_tools_zip_code").value}, function(resultsArray, status){
							var res = resultsArray[0];
							
							// Make sure status returned without problems
							if( status = google.maps.GeocoderStatus.OK )
							{
								// Change Icon SetTitle
								var info_str = Array();
								for(var key in res.address_components) 
									info_str.push(res.address_components[key].long_name);
								// Trim the last 
								
								var loc = res.geometry.location;
								miniMap.plotPin({
										lat: loc.lat(),
										lng: loc.lng(),
										pinIcon: HAR.pins.greenArrow,
										title: info_str.toString()
									});
								// Center/Zoom the map
								miniMap.map.setCenter( new google.maps.LatLng( loc.lat(),loc.lng() ) );
								miniMap.map.setZoom(13);
														
							}
					  });
			break;
		case 'draw':
				// Draw uses the same technique as navigate
		case 'navigate':
				// Gather the 4 corners being used for navigate/draw feature
				// and add that shape to the miniMap
				bounds=	{
							TopLeftLatLong: new google.maps.LatLng(parseFloat(document.getElementById("map_tools_nwlat").value),parseFloat(document.getElementById("map_tools_nwlng").value)),
							TopRightLatLong: new google.maps.LatLng(parseFloat(document.getElementById("map_tools_nwlat").value),parseFloat(document.getElementById("map_tools_selng").value)),
							BottomRightLatLong: new google.maps.LatLng(parseFloat(document.getElementById("map_tools_selat").value),parseFloat(document.getElementById("map_tools_selng").value)),
							BottomLeftLatLong: new google.maps.LatLng(parseFloat(document.getElementById("map_tools_selat").value),parseFloat(document.getElementById("map_tools_nwlng").value))
						};
				points = new google.maps.MVCArray( [bounds.TopLeftLatLong, bounds.TopRightLatLong, bounds.BottomRightLatLong, bounds.BottomLeftLatLong] );
				miniMap.drawPolyFromMVCArray(points,true);
				
			break;
	}
	}catch(e){/*alert("MiniMap: "+e.message);*/}
}
// Sliding Map Toggle
function slideMap(){
	// Toggle Sliding left and right
	var $lefty = $("#map_tools_slider");
	
	$lefty.animate({ left: parseInt($lefty.css('left'),10) == 0 ? -760:0 },"slow");
	if( parseInt($lefty.css('left'),10) == 0)
	{
		
		// Display Map area
		$("#map_tool_header_txt").animate({ left: 830 },"fast");
		$("#mapWrapper").hide();
		$("#miniMapCover").show();
		$lefty.css('height', '360px');
	}
	else
	{
		// Show minimap section
		$("#map_tool_header_txt").animate({ left: 450 },"fast");
		$("#mapWrapper").show();
		$("#miniMapCover").hide();
	}

}

// Totally Hide the Map
function resetMapTools(){
	// Hide the sliding Map Wrapper
	var $lefty = $("#map_tools_slider");
	$lefty.animate({ left: -980 },"slow", function(){
		
			// RESET MAP MENUS
			$("#mapWrapper").show(); /* <--- Prevents IE BUG <--- */
			HAR.clearMap();
			$("#myControl").show();
			$(".minicontrol").hide();	
			
			// Reset Fields
			resetFields();
		
		});
}
