/****  javascripts ****/

$(document).ready(function() {
	// Watermark
	$.watermarker.setDefaults({ color: "#888",left: -2, top: 0, animDuration: 300, minOpacity: 0.3 });
	$("input, textarea").watermark();
	
	// Addthis sharing
	var addthis_config =
	{
		username: "redani",
		email_template: "moroccan_arts_" + lang_iso_4,
		ui_language: lang_iso_2
	}
	
	// Change language tooltip
	$("a#change-lang, a#nav-theme").hover(function() {
		$("#tt-" + $(this).attr('id')).stop(true).fadeTo(300, 1);
	}, function() {
		$("#tt-" + $(this).attr('id')).stop(true).fadeTo(200, 0, function() { $(this).hide(); });
	});
	$(".tt-language, .nav-theme").hover(function() {
		$(this).stop(true).show().fadeTo(300, 1);
	}, function() {
		$(this).stop(true).fadeTo(200, 0, function() { $(this).hide(); });
	});
	
	
	// Sub menu tooltips
	$("#menu-sub a").hover(function() {
		$(this).addClass("menu-sub-active");
		$("#tt-" + $(this).attr('id')).stop(true).fadeTo(300, 1);
	}, function() {
		$(this).removeClass("menu-sub-active");	
		$("#tt-" + $(this).attr('id')).stop(true).fadeTo(200, 0, function() { $(this).hide(); });
	});
	$(".tt-menu-sub").hover(function() {
		var link_active = $(this).attr('id').substr(3);
		$("#menu-sub a#" + link_active).addClass("menu-sub-active");
		$(this).stop(true).show().fadeTo(300, 1);
	}, function() {
		$("#menu-sub a").removeClass("menu-sub-active");
		$(this).stop(true).fadeTo(200, 0, function() { $(this).hide(); });
	});
	
	
	// Login / forgot password scrollable
	$("#login").scrollable({ next: '#anext', prev: '#aprev', onBeforeSeek: function() { $('.error-login').hide(); } });
	
	// Log in
	$("#form-login").validator({
		lang: lang_iso_2,
		position: 'top left',
		offset: [-3, 40],
		message: '<div><em/></div>' // em element is the arrow
	}).submit(function(e) {
		if(!e.isDefaultPrevented()) { // client-side validation OK
			return login(this, "/account/ajax/login.php");
		}
		e.preventDefault(); // prevent default form submission
	});

	// Forgot password
	$("#form-forgot-pwd").validator({
		lang: lang_iso_2,
		position: 'top left',
		offset: [-3, 40],
		message: '<div><em/></div>' // em element is the arrow
	}).submit(function(e) {
		if(!e.isDefaultPrevented()) {
			return login(this, "/account/ajax/forgot-pwd.php");
		}
		e.preventDefault();
	});
	
	// Log out from all pages and also when prompted to logout if we want to set up a new account
	$("#logout").click(function() {
		$.post("/account/ajax/logout.php", function() {
			location.reload();
		});
		return false;
	});
	
	// disable copy/paste for the email_confirm and pwd_confirm fields
	$("#email-confirm, #pwd-confirm").bind('paste', function(e){
		return false;
	});
	
	// get the phone code based on the current country
	$("#form-new-account #phone").focus(function() {
		var field = $(this);
		if(field.val().length < 2) {
			$.get("/account/ajax/get-phone-code.php?id_country=" + $("#id-country").attr('value'), function(phone) {
				field.val("+" + phone + " ").siblings(".watermark").hide(); // the .sibling is to hide the watermark
			});
		}
	});
	
	// Scroll to with animation
	$(".scroll-to").click(function() {
		$.scrollTo($($(this).attr("href")), {
			duration: 750
		});
		return false;
	});
	
	// display "available soon" when focus on search field
	$("#form-search #kw").focus(function() {
		if(!$(this).val()) $.get("/inc/ajax/search-requests.php?add=1"); // excecute this line only once
		$(this).val(coming_soon).blur();
		return false;
	});
	
	
//***** {{ Validator elements
	// tooltips to illustrate the input fields
	$("#form-contact-info [title], #form-address-book [title], #form-add-prod [title], .form-update-prod [title]").tooltip({
		position: "center right",
		offset: [0, 6],
		effect: "fade",
		tipClass: "tooltip-form",
		opacity: 0.7,
		events: {
			input: "focus mouseenter,blur mouseleave",
			tooltip: ""
		}
	});
	
	// supply the errors translation. the variables are defined in jscript.js.php
	$.tools.validator.localize(lang_iso_2, {
		'*'			: correct_value,
		':email'	: correct_email,
		':number'	: correct_number,
		':url'		: correct_url,
		'[max]'	 	: correct_max_val,
		'[min]'		: correct_min_val,
		'[required]': correct_mandatory_field,
		'[data-equals]': correct_equal
	});
	
	// localization of the jquery Dateinput
	$.tools.dateinput.localize(lang_iso_2, {
	   months		: month1 + ',' + month2 + ',' + month3 + ',' + month4 + ',' + month5 + ',' + month6 + ',' + month7 + ',' + month8 + ',' + month9 + ',' + month10 + ',' + month11 + ',' + month12,
	   shortMonths	: month_short1 + ',' + month_short2 + ',' + month_short3 + ',' + month_short4 + ',' + month_short5 + ',' + month_short6 + ',' + month_short7 + ',' + month_short8 + ',' + month_short9 + ',' + month_short10 + ',' + month_short11 + ',' + month_short12,
	   days			: day7 + ',' + day1 + ',' + day2 + ',' + day3 + ',' + day4 + ',' + day5 + ',' + day6,
	   shortDays	: day_short7 + ',' + day_short1 + ',' + day_short2 + ',' + day_short3 + ',' + day_short4 + ',' + day_short5 + ',' + day_short6
	});
	
	
	// check the char length
	$.tools.validator.fn("[minlength]", function(input, value) {
		var min_char = input.attr("minlength");
		return value.length >= min_char ? true : correct_min_char.replace("$1", min_char);
	});
	
	// check if the value of 2 fields are equal
	$.tools.validator.fn("[data-equals]", function(input) {
		var name = input.attr("data-equals"),
		field = this.getInputs().filter("[name=" + name + "]"); 
		return input.val() == field.val() ? true : [name]; 
	});
	
	
	// check if the email exists on email field blur
	$("#form-contact-info #email, #form-new-account #email").blur(function() {
		check_email_exists($(this).val());
	});
	
	// jquery Dateinput
	$("#birthday").dateinput({
		lang: lang_iso_2,
		format: format_date_input,	// the format displayed for the user
		selectors: true, // whether month/year dropdowns are shown
		speed: 'fast', // calendar reveal speed
		firstDay: 1, // which day starts a week. 0 = sunday, 1 = monday etc..
		yearRange: [-75, 1],
		change: function() { // a different format is sent to the server
			var dt = this.getValue('yyyy-mm-dd');
			$("#dt-birthday").val(dt);
			$("#birthday").siblings(".watermark").hide(); // hide the watermark
		}
	});
//}}***** end of validator elements



//***** {{ Catalogue browser page
	// main vertical scroll
	$("#header-cat #main").scrollable({
		vertical: true,
		next: null,
		prev: null
	}).navigator({
		navi: '#main-navi',
		naviItem: 'a',
		activeClass: 'active',
		history: true
	});
	
	// horizontal scrollables. each one is circular and has its own navigator instance
	$("#header-cat .scrollable").scrollable({ speed: 500 });
	
	var ie6 = ($.browser.msie && $.browser.version < 7) ? true : false;
	if(!ie6) {		
		// change opacity of catalogue browser items on mouseenter and leave
		$("#header-cat .item").children("div").mouseenter(function () {
			$(this).dequeue().animate({ opacity: 1 }, 300);
		}).mouseleave(function () {
			$(this).not("div.active").dequeue().animate({ opacity: 0.4 }, 300);
		});
	}
//}}***** end of Catalogue browser



//***** {{ Product info page
	// Add to cart and preorder form validator
	$("#form-add-cart, #form-preorder").validator({ 
		lang: lang_iso_2,
		position: 'top left', 
		offset: [-3, 40],
		message: '<div><em/></div>'
	}).submit(function(e) {
		if(!e.isDefaultPrevented()) { // client-side validation OK
			if(this.id == "form-add-cart") { // add to cart
				$("#add-to-cart button").attr('disabled', true);
				// slide down the cart tooltip
				$("#ms-cart").addClass("menu-sub-active");
				$("#tt-ms-cart").stop(true).fadeTo(300, 1);
				$("#cart-items .cart-empty").remove();
				$("#cart-items").prepend('<div id="cart-loading"></div>');
				
				var splitter = $("#form-add-cart button").attr("id").split("add-"); // the id of the button are always as follow: add-prod-color1
				var prod = splitter[1]; // the product to be flown
				var productX = $("#" + prod).offset().left;
				var productY = $("#" + prod).offset().top;
				var basketX = $("#ms-cart").offset().left;
				var basketY = $("#ms-cart").offset().top - 40;
				var gotoX = basketX - productX;
				var gotoY = basketY - productY;
				var newImageWidth 	= $("#" + prod).width() / 4;
				var newImageHeight	= $("#" + prod).height() / 4;
				
				$("#" + prod + " img").clone().prependTo("#img-prod-clone").animate({ opacity: 0.4 }, 100).animate({ opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight }, 1000, function() {
					$(this).remove();
					
					$.ajax({
						url: "/cart/ajax/add-to-cart.php",
						data: "id_prod_ref_selected=" + $("#id_prod_ref_selected").val(),
						async: false,
						success: function(cart_item) {
							if(cart_item) $("#menu-sub span#num-prods").html(parseInt($("span#num-prods").html()) + 1); // increment the total items by 1 if the prod still available on stock
							$("#cart-loading").remove();
							if(cart_item.substr(0, 6) == "update") $("div#cart-" + cart_item.substr(7)).fadeTo(400, 0).fadeTo(500, 1).fadeTo(400, 0).fadeTo(500, 1); // if the added product already exists in the cart
							else $("#cart-items").prepend(cart_item).children(".cart-new-item").slideDown(500, function() { $(this).fadeTo(400, 0).fadeTo(500, 1); });
						}
					});
					setTimeout(function() {
						$("#tt-ms-cart").stop(true).fadeTo(200, 0, function() { // use the callback function to prevent conflicts
							$(this).hide();
							$("#ms-cart").removeClass("menu-sub-active");
							$("#add-to-cart button").attr('disabled', false);							
						});
					}, 3000);
				});
			}
			else { // preorder a product
				var msg_preorder = $(".msg-ajax-preorder");
				msg_preorder.hide();
				
				$.post("/inc/ajax/prod-preorder.php", $(this).serialize(), function(preorder) {
					if(preorder.substr(0, 2) == "ok") { // preorder succeded
						msg_preorder.html(preorder.substr(3)).fadeTo(500, 1);
						setTimeout(function() {
							msg_preorder.slideUp();
							$("div.price a[rel]").data("overlay").close();
							$("button#btn-preorder[rel]").data("overlay").close(); // doesnt close the overlay if i put the 2 triggers together!!
						}, 4000); // hide message and box after 4 sec
					}
					else {
						msg_preorder.html(preorder).fadeTo(500, 1); // show error message
						setTimeout(function() { msg_preorder.slideUp(); }, 5000); // hide message after 5 sec
					}
				});
			}
		}
		e.preventDefault(); // prevent default form submission
	});
	
	
	// write a review form validator
	$("#form-write-review").validator({ 
		lang: lang_iso_2,
		position: 'top left', 
		offset: [-3, 130],
		message: '<div><em/></div>' // em element is the arrow
	}).submit(function(e) {
		var form = $(this);
		
		if(!e.isDefaultPrevented()) { // client-side validation OK
			if($(".rates-new .jRatingAverage").width() > 1) { // perform a manual validtion for jRating
				var msg_review = $(".msg-ajax-review");
				msg_review.hide();
				
				$.post("/inc/ajax/prod-rating.php", $(this).serialize(), function(new_review) {
					if(new_review.substr(0, 2) == "ok") { // rating succeded, id_review is always preceded by "ok-"
						$("#rate-write-review textarea, #rate-write-review button").attr("disabled", true);
						$("div#rate-write-review").fadeTo(500, 0, function() { $(this).slideUp(); });
						$("div#rates-reviews").append(new_review.substr(3)).children(".review-container");
						$(".rates-small").jRating({ type: "small" });
					}
					else msg_review.html(new_review).fadeTo(500, 1); // show error message
					setTimeout(function() { msg_review.slideUp(); }, 5000); // hide message after 5 sec
				});
			}
			else { // server-side validation failed. use invalidate() to show errors
				form.data("validator").invalidate({
					"review": correct_review_rating
				});
			}
		}
		e.preventDefault(); // prevent default form submission
	});
	
	// main vertical scroll: different colors
	$("#prod-info #main").scrollable({
		vertical: true,
		next: null,
		prev: null
	}).navigator({
		navi: "#available-colors",
		naviItem: "div"
	});
	
	// different angles of the product
	$("#prod-info .angles").tabs("div.items > div", {
		effect: "fade",
		current: "active",
		tabs: "div"
	});
	
	// update the "add to cart" button id for the flying cart
	var api = $("#prod-info .angles").data("tabs");
	if(api) {
		api.onClick(function(event, index) {
			var id_btn = $("#add-to-cart button[type=submit]").attr("id");
			if(id_btn) {
				id_btn = id_btn.substr(0, id_btn.length - 1) + (index + 1);
				$("#add-to-cart button").attr("id", id_btn);
			}
		});
	}
	
	// update details when the size is being changed
	$("#prod-sizes #sizes").change(function() {
		if($(this).val()) get_new_details($(this).val());
	});
	
	// zoom the image in an overlay
	$(".items span[rel]").overlay({
		top: 20,
		fixed: false,
		mask: { color: "#fff", opacity: 0.6 },
		onBeforeLoad: function() {
			var img = this.getTrigger().attr("id");
			$("#img-zoom-content").hide().html('<img src="/'+ img +'">').fadeIn();
		}
	});
	
	// overlay
	$("div.price a[rel], button#btn-preorder[rel]").overlay({ effect: "apple", top: "20%" });
	
	// image preloader
	$("#prod-info .items").preloader();
	
	// related products scroll
	$("#related-prod .scrollable").scrollable();

//}}***** end of product info scripts



//***** {{ Cart page
	// remove the item on click
	$("#cart .remove").click(function() {
		var splitter = $(this).attr('id').split("-");
		var id_prod_ref = splitter[2];
		$(this).parent(".cart-item").addClass('bg-loading-big').fadeTo(400, 0.6);
		remove_product(id_prod_ref);
	});
	
	
	// change quatity by clicking on the arrows
	$("#cart .tri-up, #cart .tri-down").click(function() {
		var splitter = $(this).attr('id').split("-");
		var action = splitter[0];
		var id_prod_ref = splitter[2];
		var input_fld = $("input#qty-" + id_prod_ref);
		if(action == "add") {
			input_fld.val(parseInt(input_fld.val()) + 1); // increment the quantity
			update_cart(id_prod_ref);
		}
		else {
			if(input_fld.val() > 0) {
				input_fld.val(parseInt(input_fld.val()) - 1); // decrement the quantity
				if(input_fld.val() == 0) remove_product(id_prod_ref); // if quantity = 0, remove the product from the cart
				else update_cart(id_prod_ref);
			}
		}
	});
	
	
	// change the quantity directly from the input field
	$("#cart .field-qty input").keyup(function() {
		var splitter = $(this).attr('id').split("-");
		var id_prod_ref = splitter[1];
		var val = $(this).val();
		
		if(val < 0 || !val || isNaN(val)) {
			$(this).val(1);
			$(this).keyup();
		}
		else if(val == 0) {
			$(this).parents(".cart-item").addClass('bg-loading-big').fadeTo(400, 0.6);
			remove_product(id_prod_ref);
		}
		else update_cart(id_prod_ref);
		//$(this).blur();
	});
	
	
	// submit the voucher
	$("#form-apply-voucher").submit(function() {
			$.ajax({
				url: "/cart/ajax/apply-voucher.php",
				data: $(this).serialize(),
				dataType: "json",
				success: function(data) {
					if(data.response == 1) {
						if(data.msg) {
							var msg_ajax = $(".msg-ajax-voucher");
							msg_ajax.hide().html(data.msg).fadeTo(500, 1); // show error message
							setTimeout(function() { msg_ajax.slideUp(); }, 5000); // hide message after 5 sec
						}
						if(data.discount) $("#discount").hide().html(data.discount).fadeIn(600);
						if(data.total) $("#total").hide().html(data.total).fadeIn(600);
					}
				}
			});				
		return false; // prevent default form submission
	});
	
	// remove a saved cart
	$("#saved-carts a.remove").click(function() {
		var splitter = $(this).attr('id').split("-");
		var id_cart = splitter[2];
		$("#saved-carts #cart-" + id_cart).addClass('bg-loading-big').fadeTo(400, 0.6);
		remove_saved_cart(id_cart);
	});
	
	// get the cart's content and fetch it in the overlay
	$("#order-status a[rel]").overlay({
		top: "20%",
		mask: { color: "#fff", loadSpeed: 200, opacity: 0.5 },
		onBeforeLoad: function() {
			var id_order = this.getTrigger().attr("id");
			$.post("/cart/ajax/get-cart-order.php", { id_order: id_order }, function(cart) {
				$("#cart-order-content").fadeOut(200, function() { $(this).html(cart).fadeIn(); });
			});
		}
	});

//}}***** end of cart scripts


//***** {{ Checkout page
	// set the opacity of the carrier except the selected one
	$(".checkout #shipping-method .carriers").not("div.active").animate({ opacity: 0.3 }, 2000);
	
	// change opacity of the carrier on mouseenter and leave
	$(".checkout #shipping-method .carriers").mouseenter(function () {
		$(this).dequeue().animate({ opacity: 1 }, 300);
	}).mouseleave(function () {
		$(this).not("div.active").dequeue().animate({ opacity: 0.3 }, 300);
	});
	
	// update the shipping cost if changed
	$(".checkout #shipping-method .carriers").click(function () {
		var meth = this.id;
		var id_h2 = $("#form-card-info h2").attr("id"); // used to know if the payment has been processed, in this case, disable the clicks on the carriers logo
		if(id_h2 != "payed") {
			$.ajax({
				url: "/cart/ajax/update-shipping.php",
				data: "meth="+ meth,
				dataType: "json",
				success: function(data) {
					$(".checkout #shipping-method .carriers").removeClass("active").dequeue().animate({ opacity: 0.3 }, 300);
					$("#" + meth).addClass("active").dequeue().animate({ opacity: 1 }, 300);
					$("span#shipping").hide().html(data.shipping).fadeIn(600);
					$("span#total").hide().html(data.total).fadeIn(600);
				}
			});
		}
	});
	
	// select the type of credit card regarding the entered number
	$(".checkout #card-number").keyup(function() {
		var num = $(this).val();
		var num_first = num.substr(0, 1);
		var elmt = $(".checkout #card-selector li");
		
		if(num.length > 0 && !elmt.hasClass('selected')) { // automaticaly select the type of card only if it hasn't been done manually
			if(num_first == 4) {
				elmt.not("li#visa").animate({ opacity: 0.3 }, 200);
				elmt.siblings("li#visa").animate({ opacity: 1 }, 200);
				$(".checkout #card-type").val('visa');
			}
			else if(num_first == 5) {
				elmt.not("li#mastercard").animate({ opacity: 0.3 }, 200);
				elmt.siblings("li#mastercard").animate({ opacity: 1 }, 200);
				$(".checkout #card-type").val('mastercard');
			}
			else {
				elmt.animate({ opacity: 1 }, 200);
				$(".checkout #card-type").val('');
			}
		}
		else if(!elmt.hasClass('selected')) {
			elmt.animate({ opacity: 1 }, 200);
			$(".checkout #card-type").val('');
		}
	});
	
	// select manually the type of credit card
	$(".checkout #card-selector li").click(function() {
		var card = this.id;
		
		$(this).siblings().animate({ opacity: 0.3 }, 200).removeClass("selected");
		$(this).animate({ opacity: 1 }, 200);
		$(this).addClass("selected"); // to tell if the selection has been done manually
		$(".checkout #card-type").val(card);
		$("div.error").hide();
		if(card == "paypal") $("div#card-payment").hide();
		else $("div#card-payment").show();
	});
	
	// tabs
	$(".checkout ul.tabs").tabs("div.tabs-panes > div", {
		onBeforeClick: function() { $(".error").hide(); }
	});
	
	// tooltip for the card security code
	$(".checkout #info-csc").tooltip({ position: "top center", tip: ".tooltip-form", effect: "slide"});
	
	// form validator and process payment
	$("#form-card-info").validator({
		lang: lang_iso_2,
		position: 'top left',
		offset: [-3, 10],
		message: '<div><em/></div>' // em element is the arrow
	}).submit(function(e) {
		var form = $(this);
		var card_type = $(".checkout #card-type").val();
		var payment = $("ul.tabs a.current").attr('id'); // credit card or bank transfert
		
		if(payment == "card") {
			// initialize the overlay
			var ol = $("#order-process").overlay({
				api: true,
				top: "35%",
				mask: { color: "#fff", loadSpeed: 200, opacity: 0.8 },
				closeOnEsc: false,
				closeOnClick: false
			});
			
			if(card_type == "paypal") { // paypal express checkout. no form validation
				$("#overlay-content").html(please_wait_redirecting_paypal);
				ol.load();
				$("#overlay-content").removeClass('payment-error').addClass('bg-loading-big');
				$("#order-process a.close, div.error").hide(); // hide the close button of the overlay and errors
				
				$.ajax({
					url: "/cart/ajax/payment.php",
					data: form.serialize(),
					dataType: "json",
					success: function(res) {
						if(res.ok == "y") {
							window.location = res.redirect;
						}
						else {
							$("#overlay-content").removeClass('bg-loading-big').addClass('payment-error').html(res.msg);
							$("#order-process a.close").show();
						}
					}
				});
			}
			else {
				if(!e.isDefaultPrevented()) { // client-side validation OK
					if(card_type) { // if a type of credit card is selected
						$("#overlay-content").html(please_wait_processing_payment);
						ol.load();
						$("#overlay-content").removeClass('payment-error').addClass('bg-loading-big');
						$("#order-process a.close").hide(); // hide the close button of the overlay
						
						$.ajax({
							url: "/cart/ajax/payment.php",
							data: form.serialize(),
							dataType: "json",
							success: function(res) {
								if(res.ok == "y") {
									ol.close();
									$("#payment-form").addClass('payment-done').html(res.msg);
									$(".edit, button.btn").remove();
									$("#form-card-info h2").attr("id", "payed"); // to disable click on the carriers logo
								}
								else {
									$("#overlay-content").removeClass('bg-loading-big').addClass('payment-error').html(res.msg);
									$("#order-process a.close").show();
								}
							}
						});
					}
					else {
						form.data("validator").invalidate({ "card_type": card_select });
					}
				}
			}
		}
		else {
			$("#payment-transfert").val('y');
			$("div.error").hide();
			$.ajax({
				url: "/cart/ajax/payment.php",
				data: form.serialize(),
				success: function(msg) {
					$("#payment-form").addClass('payment-done').html(msg);
					$(".edit, button.btn").remove();
					$("#form-card-info h2").attr("id", "payed"); // to disable click on the carriers logo
				}
			});
		}
		e.preventDefault(); // prevent default form submission
	});

//}}***** end of Checkout


	// Browsers warning
	$.reject({
		//reject: { all: true }, // Reject all renderers for demo
		header: 'Did you know that your Internet Browser is out of date?', // Header Text
		paragraph1: 'Your browser is out of date, and may not be compatible with our website. A list of the most popular web browsers can be found below.', // Paragraph 1
		paragraph2: 'Just click on the icons to get to the download page', // Paragraph 2
		closeLink: 'Close This Window', // Text for closing link
		closeMessage: 'By closing this window you acknowledge that your experience on this website may be degraded', // Message below close window link
		closeCookie: true, // Set cookie to remember close for this session
		imagePath: '/img/browsers/' // Path where images are located
	});
});


