/// <reference path="jquery-1.3.2.js" />

$(document).ready(function() {

	$('.search').keyup(function(e) {
		if (e.which == 13 || e.keyCode == 13) {
			e.preventDefault();
			$(this).parent().find(".small-button").click();
		}
	});

	$('.password').keyup(function(e) {
		if (e.which == 13 || e.keyCode == 13) {
			e.preventDefault();
			$(this).parent().find(".small-button").click();
		}
	});

	$('.LoginPassword').keyup(function(e) {
		if (e.which == 13 || e.keyCode == 13) {
			e.preventDefault();
			$(this).parent().parent().parent().find(".button").click();
		}
	});

	$('.js-clear').each(function() {
		$(this).attr("value2", $(this).attr("value"));
	});

	$('.js-clear').focus(function() {
		if ($(this).attr("value2") == $(this).attr("value")) {
			$(this).attr("value", "");
		}
	});

	$('.js-clear').blur(function() {
		if ("" == $(this).attr("value")) {
			$(this).attr("value", $(this).attr("value2"));
		}
	});

	$('.fullscreen').css("height", $(document).height());
	$('.fullscreen').css("width", $(document).width());

	// only flip between to images
	var count = 2;

	// if frontpage flip between 6
	if ($(".frontpage").hasClass("yes"))
		count = 7;

	// background flipping
	var i = Math.floor(Math.random() * count + 1);
	$('#content').css("background", "url('/css/images/overridable/trollbeads-0" + i + ".png') 10px 10px no-repeat");

	// toggles delivery address
	$(".same .checkbox input").click(function(e) {
		if ($(this).attr("checked") == true)
			$('.delivery-address').show();
		else
			$('.delivery-address').hide();
	});

	if ($(".same .checkbox input").attr("checked") == true)
		$('.delivery-address').show();
	else
		$('.delivery-address').hide();


	// shows 300x300px img of product on product page
	$(".product .image img").hover(function() {
		$(".product .big").attr("src", $(this).attr("srcBig"));
		$(".product .big").attr("srcBig", $(this).attr("srcFull"));
	});

	// shows the popup on products on category page
	$(".relative-catch").hover(
      function() {
      	var p = $(this).position();
      	$(this).find(".popup").css("left", p.left - 21).css("top", p.top + 80).show();
      },
      function() {
      	$(this).find(".popup").hide();
      }
    );

	// shows edit address on edit profile page
	$("input.edit-address").click(function(e) {
		$(this).parent().parent().hide().next().show();
	});

	// shows edit address on edit profile page
	$("input.create-address").click(function(e) {
		$(this).hide().next().show();
	});

	// hides edit address on edit profile page
	$("div.edit-address input.button").click(function(e) {
		$(this).parent().parent().parent().parent().parent().hide().prev().show();
	});

	// hides/shows a group of products on category
	$(".toggle").click(function(e) {
		var isHidden = true;

		if ($(this).hasClass("minus"))
			isHidden = false;

		var obj = $(this).parent();
		while (obj.next().hasClass("relative-catch")) {
			obj = obj.next();

			if (isHidden)
				obj.show();
			else
				obj.hide();
		}

		$(this).find("img").attr("alt", "Show group");
		$(this).find("img").attr("title", "Show group");

		if (isHidden) {
			$(this).find("img").attr("src", "/css/images/minus.gif");
			$(this).removeClass("plus");
			$(this).addClass("minus");
		}
		else {
			$(this).find("img").attr("src", "/css/images/plus.gif");
			$(this).removeClass("minus");
			$(this).addClass("plus");
		}
	});

	$(".toggleOrderHistory").click(function(e) {
		var isHidden = true;

		if ($(this).hasClass("minus"))
			isHidden = false;

		var obj = $(this).parent().parent().next();

		if (isHidden)
			obj.show();
		else
			obj.hide();


		$(this).find("img").attr("alt", "Show group");
		$(this).find("img").attr("title", "Show group");

		if (isHidden) {
			$(this).find("img").attr("src", "/css/images/minus.gif");
			$(this).removeClass("plus");
			$(this).addClass("minus");
		}
		else {
			$(this).find("img").attr("src", "/css/images/plus.gif");
			$(this).removeClass("minus");
			$(this).addClass("plus");
		}
	});

	// show large image on product page
	$(".big, .spyglass").click(function(e) {
		$(".view img").attr("src", $(".big").attr("srcBig"))
		$(".view img").attr("alt", $(".big").attr("alt")); ;
		$(".view img").attr("title", $(".big").attr("title"));
		$(".view").show();
		$(".fullscreen").show();
	});

	// hides fullscreen overlay and large image on product page
	$(".fullscreen, .view").click(function(e) {
		$(".fullscreen").hide();
		$(".view").hide();
	});

	// shows add wishlist edit fields on wishlist page
	$("a.add-wishlist").click(function(e) {
		$("table.add-wishlist").show();
	});

	// hides add wishlist edit fields on wishlist page
	$("table.add-wishlist input:button").click(function(e) {
		$("table.add-wishlist").hide();
	});

	// shows wishlists on product page
	$(".add-to-wishlist").click(function(e) {
		if ($("ul.wishlists").css('display') == 'none') {
			$("ul.wishlists").show();
		}
		else {
			$("ul.wishlists").hide();
		}
	});

	// hides wishlists on product page
	$("ul.wishlists").click(function(e) {
		$("ul.wishlists").hide();
	});

	// hides wishlists on product page
	$(".add-item").click(function(e) {
		var val = $(this).parent().next().html().substring(1);
		if ($(this).attr("checked") == true) {
			$(this).parent().next().next().html("€" + val);
			$(".order-total").html("€" + ($(".order-total").html().substring(1) - (-val)));
		}
		else {
			$(this).parent().next().next().html("€0");
			$(".order-total").html("€" + ($(".order-total").html().substring(1) - val));
		}
		/* TODO calc VAT */
	});

	// prints page
	$(".print").click(function() {
		window.print();
		return false;
	});

	// shows cards on checkout page
	$(".card").click(function() {
		if ($(this).attr("checked") == true) {
			$(".cards").show();
		}
		else {
			$(".cards").hide();
		}
	});

	// hides ie6 warning
	$(".ie6 .close").click(function() {
		$(this).parent().hide();
	});

	// updates scroll text
	$('.scroll-textarea').keyup(function() {
		var text = $(this).html();

		//hacks
		for (x = 0; x < 100; x++) {
			text = text.replace('\n', '<br />');
		}

		$('.show-final').html(text);
	});

	$('.check-scroll').click(function() {
		var maxLetters = 10;
		var maxLines = 10;

		var text = $('.scroll-textarea').html();

		if (text.length > maxLetters * maxLines) {
			alert("Too many letters, maximum is " + maxLetters + " letters per line and maxium " + maxLines + " lines in total.");
		}

		var text = text.split(' ');

		for (y = 0; y < text.length; y++) {
			var lines = text[y].split('\n');
			for (x = 0; x < lines.length; x++) {
				if (lines[x].length > 10) {
					alert("The word: " + lines[x] + " is too low, maximum is " + maxLetters);
					return false;
				}
			}
		}

	});

	$('.edit-scroll').click(function() {
		$(this).next().show();
	});

	$('.edit-scroll-textarea input').click(function() {
		$(this).parent().parent().parent().parent().parent().hide();
	});

	// Personal information section

	// Invoice
	$("input.rb-inv").click(function(e) {
		clearHighlightInvoice();
		$(this).parents(".address").addClass("selected");
	});
	$("input.rb-inv-new").click(function(e) {
		clearHighlightInvoice();
		$(this).parents(".newaddress .address").addClass("selected");
	});
	$(".td-inv-new input").bind("focus", function(e) {
		$("input.rb-inv-new").trigger("click");
	});
	function clearHighlightInvoice() {
		$(".invoice-address .address").removeClass("selected");
	}

	// Delivery 
	$("input.rb-del").click(function(e) {
		clearHighlightDelivery();
		$(this).parents(".address").addClass("selected");
	});
	$("input.rb-del-new").click(function(e) {
		clearHighlightDelivery();
		$(this).parents(".newaddress .address").addClass("selected");
	});
	$(".td-del-new input").bind("focus", function(e) {
		$("input.rb-del-new").trigger("click");
	});
	function clearHighlightDelivery() {
		$(".delivery-address .address").removeClass("selected");
	}

	// Ensure selection on postback/validation
	$("input.rb-inv:checked").trigger("click");
	$("input.rb-inv-new:checked").trigger("click");
	$("input.rb-del:checked").trigger("click");
	$("input.rb-del-new:checked").trigger("click");


	// Engraving section
	$(".engravingLine input").change(function() {
		$(this).next(".engravingLineDisplay").text($(this).val());
	});

	$('.small-login .password-clear').show();
	$('.small-login .password-password').hide();
	
	$('.small-login .password-clear').focus(function() {
		$('.small-login .password-clear').hide();
		$('.small-login .password-password').val('')
		$('.small-login .password-password').show();
		$('.small-login .password-password').focus();
	});

	$('.small-login .password-password').blur(function() {
		if ($('.small-login .password-password').val() == '') {
			$('.small-login .password-clear').show();
			$('.small-login .password-password').hide();
		}
	});

	$('.small-login .js-clear').each(function() {
		$(this).attr("value2", $(this).attr("title"));
	});

});

