google.load("maps", "2");

jQuery.mapCounter = 0;
jQuery.mapArray = new Array();
jQuery.dirArray = new Array();

jQuery.fn.googleMapError = function() {
	return jQuery(this).each(function() {
		jQuery(this).find('.error').text("Address not recognized--please enter a valid or more specific address.");
		jQuery(this).find('.map').hide();
	});
}

function googleMapError() {
	jQuery(".map-container").find('.error').text("Address not recognized--please enter a valid or more specific address.");
	jQuery(".map-container").find('.map').hide();
}

jQuery.fn.googleMapInit = function() {
	if (google.maps.BrowserIsCompatible()) {
		return jQuery(this).each(function(){
			var mapObj = jQuery(this).children(".map")[0];
			var dirObj = jQuery(this).children(".dir")[0];
			jQuery.mapArray[jQuery.mapCounter] = new google.maps.Map2(mapObj);
			jQuery.dirArray[jQuery.mapCounter] = new google.maps.Directions(jQuery.mapArray[jQuery.mapCounter],dirObj);
			control = new google.maps.LargeMapControl();
			jQuery(this).attr("mapid", jQuery.mapCounter);
			jQuery.mapArray[jQuery.mapCounter].addControl(control);
			google.maps.Event.addListener(jQuery.dirArray[jQuery.mapCounter], "error", function() { jQuery(this).googleMapError(); });
			jQuery.mapCounter++;
		});
	}
	else
	{
	return jQuery(this);
	}
}

jQuery.fn.googleMap = function(to, from) {
    if (google.maps.BrowserIsCompatible()) {
		return jQuery(this).each(function(){
			var mapid = $(this).attr("mapid");
			string = "to: " + to + " from: " + from;
			jQuery(this).find('.map').show();
			jQuery(this).find('.error').text("");
			jQuery.dirArray[mapid].clear();
			jQuery.dirArray[mapid].load(string);
		});
	}
	else
	{
	return jQuery(this);
	}
}
	
$(window).unload(function () { google.maps.Unload(); });

jQuery.fn.prep_alert = function() {
	return jQuery(this).each(function(){
		var box = jQuery(this);
		var alertPane = box.find(".alert-pane");
		var mapPane = box.find(".map-pane");
		var mapContainer = box.find(".map-container");
		var alertButton = box.find(".open-alert-pane");
		var mapButton = box.find(".open-map-pane");
		
		mapContainer.append("<span class='error'></span>");
		mapPane.hide().find(".gmap").submit(function() {
			id = $(this).children("#event-id").val();
			fromAddr = $("#from-address"+id).val() + " " + $("#from-city"+id).val() + ", " + $("#from-state"+id).val() + " " + $("#from-zip"+id).val(); 
			toAddr = $("#to-address"+id).val() + " " + $("#to-city"+id).val() + ", " + $("#to-state"+id).val() + " " + $("#to-zip"+id).val();
			if (mapContainer.children().length < 2) mapContainer.append("<div class='map' style='width:500px; height:300px;'></div>").append("<div class='dir'></div>").googleMapInit().googleMap(to=toAddr,from=fromAddr);
			else mapContainer.googleMap(to=toAddr,from=fromAddr);
		});

		alertPane.hide().children(".alert").attr("action","javascript:;").append("<input type='hidden' id='xhr' name='xhr' value='true' />").submit(function() { 
			var submit_dict = alertPane.find(":input").serializeArray();
			jQuery.getJSON("/apps/cal/addalert/",
			submit_dict,
			function(data){
				if (data.form.success==true) 
				{	
					if (data.form.notify > 1) pluralize = "s";
					else pluralize = "";
					alertPane.html("<span class='success'><h3>Form Submission Successful!</h3><p>You will be notified " + data.form.notify + " hour" + pluralize + " before the event</p></span>");
				}
				else 
				{
					jQuery("#email" + data.form.id).next().text(data.form.errors.email);
					jQuery("#firstName" + data.form.id).next().text(data.form.errors.firstName);
					jQuery("#lastName" + data.form.id).next().text(data.form.errors.lastName);
				}
			});
		});		
		
		alertButton.click(function () {
			if (!alertPane.is(":animated") && !mapPane.is(":animated")) {
				mapPane.slideUp(250);
				if (alertPane.is(":hidden")) alertPane.show("slow");
				else alertPane.slideUp(500);
			}
		});
		
		mapButton.click(function () {
			if (!alertPane.is(":animated") && !mapPane.is(":animated")) {
				alertPane.slideUp(250);
				if (mapPane.is(":hidden")) mapPane.show("slow");
				else mapPane.slideUp(500);
			}
		});
	});
}
function prep_day_links() {	
	$(".slid").attr("href","javascript:;").click(function () {
		if(!$("#sliddiv").is(":animated")) {
			my_id = $(this).attr('id');
			$("#sliddiv").queue(function () {
				$(this).slideUp(500).dequeue();
			}).queue(function () {
				$(this).load('/apps/cal/event' + my_id, {}, function() { 
					
					$(this).prep_alert().show('slow');
					$(this).find(".event-title, .close-x").click(function () {
						if (!$("#sliddiv").is(":animated")) {
							if($("#sliddiv").is(":hidden")) $("#sliddiv").show("slow");
							else $("#sliddiv").slideUp(500);	
						}
					})
				}).dequeue();
			});
		}
	});
}