/**********************************************/
/********** General jquery functions **********/
/**********************************************/

(function($){

	/***** update account information or create an account *****/
	account = function(form, url) {
		form = $(form).fadeTo(300, 0.4); //start fading the div while processing
		var msg_ajax = $(".msg-ajax-tab");
		msg_ajax.hide();
		
		$.ajax({
			type: "POST",
			url: url,
			data: form.serialize(),
			async: false,
			success: function(msg) {
				form.fadeTo(500, 1);
				if(msg.substr(0, 2) == "ok") msg_ajax.html(msg.substr(3)).fadeTo(500, 1); // update succeded, the message is always preceded by "ok-"
				else msg_ajax.html(msg).fadeTo(500, 1); // show error message
				setTimeout(function() { msg_ajax.slideUp(); }, 5000); // hide message after 5 sec
			},
			error: function(xhr, stat, err) {
				msg_ajax.html(an_error_has_occured_short).fadeTo(500, 1);
			}
		});
	}
	
	
	/***** check if the email exists to prevent duplicated emails *****/
	check_email_exists = function(email) {
		// Error container
		var msg_ajax = $(".msg-ajax-tab");
		var email_exists;
		msg_ajax.hide();
		
		$.ajax({
			url: "/account/ajax/check-email-exists.php",
			data: "email=" + email + "&token=" + token,
			async: false,
			success: function(msg) {
				if(msg) {
					msg_ajax.html(msg).fadeTo(500, 1); // show error message if the email address already exists
					email_exists = true;
				}
				else msg_ajax.slideUp();
			}
		});
		
		return email_exists;
	};
	
	
	/***** log in *****/
	login = function(form, url) {
		form = $(form).fadeTo(400, 0.6); //start fading the div while processing
		$("#loading").fadeTo(400, 0.6);
		
		// Error container
		var msg_err = $(".error-login");
		msg_err.hide();
		
		$.post(url, form.serialize(), function(msg) {
			form.fadeTo(300, 1);
	
			if(msg.substr(0, 2) == "ok") { // identification succeded
				location.href = page_from; // page_from is defined in jscript.js.php file
			}
			else { // identification failed
				$("#loading").fadeTo(300, 0).hide();
				$("#pwd").val("").focus(); // reset the pwd field
				msg_err.html(msg).show(); // show error message
				setTimeout(function() { msg_err.slideUp(); }, 4000); // hide error message after 4 sec
			}
		});
		
		return false; // prevent default form submission
	}
	
	
	/***** insert front page data. to be removed on production *****/
	form_insert = function(form, url) {
		$("button").attr('disabled', true); //disabled the button to prevent a double submission
	
		form = $(form).fadeTo(300, 0.6); //start fading the div while processing
	
		$.post(url, form.serialize(), function(msg) {
			if(msg == "inserted") { // insertion succeded
				$("div#form").slideUp("slow", function () { // hide the form
					$("#msg-ajax-home").fadeIn("slow"); //show the success message
				});
			}
			else { // insertion failed
				form.slideUp("slow", function () { // hide the form						   
					$("#msg-ajax-home").html(msg).addClass("warning").fadeIn("slow"); // show error message
				});
			}
		});
		
		return false; // prevent default form submission
	}
	
	
	/***** Validators: create a function as the same code is for updating an account, crating a new one, changing the password and creating a new one *****/
	validate_submit_account = function(form, url, org) {
		$(form).validator({ 
			lang: lang_iso_2,
			position: 'top left', 
			offset: [0, 40],
			message: '<div><em/></div>' // em element is the arrow
		}).submit(function(e) {
			if(!e.isDefaultPrevented()) { // client-side validation OK.
				if(org == "create") $("button").attr("disabled", true); // prevent double insertion
				var msg_ajax = $(".msg-ajax-tab");
				var email = $("#email").val()
				msg_ajax.hide();
				
				// check if the entered email already exixts in case the form is submited by pressing 'enter' key
				if(!check_email_exists(email)) {
					account(form, url); // update the account
					if(org == "create") setTimeout(function() { location.href = page_from; }, 4000); // redirect to the page we came from after 4 sec if the account has been created. page_from is defined in jscript.js.php file
					else if(org == "checkout") setTimeout(function() { location.href = "/cart/checkout.php"; }, 1000);
				}
				
				return false; // prevent default form submission
			}
		});
	}
	
	validate_submit_pwd = function(form, url) {	
		$(form).validator({ 
			lang: lang_iso_2,
			position: 'top left', 
			offset: [0, 30],
			message: '<div><em/></div>' // em element is the arrow
		}).submit(function(e) {
			if(!e.isDefaultPrevented()) { // client-side validation OK.
				account(form, url);
				if(url.indexOf("new-pwd.php") > 0) setTimeout(function() { location.href = "/account/"; }, 4000); // redirect to /account/ after 4 sec if the password request is made
				return false; // prevent default form submission
			}
		});
	}
	
	
	// get new details of the product
	get_new_details = function(id_prod_ref) {
		$.getJSON("/inc/ajax/get-prod-new-details.php", {id_prod_ref: id_prod_ref, ajax: 'true'}, function(json) {
			if(json.stock == 0) {
				$("button#add_to_cart").hide();
				$("div#add-to-cart").html('<button id="btn-preorder" class="btn orange" rel="#preorder"><span>' + preorder +'</span></button>');
			}
			else {
				$("button#btn-preorder").hide();
				$("div#add-to-cart").html('<button type="submit" class="btn orange"><span class="cart">' + add_to_cart + '</span></button>');
				$("#add-to-cart button").attr("id", "add-prod-" + json.color + "1"); // assign an id attribute to the button for the flying cart
			}
			$("#info div.price").hide().html(json.price).fadeIn(); // update the new product's price
			$("div#details").hide().html(json.details).fadeIn(); // update the new product's details
			$("#id_prod_ref_selected").val(id_prod_ref);
			$("div.price a[rel], button#btn-preorder[rel]").overlay({ effect: "apple", top: "20%" });
		});
	}
	
	// get sizes of a product
	get_new_sizes = function(id_prod, id_color) {
		var selected_size = $("select#sizes").children(":selected").attr("id"); // keep the former size selected when the color is being changed
		// get the new sizes of the selected color
		$.get("/inc/ajax/get-prod-new-sizes.php?id_prod=" + id_prod + "&id_color=" + id_color, function(new_sizes) {
			$("select#sizes").hide().html(new_sizes).fadeIn();
			$("select#sizes option[id=" + selected_size + "]").attr("selected", "selected");
			$.uniform.update("select#sizes");
		});
	}
	
	
	// update the price if the quatity is being changed
	update_cart = function(id_prod_ref) {
		var qty_requested = $("input#qty-" + id_prod_ref).val();
		$.ajax({
			url: "/cart/ajax/update-cart.php",
			data: "qty="+ qty_requested +"&id_prod_ref=" + id_prod_ref,
			dataType: "json",
			success: function(data) {
				if(qty_requested <= data.qty_allowed) { // the requested quantity is available in stock
					$("#menu-sub span#num-prods").html(data.num_items).stop().fadeOut(400, function() { $(this).fadeTo(400, 1); }); // prevent blinking in loop if the user clicks several times in the arrow of quantity
					$("#price-qty-" + id_prod_ref).html(data.total_prod).stop().fadeOut(400, function() { $(this).fadeTo(400, 1); });
					$("#cart_subtotal").html(data.subtotal).stop().fadeOut(400, function() { $(this).fadeTo(400, 1); });
					$("#total").html(data.total).stop().fadeOut(400, function() { $(this).fadeTo(400, 1); });
					$("#vat").html(data.vat).stop().fadeOut(400, function() { $(this).fadeTo(400, 1); });
					if(data.discount) $("#discount").html(data.discount).stop().fadeOut(400, function() { $(this).fadeTo(400, 1); });
					if(data.msg) {
						var msg_ajax = $(".msg-ajax-voucher");
						msg_ajax.hide().html(data.msg).fadeTo(500, 1); // show error message
						setTimeout(function() { msg_ajax.slideUp(); }, 6000); // hide message after 6 sec
					}
				}
				else {
					$("#qty-" + id_prod_ref).val(data.qty_allowed); // update the qty field
					var msg_ajax = $("#qty-prod-" + id_prod_ref);
						msg_ajax.hide().html(data.msg).fadeTo(500, 1);
						setTimeout(function() { msg_ajax.fadeOut(); }, 5000);
				}
			}
		});
	}
	
	// remove a product from the cart and update the price...
	remove_product = function(id_prod_ref) {
		$.ajax({
			url: "/cart/ajax/remove-product.php",
			data: "id_prod_ref=" + id_prod_ref,
			dataType: "json",
			async: false,
			success: function(data) {
				if(data.response == 1) { // the product has been removed from the cart
					// update the tooltip cart
					$("#cart-" + id_prod_ref).hide(); // hide the product from the tooltip cart
					$("#menu-sub span#num-prods").html(data.num_items);
					if(data.num_items < 1) $("#tt-ms-cart #cart-items").html('<p class="cart-empty">' + your_cart_is_empty + '</p>');
					
					// update the main page
					$("#prod-" + id_prod_ref).fadeTo(800, 0).slideUp(300, function() {
						$(this).remove();
						$("#cart_subtotal").html(data.subtotal).fadeOut('slow').fadeIn('slow');
						$("#total").html(data.total).fadeOut('slow').fadeIn('slow');
						$("#vat").html(data.vat).fadeOut('slow').fadeIn('slow');
						if(data.discount) $("#discount").html(data.discount).fadeOut('slow').fadeIn('slow');
						if(data.num_items < 1) $("#cart-content").fadeOut(400, function() { $(this).html('<p class="cart-empty">' + your_cart_is_empty + '</p>').fadeIn(400); });
						if(data.msg) {
							var msg_ajax = $(".msg-ajax-voucher");
							msg_ajax.hide();
							msg_ajax.html(data.msg).fadeTo(500, 1); // show error message
							setTimeout(function() { msg_ajax.slideUp(); }, 6000); // hide message after 6 sec
						}
					});
				}
			}
		});
	}
	
	// remove a saved_cart
	remove_saved_cart = function(id_cart) {
		$.ajax({
			url: "/cart/ajax/remove-saved-cart.php",
			data: "id_cart=" + id_cart,
			dataType: "json",
			success: function(data) {
				if(data.response == 1) { // the saved cart has been removed
					$("#cart-" + id_cart).fadeTo(800, 0).slideUp(300, function() {
						$(this).remove();
						if(data.num_saved_carts < 1) $("#saved-carts").fadeOut(400, function() { $(this).html('<p class="saved-cart-empty">' + you_have_no_saved_carts + '</p>').fadeIn(400); });
					});
				}
			}
		});
	}
	
	
	// country locator
	country_locator = function(id) {
		$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
				$("select#" + id + " option[iso=" + json.address.country_code + "]").attr("selected", "selected");
				$.uniform.update("#" + id);
			});
	}
	
	
	/***** blinker *****/
	$.fn.blink = function(options) {
		var defaults = { delay: 1000 };
		var options = $.extend(defaults, options);
		
		return this.each(function() {
			var obj = $(this);
			setInterval(function() {
				if($(obj).css("visibility") == "visible")$(obj).css('visibility','hidden');
				else $(obj).css('visibility','visible');
			}, options.delay);
		});
	}
	
}(jQuery));


