var numLayers = 3; //number of active submenu layers
var layers = Array();
layers[0] = 1;
layers[1] = 2;
layers[2] = 3;
var maxLayers = 6; //maximum possible layers in current layout
var curr = 0; //suggestionsBox position
var maxSuggestion = 0;
var searchBar = "#menuSearchBar";

$(document).ready(function(){

	var suggestion = "#menuSearchBar_drop";

	// auto adjust all drop-down menus to appear in correct place
	$("div#menu ul li").each(function() {
		var pos = $(this).offset();  
  		$(this).children("ol").css( { "left": (pos.left) + "px", "top":(pos.top + $(this).height() + 0) + "px" } );
	});	
	
	// var numSuggestions = $("div#searchSuggestions div#menuSearchBar_drop").length;
	// if (numSuggestions == 0) {
	// 	$("div#searchSuggestions").load('includes/search.asp', function() {
	// 	});
	// }      
	
	var numSuggestions = $("div#menuSearchBar_drop").length;
	if (numSuggestions == 0) {
		$.ajax({
			url: 'includes/search.asp',
			cache: false,
			success: function(data) {
				$(data).appendTo("body");
				maxSuggestion = $(suggestion + " ul li").size();
				autoAdjustSuggestions();
			}
		});
	}
	
	// auto adjust searchbar suggestions box
	autoAdjustSuggestions();

	// main navigation rollover code
	// caters for rollovers on main menu and subsequent dropdown menu
	$("div#menu ul li ol").hide(); 
	$("div#menu > ul > li").hover(
        function () { $(this).children("ol").fadeIn("fast"); },
		function () { $(this).children("ol").fadeOut("fast"); }
	);
	
	$("div#menu > ul > li > ol > li").hover(
        function () { $(this).children("ul").fadeIn("fast"); },
		function () { $(this).children("ul").fadeOut("fast"); }
	);
	
	// $("div#menu ul li").mouseover( function(){ showMenu($("div#" + $(this).attr('id') + "_drop")); } );
	// $("div#menu ul li").mouseout( function(){ closeMenu(); } );
	// $("div.subMenu").mouseover( function(){ showMenu($(this)); } );
	// $("div.subMenu").mouseout( function(){ closeMenu(); } );

	//START SEARCH BAR SUGGESTIONS
	if ( $("#menuSearchBar").is(":visible") ) {
		searchBar = "#menuSearchBar";
	} else if ( $(".form_searchBar").is(":visible") ) {
		searchBar = ".form_searchBar";
	}
	var prevLength = 0;
	var timeout = 0;
	var default_timeout = 2000;

	maxSuggestion = $(suggestion + " ul li").size();
	
	$(suggestion).live('mouseover', function(){
		showMenu( $(this));
		$(searchBar).css({ border: "1px solid #00B3D6" });
	});
		
	$(suggestion).live('mouseout', function(){
		hideLayer( $(this));
		$(searchBar).css({ border: "1px solid #999" });
	});
	
	$(suggestion + " ul li").live('click', function(){
		$(searchBar).attr("value", $.trim($(this).text().replace(/[,]{1}.+$/, "")) );
		curr = $(this).attr('id');
		$(searchBar).parent().submit();
	});
	
	$(suggestion + " ul li").live('mouseover', function(){
		$(this).addClass("selected");
		curr = $(this).attr('id');
	});
	
	$(suggestion + " ul li").live('mouseout', function(){
		$(this).removeClass("selected");
	});
	
	$(searchBar).focus( function(){
		$(searchBar).css({ border: "1px solid #00B3D6" });
	});
	
	$(searchBar).blur( function(){
		$(searchBar).css({ border: "1px solid #999" });
	});
    
    /* thanks to:                         
	 *  Peter Vulgaris (www.vulgarisoip.com)	
	 *	jquery.suggest 1.1 - 2007-08-06
	*/

	//if ($.browser.mozilla)
		//$(searchBar).keypress(processKey);	// onkeypress repeats arrow keys in Mozilla/Opera
	//else
	$(searchBar).keyup(processKey);		// onkeydup
		
	function processKey(e) {
		// handling up/down/escape requires results to be visible
		// handling enter/tab requires that AND a result to be selected
		if ((/27$|38$|40$/.test(e.keyCode) && $(suggestion).is(':visible')) ||
		(/^13$|^9$/.test(e.keyCode) && getCurrentResult() > 0)) {

		    if (e.preventDefault)
		    	e.preventDefault();
		    if (e.stopPropagation)
		    	e.stopPropagation();

		    e.cancelBubble = true;
		    e.returnValue = false;

		    switch (e.keyCode) {

		    case 38:
		        // up
				showMenu($(suggestion)[0]);
				$(suggestion + " ul li.selected").removeClass("selected");
				$(suggestion + " ul li#sug_" + prevResult()).addClass("selected");
		        break;

		    case 40:
		        // down
				showMenu($(suggestion)[0]);
				$(suggestion + " ul li.selected").removeClass("selected");
				$(suggestion + " ul li#sug_" + nextResult()).addClass("selected");
		        break;

		    case 9:
		        // tab
		    case 13:
		        // return
		        selectCurrentResult();
				//$(searchBar).parent().submit();
		        break;

		    case 27:
		        //	escape
		        hideLayer($(suggestion));
		        break;

		    }
		} else if ($(searchBar).val().length != prevLength) {
			if (timeout)
				clearTimeout(timeout);
			timeout = setTimeout(matchSuggestion, 50);
			prevLength = $(searchBar).val().length;
			
			if (prevLength > 0) {
				showMenu($(suggestion)[0]);
			}
			
		}
	}
	
	function nextResult() {
		if ($("#menuSearchBar_drop").is(':visible')) {

			curr++;
			while ( $("#menuSearchBar_drop ul li#sug_" + curr).is(':hidden') && curr <= maxSuggestion ) {
				curr++;
			}
		
			if (curr > maxSuggestion) {
				curr = 0;
				while ( $("#menuSearchBar_drop ul li#sug_" + curr).is(':hidden') && curr <= maxSuggestion ) {
					curr++;
				}
			}
			selectCurrentResult();
			return curr;
		}
		return;
	}
	
	function prevResult() {
		if ($("#menuSearchBar_drop").is(':visible')) {
			curr--;
			while ( $("#menuSearchBar_drop ul li#sug_" + curr).is(':hidden') && curr >= 0 ) {
				curr--;
			}
		
			if (curr < 0) {
				curr = $("#menuSearchBar_drop ul li").size();
				while ( $("#menuSearchBar_drop ul li#sug_" + curr).is(':hidden') && curr >= 0 ) {
					curr--;
				}
			}
			selectCurrentResult();
			return curr;
		}
		return
	}
	
	function getCurrentResult() {
		if ($("#menuSearchBar_drop").is(':visible')) {
			return curr;
		}
		return;
	}
	
	function selectCurrentResult() {
		$(searchBar).attr("value", $.trim($("#menuSearchBar_drop ul li#sug_" + getCurrentResult()).text().replace(/[,]{1}.+$/, "")) );
	}
	
	function matchSuggestion() {
		$("#menuSearchBar_drop ul li").each(function() {
			var search = $(searchBar).attr("value").replace(/(\W)/g, "\\$1");
			var search2 = $(searchBar).attr("value").replace(/(\W)/g, "\\$1");
			var search3 = $(searchBar).attr("value").replace(/(\W)/g, "\\$1");
			search2 = search2.replace(/rd/i, "ROAD");
			search2 = search2.replace(/st./i, "SAINT");
			search2 = search2.replace(/st/i, "SAINT");
			search3 = search3.replace(/saint/i, "ST ");
			if ( $(this).text().match(new RegExp("^(" + search + ")(.*)$|\\s+(" + search + ")(.*)$", "i") ) && search.length > 0 ){
				$(this).show();
			} else if ( $(this).text().match(new RegExp("^(" + search2 + ")(.*)$|\\s+(" + search2 + ")(.*)$", "i") ) && search2.length > 0 ){
				$(this).show();
			} else if ( $(this).text().match(new RegExp("^(" + search3 + ")(.*)$|\\s+(" + search3 + ")(.*)$", "i") ) && search3.length > 0 ){
				$(this).show();
			} else {
				$(this).hide();
			}
		})
	}			
		
	//END SEARCH BAR SUGGESTIONS                                                    
	
	$('input.form_go' ).hover(function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	}, function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	});
	
	$('input.form_go_left' ).hover(function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	}, function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	});
	
	/*
	$("div.report_tabs a[name='unit']").click(function() {
		$("div#report_box_house").css( {display: 'none'});
		$("div#report_box_unit").css( {display:'block'});
	});
	
	$("div.report_tabs a[name='house']").click(function() {
		$("div#report_box_unit").css( { display : 'none' } );
		$("div#report_box_house").css( { display : 'block'} );
	});
	   
	$("div.search_tabs a[name='unit']").click(function() {
		$("div#search_box_house").css( {display: 'none'});
		$("div#search_box_unit").css( {display:'block'});
		return false;
	});
	
	$("div.search_tabs a[name='house']").click(function() {
		$("#search_box_unit").css( { display : 'none' } );
		$("#search_box_house").css( { display : 'block'} );
		return false;
	});
	*/
	
	$("ul.account_tab a[name='update']").click(function() {
		$("div#account_history_box").css( {display: 'none'});
		$("div#account_update_box").css( {display:'block'});
		return false;
	});
	
	$("ul.account_tab a[name='history']").click(function() {
		$("div#account_update_box").css( { display : 'none' } );
		$("div#account_history_box").css( { display : 'block'} );
		return false;
	});
	
	// add or remove item to/from shopping cart
	$("a.cart").click(function(event){
		$.ajax({
  			type: "GET",
  			url: $(this).attr("href"),
			cache: false,
  			success: processCart
		});
		// Stop the link click from doing its normal thing
		return false;
	});

	// auto-load the cart information
	if ($("span.cartNumber").length > 0) {
		$.ajax({
  			type: "GET",
  			url: "includes/actions.asp?action=check&reportID=130979&RandomKey=" + Math.random() * Date.parse(new Date()),
			cache: false,
  			success: processCart
		});
	};
	
	$("input#cancel_cart").click(function(event){
		var clear_cart = confirm('Are you sure you wish to cancel the checkout process? Your shopping cart will be emptied');
		if(clear_cart == true) { location.href = 'checkout_cancel.asp'; }
	});
	$("input#cancel_checkout").click(function(event){ 
		var clear_cart = confirm('Are you sure you wish to cancel the checkout process? Your shopping cart will be emptied');
		if(clear_cart == true) { location.href = 'checkout_cancel.asp'; }
	});
	$("input#shopping_cart").click(function(event){ location.href = 'shoppingcart.asp'; });
	
	
	$("input#prod_post").click(function(event){
		var totalCost = parseFloat($("input#totalCost").val());
		if ($(this).is(':checked')) {
			// add item to cart
			totalCost = parseFloat(totalCost + 10.00);
		} else {
			// remove item from cart
			totalCost = parseFloat(totalCost - 10.00);
		};
		$("input#totalCost").val(totalCost);
		if (String(totalCost).indexOf(".") > 0) {
			$("span.cartCost").html('$' + totalCost);
		} else {
			$("span.cartCost").html('$' + totalCost + '.00');
		};
		$("span.cartCost").html('$' + totalCost + '.00');
		$("span.cartCost").animate({ color: "#00B3D6" }, "slow")
            .animate({ color: "#000000" }, "slow");
	});

	$("input#prod_fax").click(function(event){
		var totalCost = parseFloat($("input#totalCost").val());
		if ($(this).is(':checked')) {
			// add item to cart
			totalCost = parseFloat(totalCost + 10.00);
		} else {
			// remove item from cart
			totalCost = parseFloat(totalCost - 10.00);
		};
		$("input#totalCost").val(totalCost);
		if (String(totalCost).indexOf(".") > 0) {
			$("span.cartCost").html('$' + totalCost);
		} else {
			$("span.cartCost").html('$' + totalCost + '.00');
		};
		$("span.cartCost").animate({ color: "#00B3D6" }, "slow")
            .animate({ color: "#000000" }, "slow");
	});

	$("form#checkout_4").submit(function() {
		var post_error = $("input#post_error").val();
		var fax_error = $("input#fax_error").val();
		var error_str = '';
		if ((post_error == 'True') || (fax_error == 'True')) {
			if (post_error == 'True') { error_str = 'You have chosen to receive a hard copy of your report by standard post, please provide your full address details.\n' };
			if (fax_error == 'True') { error_str = error_str + 'You have chosen to receive a hard copy of your report by fax, please provide your fax number.' };
			alert(error_str);
			return false;
		} else {
			var process_payment = confirm('You will now be taken to an external page to process your payment. You will be asked to enter your payment details.\nOnce this is completed you will be returned to this site where you can download your files');
			if(process_payment == true) { return true; } else { return false; }
		};
	});
	
	// comment blog form submit
	$("form#commentForm input.submit").click(function(event){
		var showAlert = '';

		if ($("#cName").val() == '') { showAlert += "- Your Name\n"; };
		if ($("#cEmail").val() == '') { showAlert += "- Your Email Address\n"; };
		if ($("#cComment").val() == '') { showAlert += "- Your Comment\n"; };
		if ($("#cSecurity").val() == '') { showAlert += "- Security Code"; };

		if (showAlert != '') {
			alert("Your comment could not be submitted. Please check the following:\n" + showAlert);
			return false;
		} else {
			// check captcha code via AJAX request
			$.ajax({
				type: "POST",
				url: "/includes/captcha_check.asp",
				cache: false,
				data: "cSecurity=" + $("#cSecurity").val(),
				success: checkCaptchaReturn
			});
			return false;
		};
	});


	if ($("div#nameDisclosure_terms").length > 0) {
		// uses an external JS plugin which in only loaded on myaccount.asp
		// loading the following statement on other pages causes JS to fall over
		// see http://groups.google.com/group/fancybox and http://fancybox.net/
		$("#fAllowNameDisclosure").fancybox({
			'onStart': function() { $("div#nameDisclosure_terms").show(); },
			'onCleanup': function() { $("div#nameDisclosure_terms").hide(); },
			'href'				: '#nameDisclosure_terms',
	        'width'             : '75%',
	        'height'            : '75%',
	        'autoScale'         : false,
			'autoDimensions'    : false,
	        'transitionIn'      : 'elastic',
	        'transitionOut'     : 'fade',
			'modal':true
	    });
	};


	$("div#nameDisclosure_terms input.ok").click(function() {
		// user has agreed to terms, we must update their tickbox status
		if ($("form#account input#fAllowNameDisclosure").is(':checked')) {
			$("form#account input#fAllowNameDisclosure").attr('checked', false);
		} else {
			$("form#account input#fAllowNameDisclosure").attr('checked', true);
		};
		$.fancybox.close()
		return false;
	});
	
	$("div#nameDisclosure_terms input.cancel").click(function() {
		// user does not agree to the terms, therefore their tickbox does not get updated
		$.fancybox.close()
		return false;
	});
	
});

