$(function() {

	$('input.ratingStar').rating();

	// Pretty Photo
	prettyPhotoInit();

	// Hack to fix issue: Product listing: 'Free' badge doesn't line up when there are less than the normal numbers of items per row.
	for (i = $('.productList tr:last-child td').length; i < 4; i++) {
		$('.productList tr:last-child').append('<td></td>');
	}		

	// Hack to fix youtube video home webkit alignment display issue
	if (jQuery.browser.webkit) {
		$('.youtubeHome').css('padding-left', '13px');
		$('.youtubeHome').css('padding-top', '10px');
	}

	// default dialogs
	$("#errorMessage").dialog({
		autoOpen: false,
		width: 310,
		close: function(){
			$("#errorMessage").dialog('option', 'width', 310);
			$("#errorMessage").html("");
			$("#errorMessage").dialog('option', 'buttons', {});
			}
	});
	
	$('#noticeMessage').dialog({
		autoOpen: false,
		width: 310,
		close: function(){
			$("#noticeMessage").dialog('option', 'width', 310);
			$("#noticeMessage").dialog('option', 'buttons', {});
			$("#noticeMessage").html("");
			}
	});


	// Load product ratings
	if ($('#product_id').val()) {
		$('#changeMemberCommentsPane > a').click(function(e) {
			e.preventDefault();
			$('#memberComments').load($(this).attr('href'), { product_id: $('#product_id').val() });
		});
		$('#memberComments').load('/comments/average-rating', { product_id: $('#product_id').val() });
	}

	// Ajax Dialogs
	$("#dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		width: 890,
		height: 600,
		open: function() {
			prettyPhotoInit();
		},
		close: function() {
			$("#dialog").html("");
		}
	});
	$(".dialog").click(function(e) {
		e.preventDefault();
		$("#dialog").load($(this).attr("href")).dialog('open');
	});

	$(".toggle").toggleVal("active");

	$('#closeChat').live('click',removeAlertMessage);
	$('#chatRoomList a').click(function(e) {
		e.preventDefault();
		var thisRoom = $(this).attr('href');
		$("#alertOverlay").show();
		$('body').append('<div id="chatOverlay"></div>');
		$('#chatOverlay').load(thisRoom); 
		$('#chatOverlay').show(); 
	});
	
	$('a>img').parent('a').css('textDecoration','none');
	
	$('#rateMe').siblings('a').hover(
      function () {
        rating($(this).attr('title'));
      }, 
      function () {
        off($(this).attr('title'));
      }
    );
	
	$('a.starrate').click(function () { 
      rateIt($(this).attr('title'));
	  return false;
    });

	// Select field contents
	$("input[type=text]").focus(function(){
		this.select();
	});	
		
	$("#commentType").change(onSelectChange); 

	// Enforce integers
	$(".int").keypress(function(e) {
		if (e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
			return false;
		}
	});

	// Stop pasting in certain fields
	$('.noPaste').keydown(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if (e.ctrlKey && (code==86 || code==118)) {
			e.preventDefault();
			return false;
		}
	});
	
	$("#changeMemberCommentsPane a").click(function () { 
	  $(this).addClass("selected");
	  $(this).siblings('a').removeClass('selected');
	  return false;
    });
	
	//initialise the slider by hiding all the child divs
	$('.slide_content').hide();
	//Toggle the divs (which divs, what is this?)
	$('.slide_header').toggle (function() {
		$('.slide_content').hide();
		$(this).next('.slide_up').css('display', 'block'); 
		$(this).next().slideDown('fast');
		//$('#header3').css("opacity", "0.4");
	}, function() {
		$('.slide_content').slideUp('fast');	// SL - 1/02/2010 - we now have two slide_content panes
		//$(this).next().slideUp('fast');
		//$('#header3').css("opacity", "1");
	});

	// Confirm certain link clicks
	$(".confirm").click(function(e) {
		return(confirm("Really?"));
	});

	// Date Inputs
	$('.date_input').each(function() {
		$(this).date_input();
	});

	// Apply delete links
	$(".delete").live("click", attachAjaxDeleteEvent);

	// Expiry warning on My Account page
	if ($('#expiryWarning').length && $.cookie('noReminder') != 'true') {
		$("#alertOverlay").show();
		$("#expiryWarning").fadeIn(200);
		$('#renewButton').click(function() {
			window.location = 'subscribe/renew/';
		});
	}

	// TODO: BROWSER TESTING
	$('#noReminder').live('click', function() {
		$.cookie('noReminder', true, { expires: 14 });
	});
	$("#alertOverlay").live('click', removeAlertMessage);
	$('.removeAlertMessage').live('click', removeAlertMessage);

	var remember = $.cookie('remember');
	if ( remember == 'true' ) {
		var username = $.cookie('username');
		var password = $.cookie('password');
		// autofill the fields
		$('#loginUsername').attr("value", username);
		$('#loginPassword').attr("value", password);
		$('#sideLoginUsername').attr("value", username);
		$('#sideLoginPassword').attr("value", password);
		$("#remember").attr('checked', true);
		$("#sideRemember").attr('checked', true);
	}
	
	// Cart
	attachCartEvents();

	
	// Form validation
	$("form").submit(function() {
		var alertMessage = "";
		$(this).find(".required").each(function() {
			if ($(this).val()=="" || $(this).val()==$(this).attr("rel")) {
				alertMessage += $(this).attr("rel")+" is required\n";
			}
		});
		if ($(this).find("#passwordc").length!=0 && $(this).find("#passwordc").val()!=$(this).find("#password").val()) {
			alertMessage += "Passwords do not match\n";
		}
		if ($(this).find("#emailc").length!=0 && $(this).find("#emailc").val()!=$(this).find("#email").val()) {
			alertMessage += "Emails do not match\n";
		}
		if ($(this).find("input[name=postageOption]").length && $(this).find("input[name=postageOption]:checked").length==0) {
			alertMessage += "You must select a Postage Method\n";
		}
		if ($(this).find(".iAgree").length != $(this).find(".iAgree:checked").length) {
			window.location = window.location.pathname + "#iAgree";
			alertMessage += "You must agree to our Terms and Conditions\n";
		}
		if (alertMessage.length) {
			alert(alertMessage);
			return false;
		}
		return true;
	});

	$("#topLoginLink").click(function(e) {
		e.preventDefault();
		storeLoginDetails('loginForm');
		$("#loginForm").submit();
	});
	
	$("#downloadLink").live('click', function(e) {
		e.preventDefault();
		if ($("#loginForm").length > 0 && $('.freeResource').length == 0) {
			alertMessage("Please ensure you have a valid subscription to our website, and are logged in. The Sign-In form is at the top of the screen.");
			return false;
		}
		if ($("#font_id").length > 0 && $("#font_id").val()=='') {
			alertMessage("Please select a font");
			return false;
		}
		$("#downloadForm").submit();
	});

	$("#newsletterSubscribeForm").ajaxForm(function(d){
		$('#newsletterSubscribeLink').show();
		alert(d);
	});

	/*
	$('#newsletterSubscribeLink').live('click', function() {
		$(this).hide();
	});
	*/

	// Checkout, accordian information display for Postage Options
	function clickPostageOption() {
		$("#postageOptions,#paymentOptions").find("input[type=radio]").parent().siblings("div").slideUp(200);
		$("#postageOptions,#paymentOptions").find("input[type=radio]:checked").parent().siblings("div").slideDown(200);
	}
	$("#postageOptions,#paymentOptions").find("input[type=radio]").click(clickPostageOption);
	clickPostageOption();

	$("#sameAsAbove").click(function() {
		if ($(this).attr('checked')) {
			//$("#deliveryAddressDetails").slideUp(200);
			$("input[type=text],select").each(function() {
				if ($(this).attr("rev")) {
					$(this).val($("select[name="+$(this).attr("rev")+"],input[name="+$(this).attr("rev")+"]").val());
				}
			});
			// adding extra code for other state
			if ($("#deliveryState").val()=="Other")
			{
				$("#deliveryStateOtherSpan").show();					
				$("#deliveryStateOther").focus();
				document.getElementById("deliveryStateOther").value=document.getElementById("stateOther").value
			}
			else
			{
				$("#deliveryStateOtherSpan").hide();					
				document.getElementById("deliveryStateOther").value="";
				document.getElementById("stateOther").value="";	
			}		
		}
	});

	$("#state, #occupation").change(doOtherValidate);
	$("#state, #occupation").each(doOtherValidate);
	
	$("#occupation").change(function() {
		if ($(this).val()=="Other") {
			$("#grade").hide();
		}
		else {
			$("#grade").slideDown();
		}
	});
	$("input[name^='grade']").click(function() {
		if ($("input[name^='grade']:checked").length > 3) {
			alert("You can only select 3 grades");
			return false;
		}
	});	
	
    jQuery('#mycarousel').jcarousel({
        auto: 2,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });	
	
});

