$(document).ready(function(){
	var hideDelayTimer = null;
	var distance = 10;
	var time = 250;
	var hideDelay = 50;
	var beingShown = false;
	var shown = false;
	var shown = false;
		var geocoder = null;
	$("#gs-radius-select").selectbox();	

	geocoder = new GClientGeocoder();
  geocoder.setBaseCountryCode("US");
	category_box_start();
	
	function category_box_start(){
		if(backfrom == 1){
			if(typeof(selected_cats) !== 'undefined'){
				var catid = selected_cats;
		    var zipcode = $('#gs-zipcode-box').val();
		    var address = $('#gs-address-box').val();
		    var state = $('#gs-state-box').val();
		    var city = $('#gs-city-box').val();
		    if(zipcode || (state && city)){
		      geocoder.getLatLng((zipcode + " " + address + " " + state + " " + city),
		  		function(point) {
						if(point){
							$('#location-point').val(point);
							var formdetails = $("#user-selected-values").serialize();
		  	   		$('html, body').animate({scrollTop:0}, 'normal');
		 					$('body').css("overflow","hidden");
							$("#lightbox , #lightbox-overlay").show();
				    	$("#modalbox").hide();
							$.ajax({
								type: "POST",
							  url: "setsession.php",
							  cache: false,
							  data: formdetails,
								async: false,
							  success: function(html){
									if (window.innerHeight) {
										theHeight=window.innerHeight;
									}
									else if (document.documentElement && document.documentElement.clientHeight) {
										theHeight=document.documentElement.clientHeight;
									}
									else if (document.body) {
										theHeight=document.body.clientHeight;
									}
						    	$("#search-results-page, #search-results-page-content").css("height",(theHeight-250));
									$("#search-results").show();
									$("#search-results-page-content").empty().html('<img id="listing-loading-gif" src="graphic/listings/loadingAnimation.gif" />');
							   	$.post("ajaxcontent.php",{category_id: catid, pageno:pagenumber}, function(html){
							    	$("#search-results-page-content").html(html).jScrollPane({showArrows:true, scrollbarWidth:18, scrollbarMargin:0});
									});
							  }
							});			    	      		
						}else{
							$("#lightbox-overlay").css("filter","alpha(opacity=70)");
							$("#lightbox , #lightbox-overlay").show();
							$("#modalbox-center").html("<h3>" + zipcode + " " + state + " " + city + " not found</h3><p>Sorry, we cannot find your location. Please check the details of your location and try again.</p><div id=\"modalbox-center-button\"><input type=\"button\" class=\"modalbox-center-button-decline\" value=\"Okey, Let me check my details\" /></div>");
							$("#modalbox").fadeIn("normal");
				   		$('html, body').animate({scrollTop:0}, 'normal');
				   		$('body').css("overflow","hidden");
						}
		  		});
		    }
			}
		}
	};
			
 	document.onkeydown = function(e){ 
		if (e == null) {
  		keycode = event.keyCode; 
		} else {
  		keycode = e.which; 
  	} 
  	if(keycode == 27){
			$("#lightbox , #lightbox-overlay").fadeOut(300);
			$("#modalbox, #search-results").hide();
   		$('body').css("overflow-y","auto");
  	} 
  };
	
	$('.get-started-clickable').click(function() {
  	var trigger = $(this).parent();
    var info = $('.popup', trigger);
    if (beingShown || shown) {
      // don't trigger the animation again
      return;
    } else {
			// reset position of info box
			$('#get-started-categories-main ul li .popup').css('display', 'none');
			$('#get-started-categories-main ul li').css({'background-position' : 'top left'});
			beingShown = true;			
			info.css({ top: -130, left: -33, display: 'block'}).animate({top: '-=' + distance + 'px', opacity: 1 }, time, 'swing', function() {beingShown = false; shown = false;});
			trigger.css({'background-position' : 'bottom left'});
  	}
	});
	
	$('.popup-top').click(function(){
		var info = $(this).parent();
		var trigger = info.parent();
    hideDelayTimer = setTimeout(function () {
    	hideDelayTimer = null;
    	info.animate({top: '-=' + distance + 'px',opacity: 0}, time, 'swing', function () {shown = false;info.css('display', 'none');});
    }, hideDelay);
		trigger.css({'background-position' : 'top left'});
	});
		
  $(".modalbox-center-button-decline").live("click", (function(ev) {
    $("#lightbox , #lightbox-overlay, #modalbox").hide();
 		$('body').css("overflow-y","auto");
  }));
	$('#gs-zipcode-box').click(function(){
		$('#get-started-categories-header').css("background-position","14px -80px");
	});
	$('#gs-address-box, #gs-state-box, #gs-city-box').click(function(){
		$('#get-started-categories-header').css("background-position","14px -160px");
	});
	$('.jquery-selectbox').css("margin-top","-8px");
	$('.popup-center a').live("click", function(ev){
		ev.preventDefault();
		var offset = $(this).offset();
		var catid = this.id;
		if (hideDelayTimer) clearTimeout(hideDelayTimer);
    $('#selected-cats').val(catid);
//    $('#selected-cats-links').val(selected_cats_links);
    var zipcode = $('#gs-zipcode-box').val();
    var address = $('#gs-address-box').val();
    var state = $('#gs-state-box').val();
    var city = $('#gs-city-box').val();
    if(zipcode || (address && state && city)){
      geocoder.getLatLng((zipcode + " " + address + " " + state + " " + city),
  		function(point) {
				if(point){
					$('#location-point').val(point);
					var formdetails = $("#user-selected-values").serialize();
  	   		$('html, body').animate({scrollTop:0}, 'normal');
 					$('body').css("overflow","hidden");
					$("#lightbox , #lightbox-overlay").show();
		    	$("#modalbox").hide();
					$.ajax({
						type: "POST",
					  url: "setsession.php",
					  cache: false,
					  data: formdetails,
						async: false,
					  success: function(html){
							if (window.innerHeight) {
								theHeight=window.innerHeight;
							}
							else if (document.documentElement && document.documentElement.clientHeight) {
								theHeight=document.documentElement.clientHeight;
							}
							else if (document.body) {
								theHeight=document.body.clientHeight;
							}
				    	$("#search-results-page, #search-results-page-content").css("height",(theHeight-250));
							$("#search-results").show();
							$("#search-results-page-content").empty().html('<img id="listing-loading-gif" src="graphic/listings/loadingAnimation.gif" />');
					   	$.post("ajaxcontent.php",{category_id: catid}, function(html){
					    	$("#search-results-page-content").html(html).jScrollPane({showArrows:true, scrollbarWidth:18, scrollbarMargin:0});
							});
					  }
					});			    	      		
				}else{
					$("#lightbox-overlay").css("filter","alpha(opacity=70)");
					$("#lightbox , #lightbox-overlay").show();
					$("#modalbox-center").html("<h3>" + zipcode + " " + state + " " + city + " not found</h3><p>Sorry, we cannot find your location. Please check the details of your location and try again.</p><div id=\"modalbox-center-button\"><input type=\"button\" class=\"modalbox-center-button-decline\" value=\"Okey, Let me check my details\" /></div>");
					$("#modalbox").fadeIn("normal");
		   		$('html, body').animate({scrollTop:0}, 'normal');
		   		$('body').css("overflow","hidden");
				}
  		});
    }else{
    	$('#zip-error').css({'left': (offset.left-145), 'top': (offset.top-80)});
    	$('#zip-error').fadeIn();
    }
    return false;
  }).mouseout(function () {
  		$('#zip-error').fadeOut();
  });
	
	$('#map-results-page-content .printbutton').live("click", function(ev) {
		ev.preventDefault();
		$('#pf-form').submit();
	})
	$('.listing-item-select a').live("click", function(ev) {
		ev.preventDefault();
		var id = $(this).attr("id").substr(13);

		var location =  $("#vendorlistingloc-"+id).val();
		var start_loc = $('#location-point').val();
		$('#pf-start').val(location);
		$('#pf-location').val(start_loc);
		$('#pf-name').val($("#vendorlistingname-"+id).text());
		if (window.innerHeight) {
			theHeight=window.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight) {
			theHeight=document.documentElement.clientHeight;
		}
		else if (document.body) {
			theHeight=document.body.clientHeight;
		}
		$("#modalbox, #search-results").hide();
		$("#map-results-page, #map-results-page-content").css("height",(theHeight-250));
		$("#map-results").show();
		MAPS_LOCATIONS = [$('#location-point').val(), $("#vendorlistingloc-"+id).val()];
		VENDOR_NAMES = new Array($("#vendorlistingname-"+id).text());
		initialize(MAPS_LOCATIONS);
		
//		$("#map-results").empty().html('<img id="listing-loading-gif" src="graphic/listings/loadingAnimation.gif" />');
//		$.post("../routecontent.php",{name: name, location: location, start: start_loc}, function(html){
//			alert(html);
			$("#map-results-page-content").jScrollPane({showArrows:true, scrollbarWidth:18, scrollbarMargin:0,animateTo:true, animateInterval:50});
			$(".please-wait-message").html('Please wait road trip directions loading...<br /><img src="graphic/listings/loadingAnimation.gif" />').wait(2000,function(){
				$("#route td[jscontent='address']:eq(0)").text('Starting Location');
				$("#route table[jstcache='0']").css( {"text-transform" : "uppercase", font : "bold 18px 'Arial', Helvetica, sans-serif", color : "#494949", border : "1px solid #d4d4d4", "margin-bottom" : "0px", "border-bottom" : "0px"} );
				for (x in VENDOR_NAMES){
					var no = parseFloat(x)+1;
					$("#route td[jscontent='address']:eq(" + no + ")").text(VENDOR_NAMES[x]);
				}
				$("#route div[jseval='this.innerHTML = $Route.summaryHtml']").hide();
				$(".please-wait-message").hide();
				$("#route").show();
				$('#map-results-page-content').jScrollPane({showArrows:true, scrollbarWidth:18, scrollbarMargin:0,animateTo:true, animateInterval:50});
			});
//		});
	});

var error_report = 0;
function onGDirectionsError(directionobject){
	if (error_report == 0){
		$("#lightbox-overlay").css("filter","alpha(opacity=70)");
		$("#lightbox , #lightbox-overlay").show();
		$("#modalbox-center").html("<h3>An Error Occured</h3><p>An unknown error occurred, possibly your final destination is too far away from your starting location. Please back to \"Begin planning\" page and check the vendors and change your final destination before try again.</p><div id=\"modalbox-center-button\"><input type=\"button\" class=\"modalbox-center-button-decline\" value=\"Okey, Let me back to startpage\" /></div>");
		$("#modalbox").fadeIn("normal");
		$('html, body').animate({scrollTop:0}, 'normal');
		$('body').css("overflow","hidden");
	}else{
		if (directionobject.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		 var 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: " + directionobject.getStatus().code;
		else if (directionobject.getStatus().code == G_GEO_SERVER_ERROR)
		 var alert  = "A geocoding or directionobject request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directionobject.getStatus().code;
		else if (directionobject.getStatus().code == G_GEO_MISSING_QUERY)
		 var 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 directionobject requests, this means that no query was specified in the input.\n Error code: " + directionobject.getStatus().code;
		else if (directionobject.getStatus().code == G_GEO_BAD_KEY)
		 var alert  = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directionobject.getStatus().code;
		else if (directionobject.getStatus().code == G_GEO_BAD_REQUEST)
		 var alert  = "A directions request could not be successfully parsed.\n Error code: " + directionobject.getStatus().code;
		else var alert  = "An unknown error occurred.";
	$("#lightbox-overlay").css("filter","alpha(opacity=70)");
	$("#lightbox , #lightbox-overlay").show();
	$("#modalbox-center").html("<h3>Error Occured</h3><p>" + alert + " Please back to get started page and try to plan your route again.</p><div id=\"modalbox-center-button\"><input type=\"button\" class=\"modalbox-center-button-decline\" value=\"Okey, Let me back to startpage\" /></div>");
	$("#modalbox").fadeIn("normal");
	$('html, body').animate({scrollTop:0}, 'normal');
	$('body').css("overflow","hidden");
	}
}

	function initialize(MAPS_LOCATIONS) {
		map = new GMap2(document.getElementById("map_canvas"));
    map.addControl(new GLargeMapControl3D());
  	var directionsPanel = document.getElementById("route");
		directions = new GDirections(map, directionsPanel);
		directions.loadFromWaypoints(MAPS_LOCATIONS);
		GEvent.addListener(directions, "error", onGDirectionsError);
	}
	$(".googledir").live("click", function(){
		 $('#map-results-page-content')[0].scrollTo(0);
	});
	$("#search-results-header-close").click(function(ev) {
   	ev.preventDefault();
		$("#lightbox , #lightbox-overlay").fadeOut(300);
		$("#modalbox, #search-results").hide();
		$('body').css("overflow-y","auto");
	});
	$("#map-results-header-close").click(function(ev) {
   	ev.preventDefault();
		$("#map-results, #route").hide();
		$(".please-wait-message").show();
		$("#route").html("");
		$("#modalbox, #search-results").show();
	});

});