// functions to show and hide dropdown menus
var TID;

function hideAll () {
	$("div#menu ul li").each(function() { $("div#" + $(this).attr('id') + "_drop").hide(); });
}

function hideLayer(obj) {
	//SET THE DELAY HERE
	TID = setTimeout(function() { $(obj).fadeOut(500); }, 7000);
}

function showMenu (obj) {
	if (TID != "undefined") { clearTimeout(TID); };
 	hideAll();
	$(obj).show();
	TID = setTimeout(function() { hideLayer(obj); }, 5000);
}

function closeMenu () {
	TID = setTimeout(function() { hideAll(); }, 1000);
}

function autoAdjustMenus() {

}
   
function autoAdjustSuggestions() {
	$("#menuSearchBar,.form_searchBar").each(function() {
		var pos = $(this).offset();
		$("#menuSearchBar_drop").css( { "left": (pos.left) + "px", "top":(pos.top + $(this).outerHeight() - 1) + "px", "width" : ($(this).outerWidth() - 2) + "px" } );
		$("#menuSearchBar_drop ul li").css( { "width" : ($(this).outerWidth() - 7) + "px" } );
	});
}


/*
function closeMenu() {
	//(var i = startingLayer; i <= numLayers; i++) {
	for (var id = 1; id <= numLayers; id++) {
		document.getElementById("layer" + id).style.display = 'none';
		//alert("layer" + id)
	}
}

function showMenu(id) {
	closeMenu();
	document.getElementById("layer" + id).style.display = 'block';
	//alert(id);
}
*/

