// Main JS file
// Kevin McGill | Elephant Head Productions | 28 April 2010

var includePath = ('https:' == document.location.protocol ? '/vs148640_secure/' : '/ssl/');

$(document).ready(function(){
	// find the pageID and therefore the id of the selected menu li
	var pageID = $("body").attr("id");
	pageID = pageID.substring(0,pageID.indexOf("-", 0));

	$("div#menu ul#nav li#" + pageID + " ol").addClass("current");

	var isIE6 = false;
	var leftDiff = 1;
	if (($.browser.msie) && ($.browser.version == "6.0")) isIE6 = true;
	if (isIE6 == true) {
		// leftDiff = (WINDOW WIDTH - CONTAINER WIDTH - CONTAINER PADDING) / 2
		leftDiff = parseInt($(window).width() - $("div#container").width() - 22)/2;
	};

	// auto adjust all drop-down menus (except current selected menu item) to appear in correct place
	$("div#menu ul#nav li:not(#" + pageID + ", .pipe)").each(function() {
		var pos = $(this).offset();
  		$(this).children("ol").css( { "left": (pos.left - leftDiff) + "px", "top":(pos.top + $(this).height() + 1) + "px" } );
	});	

	// main navigation rollover code
	// caters for rollovers on main menu and subsequent dropdown menu, only where the menu item is not current selected page item
	$("div#menu ul#nav li:not(#" + pageID + ") ol").hide();
	$("div#menu ul#nav li:not(#" + pageID + ")").hover(
		function () { $(this).children("ol").fadeIn("fast"); },
		function () { $(this).children("ol").fadeOut("fast"); }
	);

	// load the flash into on the home page if user validation NOT required
	if (($("#home-page").length > 0) && ($("div#cookie_validation").length == 0)) {
		loadFlash();
	};

	if (($("#splash-page").length == 0) && ($("#legal-page").length == 0) && ($("div#cookie_validation").length > 0)) {
		// load modal frame

		$.fancybox(
			{
			'onStart': function() { $("div#cookie_validation").show(); },
			'onCleanup': function() { $("div#cookie_validation").hide(); },
			'href': '#cookie_validation',
			'autoScale': false,
			'autoDimensions': false,
			'width': 600,
			'height': 400,
			'padding': 30,
			'transitionIn': 'fade',
			'transitionOut': 'fade',
			'centerOnScroll': true,
			'padding': 10,
			'margin': 0,
			'modal': true
			}
		);
	};

	$("form#agreement input").click(function() {
		$.ajax({
 			type: "GET",
 			url: "splash.asp",
			dataType: "json",
 			//success: processCart
			success: function(msg){
				if(window.console) { console.log(msg); };
				if(msg.status == "ok") {
					parent.$.fancybox.close();
					loadFlash(); // user has been validated, now load the home page flash animation (if possible)
					return false;
				} else {
					alert("Please check that cookies are enabled on your browser");
					return false;
				};
			}
		});

	});

	$("form#trade_section select[name='trade']").change(function() {
		$("form#trade_section").submit();
	});

	$("a[rel=file]").attr("target","_blank");
	
	$("a.iframe").fancybox({
		'transitionIn':	'fade',
		'transitionOut': 'fade',
		'scrolling': 'auto',
		'titleShow': false,
		'height': 440,
		'centerOnScroll': true
	});

	$("#popup-page a").click(function() {
		parent.$.fancybox.close();
		return false;
	});
	
	// tooptips to appear on the order page using QTIP jquery plugin
	if ($("#buy-page").length > 0) {
		$('a[rel=tooltip]').click(function() { return false; });
		load_tooltips();
	};
	
	$("form#order-form select.qty").change(function() {
		$(this).parent().prev().animate({ color: '#B6161C' }, 100)
			.animate({ color: '#666' }, 1000);
		$.ajax({
 			type: "POST",
 			url: includePath + "public/includes/ajax.asp?action=order-form",
			cache: false,
 			data: $("#order-form").serialize(),
 			dataType: "json",
 			//success: processCart
			success: function(msg){
				if(window.console) { console.log(msg); };
				if(msg.status == "ok") {
					$(".total_pre").animate({ height: 'toggle' }, 200, function() { $('.total_pre').text(msg.total_pre); })
					.animate({ height: 'toggle' }, 200);
				};
			}
		});
	});
	
	$("form#order-form input#fDeliveryStreet1").change(function() { $("input#fBillingStreet1").val($(this).val()); });
	$("form#order-form input#fDeliveryStreet2").change(function() { $("input#fBillingStreet2").val($(this).val()); });
	$("form#order-form input#fDeliverySuburb").change(function() { $("input#fBillingSuburb").val($(this).val()); });

	$("form#order-form select#fDeliveryCountry").change(function() {
		$("input#fBillingCountry").val($("select#fDeliveryCountry option:selected").text());
		if($(this).val() == "") { $("input#fBillingCountry").val(""); };
		var i, options;
		$("select#fDeliveryState").html('<option value="">Please Choose</option>');
		$.ajax({
 			type: "POST",
 			url: includePath + "public/includes/ajax.asp?action=checkout-2",
			cache: false,
 			data: $("#order-form").serialize(),
 			dataType: "json",
 			//success: processCart
			success: function(msg){
				if(window.console) { console.log(msg); };
				if(msg.status == "ok") {
					options = '<option value="">Please Choose</option>';
					for (i = 0; i < msg.states[1].length; i++) {
						options += '<option value="' + msg.states[0][i] + '">' + msg.states[1][i] + '</option>';
					};
					$("select#fDeliveryState").html(options);
					$("select#fDeliveryState").parent().show("slow");
				} else {
					$("select#fDeliveryState").html('<option value="">Please Choose</option>');
					$("select#fDeliveryState").parent().hide("fast");
					$("input#fDeliveryPostcode").parent().hide("fast");
				};
			},
			error: function(msg){
				$("select#fDeliveryState").html('<option value="">Please Choose</option>');
				$("select#fDeliveryState").parent().hide("fast");
				$("input#fDeliveryPostcode").parent().hide("fast");
			}
		});
	});

	$("form#order-form select#fDeliveryState").change(function() {
		$("input#fBillingState").val($("select#fDeliveryState option:selected").text());
		if($(this).val() != "") {
			$("input#fDeliveryPostcode").parent().show("slow");
		} else {
			$("input#fDeliveryPostcode").parent().hide("fast");
			$("input#fBillingState").val("");
		};
	});
	
	$("form#order-form input#calc_freight").click(function() {
		$("input#fBillingPostcode").val($("input#fDeliveryPostcode").val());
		var originalButtonVal = $(this).val();
		$(this).val("Thinking ...");
		$.ajax({
 			type: "POST",
 			url: includePath + "public/includes/ajax.asp?action=postcode",
			cache: false,
 			data: $("#order-form").serialize(),
 			dataType: "json",
 			//success: processCart
			success: function(msg){
				if(window.console) { console.log(msg); };
				if(msg.status == "ok") {
					updateFreightDetails(true, msg.freightDesc, msg.freightName, msg.freightRate, msg.type, msg.suburb, msg.freightPostcode, msg.orderTotal);
					$("input#calc_freight").val(originalButtonVal);
				} else {
					updateFreightDetails(false, "", "", "", "", "", "", "");
					$("input#calc_freight").val(originalButtonVal);
					alert("Please enter a valid postcode");
				};
			},
			error: function(msg){
				if(window.console) { console.log(msg); };
				updateFreightDetails(false, "", "", "", "", "", "", "");
				$("input#calc_freight").val(originalButtonVal);
				alert("Please enter a valid postcode");
			}
		});
	});

	$("form#order-form input#validate_discount").click(function() {
		var originalButtonVal = $(this).val();
		$(this).val("Thinking ...");
		$.ajax({
 			type: "POST",
 			url: includePath + "public/includes/ajax.asp?action=discount",
			cache: false,
 			data: $("#order-form").serialize(),
 			dataType: "json",
			success: function(msg){
				if(window.console) { console.log(msg); };
				if(msg.status == "ok") {
					updateDiscountDetails(true, msg.discountPercent, msg.discountCode);
					$("input#validate_discount").val("Thank you");
					$("input#validate_discount").attr('disabled','disabled');
					alert("Thank you, your coupon has been redeemed.\nPress the Continue button below to display the discount.");
				} else {
					updateDiscountDetails(false, "", "");
					$("input#validate_discount").val(originalButtonVal);
					alert("Sorry, there was a problem with the coupon code you provided.");
				};
			},
			error: function(msg){
				if(window.console) { console.log(msg); };
				updateDiscountDetails(false, "", "");
				$("input#validate_discount").val(originalButtonVal);
				alert("Sorry, there was a problem with the coupon code you provided.");
			}
		});
	});

	$("form#order-form fieldset.billingDetails input:radio").change(function() {
		if ($(this).val() == "false") {
			$("input#fBillingStreet1").parent().show("slow");
			$("input#fBillingStreet2").parent().show("slow");
			$("input#fBillingSuburb").parent().show("slow");
			$("input#fBillingState").parent().show("slow");
			$("input#fBillingPostcode").parent().show("slow");
			$("input#fBillingCountry").parent().show("slow");
		} else {
			$("input#fBillingStreet1").parent().hide("fast");
			$("input#fBillingStreet2").parent().hide("fast");
			$("input#fBillingSuburb").parent().hide("fast");
			$("input#fBillingState").parent().hide("fast");
			$("input#fBillingPostcode").parent().hide("fast");
			$("input#fBillingCountry").parent().hide("fast");
		};
	});
	
	$("input#finalise_transaction").fancybox({
		'onStart': function() { $("div#processing_cart").show(); },
		'onCleanup': function() { $("div#processing_cart").hide(); },
		'href': '#processing_cart',
		'autoScale': true,
		'autoDimensions': true,
		'padding': 30,
		'transitionIn': 'elastic',
		'transitionOut': 'fade',
		'centerOnScroll': true,
		'modal':true
	});

	$("div#processing_cart .cancel").live("click", function() {
		$.fancybox.close();
		return false;
	});

	$("div#processing_cart input#process_transaction").click(function() {
		$("div#processing_cart h1").text("Your payment is now being processed ...");
		$("div#processing_cart p strong").text("Do not use the back or forward buttons during this process.");
		$("div#processing_cart p#loading").slideDown("fast");
		$("div#processing_cart form").hide();
		$.ajax({
 			type: "POST",
 			url: includePath + "public/includes/ajax.asp?action=payment",
			cache: false,
 			dataType: "json",
 			success: function(msg){
				if(window.console) { console.log(msg); };
				if(msg.status == "ok") {
					$("div#processing_cart h1").text("Thank you");
					$("div#processing_cart p strong").html(msg.message);
					$("div#processing_cart p#loading").slideUp("fast");
				} else {
					$("div#processing_cart h1").text("There was a problem");
					$("div#processing_cart p strong").html(msg.message);
					$("div#processing_cart p#loading").slideUp("fast");
				};
			},
			error: function(msg){
				$("div#processing_cart h1").text("There was a problem");
				$("div#processing_cart p strong").html("<a href='#' class='cancel'>Please try again</a>");
				$("div#processing_cart p#loading").slideUp("fast");
			}
		});
		return false;
	});

	$('a[rel=info]').each(function() {
		$(this).qtip({
			content: {
				text: $(this).next('.kill').html(), // Use the tooltip attribute of the element for the content
				title: { text: $(this).attr('title') } // Use the title attribute of the element for the content
			},
			position: {
				corner: { target: 'topRight', tooltip: 'bottomLeft' },
				adjust: { screen: true } // Keep the tooltip on-screen at all times
			},
			hide: { delay: 300, when: 'mouseout', fixed: true },
			style: {
				width: 350,
				border: { width: 4, radius: 10 },
				background: '#FFF',
				color: '#666',
				padding: 10,
				textAlign: 'left',
				tip: true, // Give it a speech bubble tip with automatic corner detection
				name: 'blue' // Style it according to the preset 'blue' style
			}
		});
	});

});

