// UTF8‼
/*Cufon
.replace('h1,h2,h3,h4,h5,h6,#nav,#content .buttoninline,#content .buttoninline2,#nav .buttoninline2,#foot .buttoninline',{
	fontFamily:'Copperplate Gothic Bold'
})
.replace('h1,h2', {
	color:'-linear-gradient(#f0e0b8,#e1c180)',
	textShadow:'0 0 white'
});*/

var a_slides_stack = [];

$(document).ready(function() {

	$('html').addClass('jquery-active');
	
	// Products Drop Down (Use a timer to delay closing the menu)
	var navproductsmenutimer = null;
	var navproductslinkclass = $('#nav-products').attr('class');
	$('#nav-products, #nav-products-menu').bind('mouseenter',function(){
		clearTimeout(navproductsmenutimer);
		$('#nav-products-menu').slideDown(250);
		//$('#nav-products').addClass('selected');
	}).bind('mouseleave',function(){
		navproductsmenutimer = setTimeout(function(){
			if (navproductslinkclass != 'selected') {
				//$('#nav-products').removeClass('selected');
			}
			$('#nav-products-menu').slideUp(150);
		},500);
	});

	// Owners Drop Down (Use a timer to delay closing the menu)
	var navownersmenutimer = null;
	var navownerslinkclass = $('#nav-owners').attr('class');
	$('#nav-owners, #nav-owners-menu').bind('mouseenter',function(){
		clearTimeout(navownersmenutimer);
		$('#nav-owners-menu').slideDown(250);
		$('#nav-owners').addClass('selected');
	}).bind('mouseleave',function(){
		navownersmenutimer = setTimeout(function(){
			if (navownerslinkclass != 'selected') {
				$('#nav-owners').removeClass('selected');
			}
			$('#nav-owners-menu').slideUp(150);
		},500);
	});
	
	// Technical Drop Down (Use a timer to delay closing the menu)
	var navtechmenutimer = null;
	var navtechlinkclass = $('#nav-tech').attr('class');
	$('#nav-tech, #nav-tech-menu').bind('mouseenter',function(){
		clearTimeout(navtechmenutimer);
		$('#nav-tech-menu').slideDown(250);
		$('#nav-tech').addClass('selected');
	}).bind('mouseleave',function(){
		navtechmenutimer = setTimeout(function(){
			if (navtechlinkclass != 'selected') {
				$('#nav-tech').removeClass('selected');
			}
			$('#nav-tech-menu').slideUp(150);
		},500);
	});

	// Slideshow 
	if (typeof(a_slides_bank) != 'undefined') {
		for (var i = 0; i < a_slides_bank.length; i++) { 
			// Check If Image Exists
			if ($('#slides img[src="' + a_slides_bank[i]['src'] + '"]').length != 1) {
				// Preload Images Before Adding To Slideshow
				var img = $('<img />',{
					'src':a_slides_bank[i]['src'],
					'alt':a_slides_bank[i]['alt'],
					'width':a_slides_bank[i]['width'],
					'height':a_slides_bank[i]['height']
				});
				// Click isn't being passed through to slideshow properly
//				if (a_slides_bank[i]['href']) {
//					var href = a_slides_bank[i]['href'];
//					$(img).css({'cursor':'pointer'}).addClass(href).click(function(){
//						//alert(i);
//						//return false;
//						//location.href=href;
//					});
//				}
				$(img).bind('load',function(){ 
					a_slides_stack.push(this);
				});
			}
		}  
		// Start Slideshow 
		$('#slides').cycle({
			slideExpr:'img',
			timeout:1000, 
			before:f_slides_add 
		}); 
	};
	
	$('#recipe_print').click(function(){
		window.print();
	});

	// Load Order Totals
	$.post(v_url_root + "store/cart/index.codebehind.php",{
		'v_action':'Load Totals'
	},function(data){
		f_ord(data.t_ord[0]);
		// Customer Logout Link
		if (typeof data.v_cst_liu != 'undefined' && $('#accountlink_out').length == 0) {
			$('#accountlink_acc').after('<li><a href="' + v_url_root + 'store/customer/logoff/">Log Out</a></li>');
		}
	},"json");
	
	// Nullify Cart Update Button
	$("#v_f_cart_update").click(function(){return false;});

	$('#v_f_cart_view').click(function(){
		if ($(this).text() == "View My Cart") {
			$("#cart").addClass("open");
			$("#cart-contents").empty().append($("<p/>").addClass("product").append("Loading…"));
			$(this).text('Hide My Cart');
			// Load Products
			$.post(v_url_root + "store/cart/index.codebehind.php",{
				'v_action':'Load Products'
			},function(data){
				f_ord_prd(data.t_ord_prd);
			},"json");
		} else {
			$(this).text("View My Cart");
			$("#minicart-contents").slideUp("fast",function(){
				$("#cart").removeClass("open");
				$("#minicart-discount,#minicart-delivery,#cart-actions,#minicart-total").hide();
			});
		}
/*		Cufon.replace('#nav .buttoninline2',{
			fontFamily:'Copperplate Gothic Bold'
		});*/
		return false;
	});

	// Category Page Products
	$("#category .product")
	.css({'cursor':'pointer'})
	.hover(
		function(){
			$(this).addClass("hover");
		},function(){
			$(this).removeClass("hover");
		}
	)
	.click(function(){
		location.href = $(this).find("a").attr("href");
	});

});