function showEngravings(itemId) {
    $(".engravingsContainer").removeClass("engravingsContainerDisplay");
    $("#engraving" + itemId).show();
    $(".editText").hide();
}
function hideEngravings() {
    $(".engravingsContainer").addClass("engravingsContainerDisplay");
    $(".editText").show();
}

function highlightError(doHighlight, widgetId) {
    if (doHighlight) $('.' + widgetId).addClass('error');
}

function captureIntro() {
    $('#aspnetForm').keydown(
	function(event) {
	    var keyCode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));

	    if (keyCode == 13) {
	        event.returnValue = false;
	        event.cancel = true;
	        return false;
	    }
	    return true;
	});
}

var maxCount = 5;
var requestInterval = 5000;

function requestIfOrderReady(i, afterMaxCountUrl, requestUrl, jsonData, sucessDataKey) {
    if (i == maxCount) {
        document.location = afterMaxCountUrl;
    }
    $.ajax({
        type: 'POST',
        url: requestUrl,
        contentType: 'application/json; charset=utf-8',
        data: jsonData,
        dataType: 'json',
        success: function(result) { ajaxSucceeded(result, sucessDataKey) },
        error: ajaxFailed
    });
}

function ajaxSucceeded(result, successDataKey) {
    var redirectionUrl = result[successDataKey];
    if (redirectionUrl) {
        document.location = redirectionUrl;
    }
}

function ajaxFailed(result) {
    alert(result.status + ' result: ' + result.statusText);
}