function updateFreightDetails (isOK, freightDesc, freightName, freightRate, type, suburb, postcode, total) {
	$("#freightDesc").html(freightDesc);
	$('a[rel=tooltip]').qtip("destroy"); // Disables the tooltip
	load_tooltips();
	$("#freightDetails").html("<strong>" + postcode + "</strong> : " + freightRate);
	$("h1#orderTotal").text(total);
	$("#freightName").text(freightName);
	$("#freightRate").text(freightRate);
	$("#freightType").text(type);
	$("input#fDeliverySuburb").val(suburb);
	$("input#fBillingSuburb").val(suburb);

	if (isOK == true) {
		$("div.pre_freight").hide("fast");
		$("div.post_freight").slideDown("slow");
		$("input#fDeliveryStreet1").parent().show("slow");
		$("input#fDeliveryStreet2").parent().show("slow");
		$("input#fDeliverySuburb").parent().show("slow");
		$("textarea#fDeliveryInstructions").parent().show("slow");
	} else {
		$("div.post_freight").hide("fast");
		$("div.pre_freight").slideDown("slow");
		$("input#fDeliveryStreet1").parent().hide(0);
		$("input#fDeliveryStreet2").parent().hide(0);
		$("input#fDeliverySuburb").parent().hide(0);
		$("textarea#fDeliveryInstructions").parent().hide(0);
	};
};

