// JavaScript Document

$(document).ready(function() {
	
	// manage toggle elements
	$(".togglable").hide();
	$(".toggler").click(function(){
		var theDiv = $(".togglable#"+$(this).attr('href').split('#')[1]).slideToggle();
		return false;
	});
	
	// display default values in fields
	$("input.not_null").each(function(){
		var idname = $(this).attr("id"); // get id
		if ($(this).val() == "") {
			$(this).val($("input[title='"+idname+"']").val());
			$(this).css({ color:"#aaa" });
		}
	});

	$("input.not_null").focus(function(){
		// if a label exists which is pointing at this element 
		// and it's text matches, clear the field
		var idname = $(this).attr("id"); // get id
		if ($("input[title='"+idname+"']").val() == $(this).val()) {
			$(this).val("");
			$(this).css({ color:"" });			
		}
	});

	$("input.not_null").blur(function(){
		// if the specified input box is blank
		// display the value of the label tag pointing at this element 
		var idname = $(this).attr("id"); // get id
		if ($(this).val() == "") {
			$(this).val($("input[title='"+idname+"']").val());
			$(this).css({ color:"#aaa" });
		}
	});

	// display labels in fields
	$("input.hint").each(function(){
		var idname = $(this).attr("id"); // get id
		$("label[for='"+idname+"']").hide(); // hide the corresponding label
		if ($(this).val() == "") {
			$(this).val($("label[for='"+idname+"']").text());
			$(this).css({ color:"#aaa" });
		}
	});

	$("input.hint").focus(function(){
		// if a label exists which is pointing at this element 
		// and it's text matches, clear the field
		var idname = $(this).attr("id");
		if ($("label[for='"+idname+"']").text() == $(this).val()) {
			$(this).val("");
			$(this).css({ color:"" });			
		}
	});

	$("input.hint").blur(function(){
		// if the specified input box is blank
		// display the value of the label tag pointing at this element 
		var idname = $(this).attr("id");
		if ($(this).val() == "") {
			$(this).val($("label[for='"+idname+"']").text());
			$(this).css({ color:"#aaa" });
		}
	});
	
	// autocomplete the keywords input box
	if (jQuery.autocomplete) {
		$(".autocomplete").autocomplete("/autocomplete.php", { minChars:2,autoFill:true,maxItemsToShow:10 });
	}
	
	// display image gallery in profiles
	if ($.fn.cycle) {
		$('#cycle').cycle({
			fx:     'fade', 
			speed:  300, 
			timeout: 0,
			pager:  '#cycle_nav',
			before:  onBefore, 
			after:   onAfter
		});
	}
	function onBefore() { 
		$('#caption').fadeOut(); 
		$('#cycle').animate({ 
        width: this.width,
        height: this.height
      	}, 300 );		
	} 
	function onAfter() { 
		if (this.alt) {$('#caption').html(this.alt);}
		else if (this.name) {$('#caption').html(this.name);}
		else {$('#caption').html("&nbsp;");}
		$('#caption').fadeIn(); 
	}
	
	// Script to initiate auto-expand textarea
	// Causes script errors on pages without a nominated textarea
	// prettyComments.init('description');
	
	// this causes the textarea to lose its left margin
	// $('textarea.expanding').autogrow();
	
	// present confirmation on delete
	$(".catch_delete").click(function(){
		if (confirm('Do you want to permanently delete this item?')) {
			return true;
		} else {
			return false;
		}
	});

	// display datepicker
	if ($.fn.datePicker) {
		Date.firstDayOfWeek = 7;
		Date.format = 'yyyy-mm-dd';
		$('.date-pick').datePicker();
	}

	// autoselect code in textarea
	$(".selectable_code").click(function(){
		$(this).focus().select();
	});

	// hide query code
	$(".query").each(function(){
		$(this).prev("p").append(" - <a href='#query'>show sql query</a>");
		$(this).hide();
	});
	$("a[href='#query']").click(function(){
		$(".query").slideToggle();
	});

	// hide optional input
	$(".optional_input").each(function(){
		$(this).before("<div><a href='#optional_input'>show input box</a><div>");
		$(this).hide();
	});
	$("a[href='#optional_input']").click(function(){
		$(".optional_input").slideToggle();
	});

	// select all checkboxes
	$("#select_all").click(function(){
		$("input.js_selectable").attr("checked","checked");
		return false;
	});	
	
	// Simple validation for profile emailing system
	$("form input[value='Send']").click(function(){
		var email_field = $(this).parents("form").find("input#email_sender_address");
		if (email_field.length > 0 && email_field.attr("value") == null) {
			if (confirm("You have not provided your email address. Do you still wish to submit the message?")) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return true;
		}
		
	});
	
	// address input visibility
	if ($("fieldset.input input#situation_address").not(":checked").length > 0) {
		$("fieldset.input div.location_address").hide();
	}
	$("fieldset.input input#situation_address").click(function(){
		$("fieldset.input div.location_address").slideToggle();
	});
	
	// check admin email before sending
	$("input#admin_button_send").click(function(){
		if ($("input#email_subject").attr("value") == "" || $("textarea#email_content").attr("value") == "") {
			if (confirm("Some message details are missing. Do you still wish to submit the message?")) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return true;
		}
	});

	// dynamically add map canvas to #box
	if (window.GBrowserIsCompatible && GBrowserIsCompatible() && $("form input[name='accuracy']").attr("value") > 1 && $(".item input[name='accuracy']").length > 0) {
		$("div #box").append(" <h3><a class='show_box_item' href='#map_canvas'>Map</a></h3><div id='map_canvas' class='item'></div> ");

		// add pushpins to page
		$(".geo_data").each(function(){
			
			var accuracy = $(this).find("input[name='accuracy']").attr("value");
			if (accuracy < 8) {
				$(this).find("span.xpushpin").append(" <a href='#map_canvas' class='show_box_item'><img src='/mto/images/general/icons/pushpin_dot_mid.png' alt='display on map' title='display on map' align='baseline' border='0' /></a>");
			}
			else {
				$(this).find("span.xpushpin").append(" <a href='#map_canvas' class='show_box_item'><img src='/mto/images/general/icons/pushpin_mid.png' alt='display on map' title='display on map' align='absmiddle' border='0' /></a>");
			}
			
		});
	}
	
	function boxSwitch() {
		
		// get the href value
		var theHref = $(this).attr('href');
		
		// get the nav list item
		var theNavItem = $("#box ul.nav li:has(a[href='"+theHref+"'])");
		
		// create instance of div
		var theTargetId = theHref.split('#')[1];
		var theDiv = $("#box div.item#"+theTargetId);
		
		// display selected content
		theDiv.show();
		
		// hide all other content
		$("#box div.item").not("#"+theTargetId).hide();
				
		// set active nav item to passive
		$("#box ul.nav li.active").not("[title='"+theTargetId+"']").each(function(){
			var x = $(this).attr("title");
			$(this).wrapInner("<a href='#"+x+"' class='show_box_item'></a>");
			$(this).removeAttr("title").removeAttr("class");
			$("a.show_box_item").click(boxSwitch);
		});
		
		// set current nav item to active
		var y = theNavItem.find("a").html();
		theNavItem.html(y);
		theNavItem.removeClass("sfhover").addClass("active").attr("title",theTargetId);

		// create the map
		if (theTargetId == "map_canvas" && !window.map && window.createMap) {
			createMap();
		}
		
	}
	
	// add nav to box
	if ($("#box h3").length > 1) {
		$("#box").addClass("box");
		$("#box").prepend("<ul class='nav'></ul>");
	}
	$("#box h3").each(function(){
		$("#box ul.nav").append("<li>"+$(this).html()+"</li>");
		$(this).replaceWith("");
	});
	$("#box li:first a.show_box_item").each(boxSwitch);
	$("a.show_box_item").click(boxSwitch);

	/*
	if map_canvas is visible, create map
	else create map once when nav is clicked
	*/
	if ($("div #box #map_canvas:visible").length > 0 && window.createMap) {
		createMap();
	}
	
	$('.example a').lightBox({
		imageLoading: '/mto/images/general/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: '/mto/images/general/lightbox/lightbox-btn-close.gif',
		imageBtnPrev: '/mto/images/general/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/mto/images/general/lightbox/lightbox-btn-next.gif'
    });
	
});