/*
 * jQuery Watermark plugin
 * Version 1.2 (7-DEC-2010)
 * @requires jQuery v1.3 or later
 *
 * Examples at: http://mario.ec/static/jq-watermark/
 * Copyright (c) 2010 Mario Estrada
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
(function(a){var k=a.browser.msie&&a.browser.version<8;a.watermarker=function(){};a.extend(a.watermarker,{defaults:{color:"#999",left:0,top:0,fallback:false,animDuration:300,minOpacity:0.6},setDefaults:function(e){a.extend(a.watermarker.defaults,e)},checkVal:function(e,c){e.length==0?a(c).show():a(c).hide();return e.length>0},html5_support:function(){return"placeholder"in document.createElement("input")}});a.fn.watermark=function(e,c){var i;c=a.extend(a.watermarker.defaults,c);i=this.filter("textarea, input:not(:hidden,:checkbox,:radio,:file,:submit,:reset)");
if(!(c.fallback&&a.watermarker.html5_support())){i.each(function(){var b,f,j,g,d,h=0;b=a(this);if(b.attr("data-jq-watermark")!="processed"){f=b.attr("placeholder")!=undefined&&b.attr("placeholder")!=""?"placeholder":"title";j=e===undefined||e===""?a(this).attr(f):e;g=a('<span class="watermark_container"></span>');d=a('<span class="watermark">'+j+"</span>");f=="placeholder"&&b.removeAttr("placeholder");g.css({display:"inline-block",position:"relative"});k&&g.css({zoom:1,display:"inline"});b.wrap(g).attr("data-jq-watermark",
"processed");if(this.nodeName.toLowerCase()=="textarea"){e_height=b.css("line-height");e_height=e_height==="normal"?parseInt(b.css("font-size")):e_height;h=b.css("padding-top")!="auto"?parseInt(b.css("padding-top")):0}else{e_height=b.outerHeight();if(e_height<=0){e_height=b.css("padding-top")!="auto"?parseInt(b.css("padding-top")):0;e_height+=b.css("padding-bottom")!="auto"?parseInt(b.css("padding-bottom")):0;e_height+=b.css("height")!="auto"?parseInt(b.css("height")):0}}h+=b.css("margin-top")!="auto"?
parseInt(b.css("margin-top")):0;f=b.css("margin-left")!="auto"?parseInt(b.css("margin-left")):0;f+=b.css("padding-left")!="auto"?parseInt(b.css("padding-left")):0;d.css({position:"absolute",display:"block",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),color:c.color,left:4+c.left+f,top:c.top+h,height:e_height,lineHeight:e_height+"px",textAlign:"left",pointerEvents:"none"}).data("jq_watermark_element",b);a.watermarker.checkVal(b.val(),d);d.click(function(){a(a(this).data("jq_watermark_element")).trigger("focus")});
b.before(d).bind("focus.jq_watermark",function(){a.watermarker.checkVal(a(this).val(),d)||d.stop().fadeTo(c.animDuration,c.minOpacity)}).bind("blur.jq_watermark change.jq_watermark",function(){a.watermarker.checkVal(a(this).val(),d)||d.stop().fadeTo(c.animDuration,1)}).bind("keydown.jq_watermark",function(){a(d).hide()}).bind("keyup.jq_watermark",function(){a.watermarker.checkVal(a(this).val(),d)})}});return this}};a(document).ready(function(){a(".jq_watermark").watermark()})})(jQuery);


/*
 * Image preloader
 *
 */