function doOtherValidate() {
	if ($(this).val() == 'Other') {
		$(this).nextAll(".other_validate").show().addClass('required');
		$(this).nextAll(".other_validate_label").show();
	} else {
		$(this).nextAll(".other_validate").hide().removeClass('required');
		$(this).nextAll(".other_validate_label").hide();
	}
	return false;
}

function attachCartEvents() {
	$("#addToCart").live('click',function(e) {
		e.preventDefault();
		if ($("#cart_font_id").length > 0 && $("#cart_font_id").val()=='') {
			alert("Please select a font");
			return false;
		}
		if ($("#paper_size").length > 0 && $("#paper_size").val()=='') {
			alert("Please select a paper size");
			return false;
		}
		$("#addToCartForm").submit();
	});
	$("#updateCart, .updateCart").live('click',function(e) {
		e.preventDefault();
		$("#cartForm").submit();
	});
	$(".removeItemFromCart").live('click',function(e) {
		e.preventDefault();
		$($(this).siblings("input")[0]).val(0);
		$("#cartForm").submit();
	});
	$("#addCartInput, #checkout").bind("blur",  function(e){
		$("#cartForm").submit();	
	});
	$("a.save_cart").click(function () {
		i = 0;
		saveString = new Array;
		$("tr.item").each(function(e) {
			// ID | link | img | description | quantity | pages | size | price
			saveString[i] = $(this).find("td.description").attr('id')+'|'+$(this).find("td.description>a").attr('href')+'|'+'/'+'|'+$(this).find("td.description>p").text()+'|'+$(this).find("td.quantity>input").val()+'|'+$(this).find("td.pages").text()+'|'+$(this).find("td.size").text()+'|'+$(this).find("td.currency").text();
			++i;
		});	
		alert('Cart saved');
		initCookie();
		$.cookie('cart',saveString.toString());
		return false;
	});
	$("a.load_cart").live("click",  function(){
		loadCart();
		return false;
	});
}

