$(document).ready(function() {
	$.postJSON = function( url, data, callback ) {
	  return $.post(url, data, callback, "json");
	}
	
	$("a#email_planner").click(function() {
		$("div#email_form_wrap").slideToggle('slow');
		return false;
	});
	
	$("a.add-link").click(function() {
		var theShop = $(this);
		if(theShop.attr("id").substr(0,5)!="shop-") return true;
		$.postJSON("/wp-content/plugins/day_planner/day_planner_functions.php", {
			shop : theShop.attr("id"),
			func : "add_shop"
		},
			function(j) {
				if (j.code == 1) {
					theShop.text("Added!");
				} else if(j.data == "Shop is already in the day planner") {
					theShop.text("Shop already in Day Planner");
				} else {
					theShop.text("Could not add shop");
				}
			}
		);
		return false;
	});

	$("form#personal_shopper").submit(function() {
		show_loading_area();

		$.postJSON("/wp-content/plugins/day_planner/processor.php", {
			i_am : $("#i_am").val(),
			aged : $("#aged").val(),
			buying : $("#buying").val(),
			fashion_for : $("#fashion_for").val(),
			fashion_aged : $("#fashion_aged").val(),
			fashion_occassion : $("#fashion_occassion").val(),
			fashion_interested : $("#fashion_interested").val(),
			food_type : $("#food_type").val(),
			food_area : $("#food_area").val()
		}, function(j)
		{
			hide_loading_area();
			if (!j) {
				$("#suggestions").append("<li>No shops could be found</li>");
			}
			else
			{
				for (var i = 0; i < j.length; i++) {
					if (j[i].is_in)
					{
						$("#suggestions").append("<li class=\"result\" style=\"background-color: #A6A8B1;\"><span style=\" cursor: default;\" class=\"shop\" id=\"shop_"+j[i].id+"\">Added/&nbsp;</span><span class=\"shop\" id=\"planner_shop_view_search_"+j[i].id+"\">View/&nbsp;&nbsp;&nbsp;</span>"+j[i].name+"<br /><span id=\"planner_shop_description_"+j[i].id+"\" class=\"shop_description\" style=\"display: none;\">"+j[i].description+"</span></li>");
					}
					else
					{
						$("#suggestions").append("<li class=\"result\"><span class=\"shop\" id=\"shop_"+j[i].id+"\">Save/&nbsp;</span><span class=\"shop\" id=\"planner_shop_view_search_"+j[i].id+"\">View/&nbsp;&nbsp;&nbsp;</span>"+j[i].name+"<br /><span id=\"planner_shop_description_"+j[i].id+"\" class=\"shop_description\" style=\"display: none;\">"+j[i].description+"</span></li>");
						$("#shop_"+j[i].id).bind("click", function() {
							add_shop($(this));
						});
					}

					$("#planner_shop_view_search_"+j[i].id).bind("click", function() {
						$(this).siblings(':last').toggle();
					});
				}
			}
		});
		return false;
	});
	
	$("#email_form").submit(function() {
		$("#email_form_response").html('Sending email');
		if ($("#email").val() == '')
		{
			$("#email_form_response").html('An Error Occurred: You must enter an email address');
			return false;
		}
		$.postJSON("/wp-content/plugins/day_planner/day_planner_functions.php", {
			func : "send_email",
			email : $("#email").val()
		}, function(j)
		{
			if (j.code == 1)
			{
				$("#email_form_response").html('Your email has been sent!');
			}
			else
			{
				$("#email_form_response").html('An Error Occurred: ' + j.data)
			}
		});
		return false;
	});
	
	load_current_shops();
	function load_current_shops()
	{
		$("#my_visit").empty();
		$("#my_visit").append('<li>Loading your day planner&hellip;</li>');
		$.postJSON("/wp-content/plugins/day_planner/day_planner_functions.php", {
			func : "get_shops"
		}, function(j)
		{
			$("#my_visit").empty();
			if (!j['data'][0])
			{
				$("#my_visit").append("<li id=\"no_shops\">You have not added any shops for your visit yet&hellip;</li>");
			}
			else
			{
				for (var i = 0; i < j.data.length; i++) {
					$("#my_visit").append("<li class=\"result\"><span class=\"shop\" id=\"planner_shop_"+j.data[i].id+"\">Remove/&nbsp;</span><span class=\"shop\" id=\"planner_shop_view_"+j.data[i].id+"\">View/&nbsp;&nbsp;&nbsp;</span>"+j.data[i].name+"<br /><span id=\"planner_shop_description_"+j.data[i].id+"\" class=\"shop_description\" style=\"display: none;\">"+j.data[i].description+"</span></li>");

					$("#planner_shop_"+j.data[i].id).bind("click", function() {
						remove_shop($(this));
					});
					
					$("#planner_shop_view_"+j.data[i].id).bind("click", function() {
						$(this).siblings(':last').toggle();
					});
					
					if (j.data[i].coords != false)
					{
						add_point(j.data[i].coords.lat, j.data[i].coords.long, j.data[i].coords.for_map);
					}
				}
			}
		});
	}

	function reload_map()
	{
	    map.clearOverlays();
		$.postJSON("/wp-content/plugins/day_planner/day_planner_functions.php", {
		    func : "get_shops"
		}, function(j)
		{
		    if (j['data'][0])
		    {
		        for (var i = 0; i < j.data.length; i++) {
		            add_point(j.data[i].coords.lat, j.data[i].coords.long, j.data[i].coords.for_map);
		        }
		    }
		});
	}

	function show_loading_area()
	{
		$("#suggestions").empty();
		$("#search_results").show();
		$("#suggestions").append("<li>Getting your results&hellip;</li>");
	}

	function hide_loading_area()
	{
		$("#suggestions").empty();
	}

	function add_shop(shop)
	{
		$.postJSON("/wp-content/plugins/day_planner/day_planner_functions.php", {
			shop : shop.attr("id"),
			func : "add_shop"
		}, function(j)
		{
			if (j.code == 1)
			{
				shop.parent().css('backgroundColor', '#A6A8B1');
				shop.html('Added/&nbsp;');
				shop.unbind('click');
				shop.css('cursor', 'default');
				
				$("#my_visit").append("<li class=\"result\"><span class=\"shop\" id=\"planner_shop_"+j.data[1].id+"\">Remove/&nbsp;</span><span class=\"shop\" id=\"planner_shop_view_"+j.data[1].id+"\">View/&nbsp;&nbsp;&nbsp;</span>"+j.data[1].name+"<br /><span id=\"planner_shop_description_"+j.data[1].id+"\" class=\"shop_description\" style=\"display: none;\">"+j.data[1].description+"</span></li>");
				$("#no_shops").remove();
				
				if (j.data[1].coords != false)
				{
					add_point(j.data[1].coords.lat, j.data[1].coords.long, j.data[1].coords.for_map);
				}
				
				$("#planner_shop_"+j.data[1].id).bind("click", function() {
					remove_shop($(this));
				});

				$("#planner_shop_view_"+j.data[1].id).bind("click", function() {
					$(this).siblings(':last').toggle();
				});
				
			}
			if(j.code == 0)
			{
				alert('An Error Occurred: ' + j.data)
			}
		});
	}
	
	function remove_shop(shop)
	{
		$.postJSON("/wp-content/plugins/day_planner/day_planner_functions.php", {
			shop : shop.attr("id"),
			func : "remove_shop"
		}, function(j)
		{
			if (j.code == 1)
			{
				shop.parent().remove();
				$("#shop_"+j.data[1].id).parent().css('backgroundColor', '#F1F2F3'); 
				$("#shop_"+j.data[1].id).html('Save/&nbsp;');
				$("#shop_"+j.data[1].id).css('cursor', 'pointer');
				$("#shop_"+j.data[1].id).bind("click", function() {
					add_shop($(this));
				});
				$("#shop_"+j.data[1].id).parent().bind('mouseover', function() {
					$(this).css('backgroundColor', '#222');
				});
				$("#shop_"+j.data[1].id).parent().bind('mouseout', function() {
					$(this).css('backgroundColor', '#F1F2F3');
				});
			}
			if(j.code == 0)
			{
				alert('An Error Occurred: ' + j.data)
			}
		});
		reload_map();
	}

	var map;
    var is_running = false;
	var map_icons_url = "/wp-content/themes/StyleBirmingham2010/img/";

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GOverviewMapControl());
		map.setCenter(new GLatLng(52.480169,-1.896092), 15);
		map.enableDoubleClickZoom();
	}
	
	function createMarker(point, iconOptions, text) {
		var marker = new GMarker(point, iconOptions);
		GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(text); });
		return marker;
	}
	
	function add_point(lat, longi, text)
	{
	      //map.clearOverlays();
      	  var icon = new GIcon(G_DEFAULT_ICON);
      	  icon.image = map_icons_url + "map-icon-v2.png"; 
      	  var iconType = { icon:icon };	
	      map.addOverlay(
		      createMarker(
		         new GLatLng(
		       	     lat,
		       		 longi
	       		 ),
		    	 iconType,
	       		 text
       		  )
       	  );
	}
	
	$("select").change(function() {
		// Work element by element, determining if it should be shown

		// Show age box?
		if ($("#i_am").val() == 'male' || $("#i_am").val() == 'female')
		{
			$("#aged_wrapper").show();
		}
		else
		{
			$("#aged_wrapper").hide();
			$("#aged").val("0");
		}

		// Show buying box?
		if (($("#i_am").val() == 'family' || $("#i_am").val() == 'couple') || $("#aged").val() != "null")
		{
			$("#buying_wrap").show();
		}
		else
		{
			$("#buying_wrap").hide();
			$("#buying").val("0");
		}

		// Show for a box?
		if ($("#buying").val() == 'fashion')
		{
			$("#fashion_for_wrap").show();
			// if we know the shopper, add two more values
			if (($("#i_am").val() == 'male' || $("#i_am").val() == 'female') && ($("#fashion_for").val() != 'myself' && $("#fashion_for").val() != 'partner'))
			{
				$("#fashion_for").addOption({"myself" : "myself", "partner" : "partner" }, false);
			}
			// else, just make sure the additional values are gone
			else if ($("#i_am").val() != 'male' && $("#i_am").val() != 'female')
			{
				$("#fashion_for").removeOption("myself");
				$("#fashion_for").removeOption("partner");
			}
		}
		else
		{
			$("#fashion_for_wrap").hide();
			$("#fashion_for").val("0");
		}

		// Show Fashion for (age range) box
		if ($("#fashion_for").val() == 'male_adult' || $("#fashion_for").val() == 'female_adult')
		{
			$("#fashion_aged_wrap").show();
		}
		else
		{
			$("#fashion_aged_wrap").hide();
			$("#fashion_aged").val("0");
		}

		// Show atmosphere box
		if (($("#fashion_aged").val() != "null") || ($("#fashion_for").val() != 'male_adult' && $("#fashion_for").val() != 'female_adult' && $("#fashion_for").val() != 'null'))
		{
			$("#fashion_occasion_wrap").show();
		}
		else
		{
			$("#fashion_occasion_wrap").hide();
			$("#fashion_occassion").val("0");
		}

		// Show interested in box
		if ($("#fashion_occassion").val() != "null")
		{
			$("#fashion_interested_wrap").show();
		}
		else
		{
			$("#fashion_interested_wrap").hide();
			$("#fashion_interested").val("0");
		}

		// Show food type box?
		if ($("#buying").val() == "food")
		{
			$("#food_type_wrap").show();
		}
		else
		{
			$("#food_type_wrap").hide();
			$("#food_type").val("0");
		}

		// Show food area box?
		if ($("#food_type").val() != "null")
		{
			$("#food_area_wrap").show();
		}
		else
		{
			$("#food_area_wrap").hide();
			$("#food_area").val("0");
		}
	});
});