//adjust position of submenus

function setLyr(obj,lyr)
{
	var coors = findPos(obj);
	var x = document.getElementById(lyr);
	//alert(lyr)
	coors[1] += 28; // adjust for padding, border, margin. Vertical position
	coors[0] -= 47; // adjust for padding, border, margin. Horizontal position
	if (ie6) {coors[0] += 425;}
	if (ie7) {coors[0] -= 502;}
	x.style.top = coors[1] + 'px';
	x.style.left = coors[0] + 'px';
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function processCart(responseXML) { 
    // 'responseXML' is the XML document returned by the server; we use 
    // jQuery to extract the content of the message node from the XML doc 
 	var status = $('status', responseXML).text();
	var message = $('message', responseXML).text();
	var numberReports = $('reportsTotal', responseXML).text();
	var listReports = $('reportsList', responseXML).text();
	var lastReport = $('lastReport', responseXML).text();
	var lastAction = $('lastAction', responseXML).text();
	var reportsCost = $('reportsCost', responseXML).text();
	var post = $('post', responseXML).text();
	var fax = $('fax', responseXML).text();
	var thetype = $('thetype', responseXML).text();

	if(window.console) { console.log('status:' + status + '\nmessage:' + message + '\nnumberReports:' + numberReports + '\nlistReports:' + listReports + '\nlastReport:' + lastReport + '\nlastAction:' + lastAction + '\nreportsCost:' + reportsCost + '\npost:' + post + '\nfax:' + fax + '\nthetype:' + thetype); };
	switch (status) {
		case "ok":
			if (lastAction != 'check') {
				$("span.cartNumber").html("(" + numberReports + ")");

				$("span.cartNumber").animate({ color: "#00B3D6" }, "slow")
		            .animate({ color: "#000000" }, "slow");

				if ($("span.cartCost").length > 0) { 
					$("span.cartCost").html(reportsCost);
					$("span.cartCost").animate({ color: "#00B3D6" }, "slow")
			            .animate({ color: "#000000" }, "slow");
				};			

				if ((lastAction == 'remove') && (message == 'Report removed from cart')) {
					$("tr#reportRow_" + lastReport).hide();
				}

				if ((message.length > 0) && (lastAction != 'check')) { alert(message); };
			};
			
  			break;
		case "error":
  			alert(message);
  			break;
		default:
			//alert(message);
	};
}

function checkCaptchaReturn (responseXML) {
    // 'responseXML' is the XML document returned by the server; we use
    // jQuery to extract the content of the message node from the XML doc

	var captchaStatus = $('status', responseXML).text();
	var captchaMessage = $('message', responseXML).text();
	switch (captchaStatus) {
		case "ok":
//	  		alert(captchaMessage);
			$('#commentForm').submit();
	  		break;
		case "error":
			$("#cSecurity").val('');
			$("img#security").attr("src", "/includes/security.asp?random=" + new Date().getTime());
	  		alert(captchaMessage);
	  		break;
		default:
	  		alert(captchaMessage);
	}
}