$.fn.preloader = function(options){
	var defaults = {
		delay:200,
		preload_parent:"a",
		check_timer:300,
		ondone:function(){ },
		oneachload:function(image){  },
		fadein:500 
	};
	// variables declaration and precaching images and parent container
	 var options = $.extend(defaults, options),
	 root = $(this) , images = root.find("img").css({"visibility":"hidden",opacity:0}) ,  timer ,  counter = 0, i=0 , checkFlag = [] , delaySum = options.delay ,
	 
	 init = function() {
		timer = setInterval(function(){
			if(counter>=checkFlag.length) {
				clearInterval(timer);
				options.ondone();
				return;
			}
			for(i=0;i<images.length;i++) {
				if(images[i].complete==true) {
					if(checkFlag[i]==false) {
						checkFlag[i] = true;
						options.oneachload(images[i]);
						counter++;			
						delaySum = delaySum + options.delay;
					}
					$(images[i]).css("visibility","visible").delay(delaySum).animate({opacity:1},options.fadein,
					function(){ $(this).parent().removeClass("preloader"); });
				}
			}
			},options.check_timer)
		 } ;
	images.each(function(){
		if($(this).parent(options.preload_parent).length==0)
		$(this).wrap("<a class='preloader' />");
		else
		$(this).parent().addClass("preloader");
		checkFlag[i++] = false;
	}); 
	images = $.makeArray(images); 
	var icon = jQuery("<img />",{
		id : 'loadingicon' ,
		src : '/img/loading.gif'
	}).hide().appendTo("body");
	timer = setInterval(function() {
		if(icon[0].complete==true) {
			clearInterval(timer);
			init();
			icon.remove();
			return;
		}
	},100);
}