// Add images to slideshow 
function f_slides_add(curr,next,opts) { 
	if (opts.addSlide) // <-- important! 
		while(a_slides_stack.length) 
			opts.addSlide(a_slides_stack.pop());  
}; 

var delay_ord_disc_code;

// Display Order Totals
function f_ord(a_ord) {
	
	$("#minicart-contents").hide();
	if (typeof a_ord == 'undefined' || a_ord === false) {
		var v_cntry_tr = '0%';
		var v_ord_total_inctax = "<span>£0</span>.00";
	} else {
		
		var v_cntry_tr = a_ord.v_cntry_tr;
		var v_ord_total_inctax = "<span>" + a_ord.v_ord_total_inctax.substring(0,a_ord.v_ord_total_inctax.indexOf(".")) + "</span>" + a_ord.v_ord_total_inctax.substring(a_ord.v_ord_total_inctax.indexOf("."),a_ord.v_ord_total_inctax.length);

		// Update/Insert Discount
		if ($("#minicart-discount").length == 0) {
			$("<div/>").attr("id","minicart-discount").hide().insertBefore('#minicart-total');
			$("#minicart-discount")
				.append($('<label/>').attr("for","v_ord_disc_code"))
				.append($('<input/>').attr("type","text").attr("id","v_ord_disc_code"))
		}
		$("#minicart-discount label").text(a_ord.v_ord_disc_label);
		$("#v_ord_disc_code")
			.val(((a_ord.v_ord_disc_code != null) ? a_ord.v_ord_disc_code : ''))
			.removeAttr('readonly')
			.keyup(function(){
				var v_ord_disc_code = $(this).val();
				clearTimeout(delay_ord_disc_code);
				delay_ord_disc_code = setTimeout(function(){
					$("#v_ord_disc_code").attr('readonly','readonly');
					$("#minicart-discount label").text('Please Wait…');
					$.post(v_url_root + "store/cart/index.codebehind.php",{
						'v_action':'Order Discount',
						'v_ord_disc_code':v_ord_disc_code
					},function(data){
						if (typeof data.Message != 'undefined') {
							alert(data.Message);
						}
						if (typeof data.Error == 'undefined') {
							// Refresh Order Total
							f_ord(data.t_ord[0]);
						}
					},"json");
				},750);
			});
		// Update/Insert Delivery Total
		if ($("#minicart-delivery").length == 0) {
			$("<div/>").attr("id","minicart-delivery").insertBefore('#minicart-total');
		}
		$("#minicart-contents").slideDown("fast");
		$("#minicart-delivery")
		.empty()
		.append(a_ord.v_cntry_code + ' ' + a_ord.v_ord_dlv_m_title + ' Delivery ' + a_ord.v_ord_dlv_total_inctax);

	}
	$("#minicart-total")
	.empty()
	.append(
		$("<span/>")
			.addClass("amounts")
			.append("Total " + v_ord_total_inctax + ((v_cntry_tr == '0%') ? '' : ' (inc VAT)'))
	);
	
}

