// JavaScript Document
var map;
var bounds = new google.maps.LatLngBounds();
var count = 5;
var home;
var openInfo;
var locations = new Array();
var closest = 5000;
var counter = 0;
var phoneNumber = "1-866-732-1682";
var offer = "standard";

//var killFlash = 0;

function reinitMap() {
//alert('reinitVars');
count = 5;
locations = new Array();
closest = 5000;
counter = 0;
$('#locations').html('');
$('#map_canvis').html('');

}

$.fn.idle = function(time)
  {
      var o = $(this);
      o.queue(function()
      {
         var t = setTimeout(function()
         {
            o.dequeue();
			clearTimeout(t);
         }, time);
      });
      return this;
}

$(function(){
		   
	locations = new Array();
	
	$('#search input').change(function(){
		$('form .error').html('');
	});
	$('#search').submit(function(){
//	$('#search').submit(function(){
								 
		$('form .error').html('');
		if(counter > 0) return false;
		counter ++;
		var zip = $('input[name="zip"]').val();
//		$('input.submit').attr('disabled','disabled');
		
				if(zip){
					if(offer == "businessPlus"){
						ziptrack = 's9zip408;u3=' + zip;
						};
					if(offer == "standard"){
						ziptrack = 's9zip908;u3=' + zip;
						};
					clicktrack(null, 'zipCode', ziptrack);
					//clicktrack(null, 'zipCode', 's9zip908');
					$('#search input[name="zip"]').css('background', 'url(/images/loader.gif) no-repeat 132px center');	
					$('#search input[name="zip"]').css('background-color', '#fff');			
					bounds = new google.maps.LatLngBounds();
					count = 5;
					geolocate(zip, true);
				}else{
					counter = 0;
					$('#search input[name="zip"]').css('background', 'none');	
					$('#search input[name="zip"]').css('background-color', '#fff');	
					$('form .error').html('Please enter a valid zip code.').fadeIn();
				}
				
			return false;
	});

});

function passed(href, targetval){

	linkpass++;
	if(linkpass > 1){
		linkpass = 0;
		if(targetval == "_blank"){ window.open(href, 'new');}
		else{
		setTimeout(function(){document.location = href}, 1000);
		}
	}
}
var linkpass = 0;