function change_calendar(my_id) {
	if(!$("#current-cal").is(":animated")){
	$("#current-cal").queue(function() {
		$(this).fadeOut("slow").dequeue();
	}).queue(function() {
		$(this).load('/apps/cal/tiny' + my_id, {}, function() { 
			prep_cal_links(); 
			prep_cal_days(); 
		}).dequeue();
	}).queue(function() {
		$(this).fadeIn("slow").dequeue();
	});
	}
}

function prep_cal_links() {	
	$(".prev-month, .next-month").attr("href","javascript:;").click(function() {
			change_calendar($(this).attr('id'));
	});
}

function prep_cal_days() {
	$(".busy a").each(function() {
		$(this).attr("rel",$(this).attr("href")).attr("href","javascript:;");
	});
	$(".busy").click(function () {
		if(!$("#dayevents").is(":animated")) {
			var url = $(this).children("a").attr("rel")
			$("#dayevents").queue(function () {
				$(this).slideUp(500).dequeue();
			}).queue(function () {
				$(this).load(url, {}, function() { prep_day_links(); }).dequeue();
			}).queue(function () {
				$(this).show("slow").dequeue();
			});
			$("#sliddiv").slideUp(500);
		}
	}); 
}

function do_search(keywords) {
error_msg = "";
termLength = $("#search-cal-form #keywords").val().length;
if($("#loading").text()!="Loading...") {
	$.getJSON("/apps/cal/"+category+"/search/",
		{'keywords':keywords,'xhr':'true' },
        function(data){
			if (data.novalid) 	if (termLength<1) error_msg = "<br />Please enter a search phrase.";
								else error_msg = "<br />Common words are excluded from searches. Please use more specific words (i.e. 'Topeka', 'Emporia').";
			else if (data.ids.length<1) {
				error_msg = "<br />No search results. Feel free to fill out the below form to contact an Admissions representative.";
				$("#search-feedback").load("/apps/cal/feedback/", {}, function () { 
					$("#search-feedback").find("form").attr("action","javascript:;").submit(function() {
						name = $(this).find("#search-name").val();
						email = $(this).find("#search-email").val();
						comments = $(this).find("#search-comments").val();
						$.getJSON("/apps/cal/feedback", {'search-name':name, 'search-email':email, 'search-comments':comments, 'xhr':'true' }, function(data) {
							if (data.submit) { 
								$("#loading").html("<br /> Form submitted successfully. An Admissions representative will receive an email detailing your comments shortly."); 
								$("#search-feedback").html(""); 
							}
						});
					}); 
				});
			}
			else { 
				error_msg = "";
				$("#search-feedback").html("");
			}
			$.each(data.ids, function(i,ids){
				$("#search-results").append("<div id=\"" + ids + "\"></div>").children("div:last-child").load("/apps/cal/event/" + ids + "/", {}, function() { 
					$(this).queue(function() {
						$(this).children(".box").hide();
						$(this).dequeue();
					}).queue(function() {
						$(this).prep_alert().find(".event-title, .close-x").click(function () {
							box = $(this).parent().find(".box");
							if (!box.is(":animated")) {
								$("#search-results .box").hide(500);
								if(box.is(":hidden")) box.show("slow");
								else box.slideUp(500);	
							}
						})
						$(this).dequeue();
					});
					$(this).find(".event-title").wrapInner("<a href='javascript:;'></a>");
				});
			});
        });
	$("#loading").html("<br />Loading...");
	$("#search-results").empty().hide().ajaxSuccess(function(){
		
		$(this).show(500);
		$("#loading").html(error_msg);
	});
}
}