$(function() {
	$(".lightbox").lightBox();	
});

// Display Order Products
function f_ord_prd(a_ord_prd) {
	$("#minicart-contents").hide().empty();
	if (typeof a_ord_prd != 'undefined' && a_ord_prd != false) {
		$.each(a_ord_prd,function(){
			var delayed;
			var v_ord_prd_id = this.v_ord_prd_id;
			$("#minicart-contents").append(
				$("<div/>")
					.addClass("product")
					.append(
						$("<a/>").addClass("img").attr("href",v_url_root + "store/" + this.v_prd_url).append(
							$("<img/>").attr("src",v_url_root + "store/media/img/prd/" + ((this.v_prd_img_id != null) ? this.v_prd_id + "/" + this.v_prd_img_id : 'default') + "/S.jpg")
						)
					)
					.append(
						$("<div/>").addClass("txt")
						.append(
							$("<p/>")
								.append(
									$("<input/>")
										.addClass("qty")
										.attr("value",this.v_ord_prd_qty)
										.attr("size","1")
										.keyup(function(){
											var v_ord_prd_qty = $(this).val();
											clearTimeout(delayed);
											if (v_ord_prd_qty != '') {
												delayed = setTimeout(function(){
													//f_ord();
													$("#minicart-contents").slideUp("fast");
													$.post(v_url_root + "store/cart/index.codebehind.php",{
														'v_action':'Product Qty',
														'v_ord_prd_id':v_ord_prd_id,
														'v_ord_prd_qty':v_ord_prd_qty
													},function(data){
														if (typeof data.Message != 'undefined') {
															alert(data.Message);
														}
														if (typeof data.Error == 'undefined') {
															// Display Order Products
															f_ord_prd(data.t_ord_prd);
															// Display Order Total
															f_ord(data.t_ord[0]);
														} else {
															$('#v_f_cart_view').click();
														}
													},"json");
												},750);
											}
										})
								)
								.append(
									$("<a/>")
										.append("Remove")
										.addClass("remove")
										.click(function(){
											$.post(v_url_root + "store/cart/index.codebehind.php",{
												'v_action':'Remove Product',
												'v_ord_prd_id':v_ord_prd_id
											},function(data){
												if (typeof data.Message != 'undefined') {
													alert(data.Message);
												}
												if (typeof data.Error == 'undefined') {
													// Display Order Products
													f_ord_prd(data.t_ord_prd);
													// Display Order Total
													f_ord(data.t_ord[0]);
												}
											},"json");
										})
								)
						)
						.append(
							$("<h5/>").append(this.v_prd_title)
						)
						.append(
							((this.v_prd_opt_title != null) ? $("<p/>").append('â€¢ ' + this.v_prd_opt_title.replace(/\n/g,'<br />â€¢ ')) : '')
						)
						.append(
							((this.v_ord_prd_prs_txt != null) ? $("<p/>").append('â€¢ ' + this.v_ord_prd_prs_txt.replace(/\n/g,'<br />â€¢ ')) : '')
						)
						.append(
							$("<p/>").append(this.v_prd_p_inctax)
						)
						
					)
					.append(
						$("<div/>").addClass("clear")
					)
			)
		});
	} else {
		$("#minicart-contents").append($("<p/>").addClass("product").append("There are no items in your order."));
	}

	$("#minicart-contents").slideDown("fast");
	$("#minicart-total,#minicart-discount,#minicart-delivery,#cart-actions").show();
}
/**
 * Cookie plugin v1.0
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