function buildmap(coordinates, zip){

	home = coordinates;
	var myOptions = {
		mapTypeControl: false,
		backgroundColor: '#ffffff',
	    mapTypeId: google.maps.MapTypeId.ROADMAP
    };


	var zip = zip;
	$.get('transport.php', {action:'ziplocate', zipcode:zip}, function(data){
		var total = 0;
		for(each in data) total++;
		if(total > 1){

overlay('#searchPopup');

if(offer == "standard"){
	clicktrack(null, null, null, 'f4ban685', 'mapModal');
	};
	
if(offer == "businessPlus"){
	clicktrack(null, null, null, 'fb4ba346', 'mapModal');
	};

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
					$('#search input[name="zip"]').css('background', 'none');	
					$('#search input[name="zip"]').css('background-color', '#fff');	

			for(each in data) geolocate(data[each], false);
		}			
		
		else {
				//$('#search input').css('background', 'none');
				$('#search input[name="zip"]').css('background', 'none');	
				$('#search input[name="zip"]').css('background-color', '#fff');	
				$('form .error').html('No locations were found within 25 miles of your zip code.').fadeIn();
				//$('input.submit').attr('disabled','');
				locations = new Array();
				counter = 0;
					
			}
	},'json');		
}
function geolocate(place, center){

	var coordinates = new Object();
	if(center){
		query = place;
		method = buildmap;
	}else{
		query = place.street1+','+place.city+','+place.state;
		method = addmarker;
		var contentString = place.street1+'<br/>'+
			place.city+', '+place.state+'<br/>'+
	 		'<a target="_blank" href="http://maps.google.com/maps?&q='+query+'&pw=2">Print</a> <a target="_blank" href="http://maps.google.com/maps?&q='+query+'&f=d">Get Directions</a>';
			//place.phone;
		var infowindow = new google.maps.InfoWindow({
			content: contentString
		});
		place.window = infowindow;
		
	}
	$.get('transport.php', {action:'geolocate', q:query}, function(geolocation){
			if(typeof(geolocation.Placemark)!='undefined'){
				
				method(({latitude:geolocation.Placemark[0].Point.coordinates[1], longitude:geolocation.Placemark[0].Point.coordinates[0]}), place);
								
			}else{
			 	$('#search input[name="zip"]').css('background', 'none');	
				$('#search input[name="zip"]').css('background-color', '#fff');	
			 	$('form .error').html('Please enter a valid zip code.').fadeIn();
				locations = new Array();
				//$('input.submit').attr('disabled','');
				counter = 0;
			}				
	}, 'json');
	return coordinates;
	
}
Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
}
function addmarker(coordinates, target){

	// **obsolete client side distance calculation** //
	
	var R = 6371/1.609344; // km
	var dLat = (coordinates.latitude-home.latitude).toRad();
	var dLon = (coordinates.longitude-home.longitude).toRad(); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(home.latitude.toRad()) * Math.cos(coordinates.latitude.toRad()) * 
	        Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	
	if(d<closest)closest = d;
	
	// --------------------------------------------//
	
	var latlng = new google.maps.LatLng(coordinates.latitude, coordinates.longitude);
	switch(count){
		case 5:
			var icon = '/images/icon1.gif';
			break;
		case 4:
			var icon = '/images/icon2.gif';
			break;
		case 3:
			var icon = '/images/icon3.gif';
			break;
		case 2:
			var icon = '/images/icon4.gif';
			break;
		case 1:
			var icon = '/images/icon5.gif';
			break;
	}
	var marker = new google.maps.Marker({
	      position: latlng, 
	      icon: icon,
		  map: map
		  
	});
	target.marker = marker;
	google.maps.event.addListener(marker, 'click', function(){
		if(openInfo){
			openInfo.close();
		}
	  	target.window.open(map,marker);
		openInfo = target.window;
	});
	locations.push(target);
	bounds.extend(marker.getPosition());
	count--;
	if(!count && closest < 25){
		//$('#locations').html(locationlist);
		for(i=0; i<locations.length; i++){
			//var item = $('#locations').append('<li><img src="images/icon'+[i]+'.gif">'+locations[i].window.content+'</li>').children('li:last-child').click(function(){
			var item = $('#locations').append('<li>'+locations[i].window.content+'</li>').children('li:last-child').click(function(){
				if(openInfo){
					openInfo.close();
				}
				$(this).data('popup').open(map, $(this).data('marker'));
				openInfo = $(this).data('popup');
				//locations[i].window.open();
			}).data('popup', locations[i].window).data('marker', locations[i].marker);
		}
		$('#locations li(not:last-child) a').click(function(){window.open($(this).attr('href'),'print','toolbar=false,width=730,height=820,scrollbars=false'); return false;});
		$('#locations').append('<li>For more information call '+phoneNumber+'</li>');
		$('#locations li:last-child').css('cursor','default');
		var latlng = new google.maps.LatLng(home.latitude, home.longitude);
		var image = "http://maps.google.com/mapfiles/kml/pal3/icon48.png";
		var currentzip = new google.maps.Marker({
		      position: latlng, 
		      map: map,
			  icon: image
		});
		bounds.extend(currentzip.getPosition());
		map.setCenter(bounds.getCenter());
		map.fitBounds(bounds);
		

	}else if(closest > 25){
		$('#search input[name="zip"]').css('background', 'none');	
		$('#search input[name="zip"]').css('background-color', '#fff');	
		$('form .error').html('No locations were found within 25 miles of your zip code').fadeIn();
		locations = new Array();
		//$('input.submit').attr('disabled','');
		counter = 0;
	}
}