/*
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);



/*
* jReject (jQuery Browser Rejection Plugin)
* Version 0.7-Beta
* URL: http://jreject.turnwheel.com/
* Description: jReject gives you a customizable and easy solution to reject/allowing specific browsers access to your pages
* Author: Steven Bower (TurnWheel Designs) http://turnwheel.com/
* Copyright: Copyright (c) 2009-2010 Steven Bower under dual MIT/GPL license.
* Depends On: jQuery Browser Plugin (http://jquery.thewikies.com/browser)
 */
(function(b){b.reject=function(a){a=b.extend(true,{reject:{all:false,msie5:true,msie6:true},display:[],browserInfo:{firefox:{text:"Firefox 3.5+",url:"http://www.mozilla.com/firefox/"},safari:{text:"Safari 4",url:"http://www.apple.com/safari/download/"},opera:{text:"Opera 10.5",url:"http://www.opera.com/download/"},chrome:{text:"Chrome 5",url:"http://www.google.com/chrome/"},msie:{text:"Internet Explorer 8",url:"http://www.microsoft.com/windows/Internet-explorer/"},gcf:{text:"Google Chrome Frame",
url:"http://code.google.com/chrome/chromeframe/",allow:{all:false,msie:true}}},header:"Did you know that your Internet Browser is out of date?",paragraph1:"Your browser is out of date, and may not be compatible with our website. A list of the most popular web browsers can be found below.",paragraph2:"Just click on the icons to get to the download page",close:true,closeMessage:"By closing this window you acknowledge that your experience on this website may be degraded",closeLink:"Close This Window",
closeURL:"#",closeESC:true,closeCookie:false,cookieSettings:{path:"/",expires:0},imagePath:"/images/",overlayBgColor:"#000",overlayOpacity:0.8,fadeInTime:"fast",fadeOutTime:"fast"},a);if(a.display.length<1)a.display=["firefox","chrome","msie","safari","opera","gcf"];b.isFunction(a.beforeReject)&&a.beforeReject(a);if(!a.close)a.closeESC=false;var d=function(c){return(c.all?true:false)||(c[b.os.name]?true:false)||(c[b.layout.name]?true:false)||(c[b.browser.name]?true:false)||(c[b.browser.className]?
true:false)};if(!d(a.reject)){b.isFunction(a.onFail)&&a.onFail(a);return false}if(a.close&&a.closeCookie){var f="jreject-close",h=function(c,g){if(typeof g!="undefined"){var e="";if(a.cookieSettings.expires!=0){e=new Date;e.setTime(e.getTime()+a.cookieSettings.expires);e="; expires="+e.toGMTString()}var k=a.cookieSettings.path||"/";document.cookie=c+"="+encodeURIComponent(g==null?"":g)+e+"; path="+k}else{k=null;if(document.cookie&&document.cookie!="")for(var o=document.cookie.split(";"),n=0;n<o.length;++n){e=
b.trim(o[n]);if(e.substring(0,c.length+1)==c+"="){k=decodeURIComponent(e.substring(c.length+1));break}}return k}};if(h(f)!=null)return false}var i='<div id="jr_overlay"></div><div id="jr_wrap"><div id="jr_inner"><h1 id="jr_header">'+a.header+"</h1>"+(a.paragraph1===""?"":"<p>"+a.paragraph1+"</p>")+(a.paragraph2===""?"":"<p>"+a.paragraph2+"</p>")+"<ul>",l=0;for(var s in a.display){var p=a.display[s],j=a.browserInfo[p]||false;if(!(!j||j.allow!=undefined&&!d(j.allow))){i+='<li id="jr_'+p+'"><div class="jr_icon"></div><div><a href="'+
(j.url||"#")+'">'+(j.text||"Unknown")+"</a></div></li>";++l}}i+='</ul><div id="jr_close">'+(a.close?'<a href="'+a.closeURL+'">'+a.closeLink+"</a><p>"+a.closeMessage+"</p>":"")+"</div></div></div>";var m=b("<div>"+i+"</div>");d=q();i=r();m.bind("closejr",function(){if(!a.close)return false;b.isFunction(a.beforeClose)&&a.beforeClose(a);b(this).unbind("closejr");b("#jr_overlay,#jr_wrap").fadeOut(a.fadeOutTime,function(){b(this).remove();b.isFunction(a.afterClose)&&a.afterClose(a)});b("embed, object, select, applet").show();
a.closeCookie&&h(f,"true");return true});m.find("#jr_overlay").css({width:d[0],height:d[1],position:"absolute",top:0,left:0,background:a.overlayBgColor,zIndex:200,opacity:a.overlayOpacity,padding:0,margin:0}).next("#jr_wrap").css({position:"absolute",width:"100%",top:i[1]+d[3]/4,left:i[0],zIndex:300,textAlign:"center",padding:0,margin:0}).children("#jr_inner").css({background:"#FFF",border:"1px solid #CCC",fontFamily:'"Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif',color:"#4F4F4F",
margin:"0 auto",position:"relative",height:"auto",minWidth:l*100,maxWidth:l*140,width:b.layout.name=="trident"?l*155:"auto",padding:20,fontSize:12}).children("#jr_header").css({display:"block",fontSize:"1.3em",marginBottom:"0.5em",color:"#333",fontFamily:"Helvetica,Arial,sans-serif",fontWeight:"bold",textAlign:"left",padding:5,margin:0}).nextAll("p").css({textAlign:"left",padding:5,margin:0}).siblings("ul").css({listStyleImage:"none",listStylePosition:"outside",listStyleType:"none",margin:0,padding:0}).children("li").css({background:'transparent url("'+
a.imagePath+'background_browser.gif") no-repeat scroll left top',cusor:"pointer","float":"left",width:120,height:122,margin:"0 10px 10px 10px",padding:0,textAlign:"center"}).children(".jr_icon").css({width:100,height:100,margin:"1px auto",padding:0,background:"transparent no-repeat scroll left top",cursor:"pointer"}).each(function(){var c=b(this);c.css("background","transparent url("+a.imagePath+"browser_"+c.parent("li").attr("id").replace(/jr_/,"")+".gif) no-repeat scroll left top");c.click(function(){window.open(b(this).next("div").children("a").attr("href"),
"jr_"+Math.round(Math.random()*11));return false})}).siblings("div").css({color:"#808080",fontSize:"0.8em",height:18,lineHeight:"17px",margin:"1px auto",padding:0,width:118,textAlign:"center"}).children("a").css({color:"#333",textDecoration:"none",padding:0,margin:0}).hover(function(){b(this).css("textDecoration","underline")},function(){b(this).css("textDecoration","none")}).click(function(){window.open(b(this).attr("href"),"jr_"+Math.round(Math.random()*11));return false}).parents("#jr_inner").children("#jr_close").css({margin:"0 0 0 50px",
clear:"both",textAlign:"left",padding:0,margin:0}).children("a").css({color:"#000",display:"block",width:"auto",margin:0,padding:0,textDecoration:"underline"}).click(function(){b(this).trigger("closejr");if(a.closeURL==="#")return false}).nextAll("p").css({padding:"10px 0 0 0",margin:0});b("#jr_overlay").focus();b("embed, object, select, applet").hide();b("body").append(m.hide().fadeIn(a.fadeInTime));b(window).bind("resize scroll",function(){var c=q();b("#jr_overlay").css({width:c[0],height:c[1]});
var g=r();b("#jr_wrap").css({top:g[1]+c[3]/4,left:g[0]})});a.closeESC&&b(document).bind("keydown",function(c){c.keyCode==27&&m.trigger("closejr")});b.isFunction(a.afterReject)&&a.afterReject(a);return true};var q=function(){var a=window.innerWidth&&window.scrollMaxX?window.innerWidth+window.scrollMaxX:document.body.scrollWidth>document.body.offsetWidth?document.body.scrollWidth:document.body.offsetWidth,d=window.innerHeight&&window.scrollMaxY?window.innerHeight+window.scrollMaxY:document.body.scrollHeight>
document.body.offsetHeight?document.body.scrollHeight:document.body.offsetHeight,f=window.innerWidth?window.innerWidth:document.documentElement&&document.documentElement.clientWidth?document.documentElement.clientWidth:document.body.clientWidth,h=window.innerHeight?window.innerHeight:document.documentElement&&document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight;return[a<f?a:f,d<h?h:d,f,h]},r=function(){return[window.pageXOffset?window.pageXOffset:
document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollLeft:document.body.scrollLeft,window.pageYOffset?window.pageYOffset:document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop]}})(jQuery);

/*
    * jQuery Browser Plugin
    * Version 2.3
    * 2008-09-17 19:27:05
    * URL: http://jquery.thewikies.com/browser
    * Description: jQuery Browser Plugin extends browser detection capabilities and can assign browser selectors to CSS classes.
    * Author: Nate Cavanaugh, Minhchau Dang, & Jonathan Neal
    * Copyright: Copyright (c) 2008 Jonathan Neal under dual MIT/GPL license.
*/
(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery);



/***** Google analytics script *****/
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-19327435-1']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