function mycarousel_initCallback(carousel) {
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function attachAjaxDeleteEvent(e) {
	e.preventDefault();
	var parentRow;
	//TODO: tr/li branch untested!
	if ($(this).parents("tr")[0]) {
		parentRow = $(this).parents("tr")[0];
	}
	else if ($(this).parents("li")[0]) {
		parentRow = $(this).parents("li")[0];
	}
	if (confirm("Really Delete?")) {
		$.get($(this).attr("href"), function(d) {
			if (d=="Success") {
				$(parentRow).hide();
			}
			else alert("UNEXPECTED RESPONSE FROM SERVER: "+d);
		});
	}
}

function initCookie(){
	$.cookie('cart', '0', { expires: 7 });	
}	
function getCookie(){
	var data = $.cookie('cart').split(",");
	return(data);
}
function loadCart(){
	data = getCookie();
	//element = new Array;
	var arLen=data.length;
	for ( var i=0, len=arLen; i<len; ++i ){
		element = data[i].split("|");
		loadString = '<tr class="item"><td class="description" id="'+element[0]+'" colspan="2"><a href="'+element[1]+'" title="View '+element[3]+'"><img src="'+element[2]+'" alt="" />'+element[3]+'</a></td><td class="quantity"><input type="text" name="quantity['+element[0]+']" value="'+element[4]+'" id="addCartInput" /><a href="cart/remove/id/'+element[0]+'" class="removeItemFromCart" title="Remove">&nbsp;&nbsp;&nbsp;&nbsp;</a></td><td>'+element[5]+'</td><td class="size">'+element[6]+'</td><td class="currency">'+element[7]+'</td></tr>';	
	}
	$('#cart>tbody').append(loadString);
	alert('Cart loaded');
}

function alertMessage(msg) {
	alert(msg);
}

function storeLoginDetails(formId) {
	var remember;
	var username;
	var password;

	if (formId=='loginForm' && $('#remember').attr('checked')) {
		remember = true;
		username = $('#loginUsername').val();
		password = $('#loginPassword').val();
	}
	else if (formId=='sideLoginForm' && $('#sideRemember').attr('checked')) {
		remember = true;
		username = $('#sideLoginUsername').val();
		password = $('#sideLoginPassword').val();
	}
	else {
		remember = false;	// Unknown formId
	}

	if (remember) {
		//console.log('remember: '+username+','+password);
		$.cookie('username', username, { expires: 14 });	//, secure: true 
		$.cookie('password', password, { expires: 14 });	//, secure: true 
		$.cookie('remember', true, { expires: 14 });
	} else {
		//console.log('forget');
		$.cookie('username', null);
		$.cookie('password', null);
		$.cookie('remember', null);
	}
}

function removeAlertMessage(e) {
	e.preventDefault();
	$("#alertOverlay,.alertMessage,#chatOverlay").fadeOut(200, function() {
		if ($('#chatOverlay').length > 0) {
			$('#chatOverlay').remove();
		}
	});
}

// For comment section
function onSelectChange(){
	if ($('#commentType option:selected').val() == "review") {
		$("div#starRating").css('display','inline').focus(); 
	} else {
		$("div#starRating").css('display','none'); 
	}
}

function prettyPhotoInit() {
	$("a[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.35, /* Value betwee 0 and 1 */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'light_rounded' /* light_rounded / dark_rounded / light_square / dark_square */
	});
}

// For toggling input boxes
jQuery.fn.toggleVal=function(focusClass){this.each(function(){$(this).focus(function()
{if($(this).val()==this.defaultValue){$(this).val("")}if(focusClass)
{$(this).addClass(focusClass)}}).blur(function(){if($(this).val()=="")
{$(this).val(this.defaultValue)}if(focusClass){$(this).removeClass(focusClass)}})})}