function updateDiscountDetails (isOK, discountPercent, discountCode) {

	$("h1#discountPercent").text(discountPercent + " off");

	if (isOK == true) {
		$("div.discount_details").slideDown("slow");
	} else {
		$("div.discount_details").hide("fast");
	};
};

function load_tooltips() {
	$('a[rel=tooltip]').each(function() {
		$(this).qtip({
			content: {
				text: $(this).next().html() + "<br /><a href='" + $(this).attr('href') + "' target='_blank'>more &gt;</a>", // Use the tooltip attribute of the element for the content
				title: { text: $(this).attr('title') } // Use the title attribute of the element for the content
			},
			position: {
				corner: { target: 'topRight', tooltip: 'bottomLeft' },
				adjust: { screen: true } // Keep the tooltip on-screen at all times
			},
			hide: { delay: 300, when: 'mouseout', fixed: true },
			style: {
				width: 350,
				border: { width: 4, radius: 10 },
				background: '#FFF',
				color: '#666',
				padding: 10,
				textAlign: 'left',
				tip: true, // Give it a speech bubble tip with automatic corner detection
				name: 'blue' // Style it according to the preset 'blue' style
			}
		});
	});
};

/*
loads the flash animation on the home page
is auto-called if current page is home page AND user validation not required
is also called after user is validated (when user validation is required)
*/
function loadFlash() {
	if ($("#home-page").length > 0) {
		$('#hp-animation').flash(
			{
			src: '/ssl/public/flash/cumulus_web1_13.swf',
			width: 950,
			height: 492,
			wmode: 'transparent'
			},
			{ version: 8, update: false }
		);
	};
};
