// UTF8‼
$(document).ready(function(){

	if (/MSIE\s(5\.5|6\.)/.test(navigator.userAgent)) {
		DD_belatedPNG.fix('#feat-categories div,.form_nav,img,#v_prd_add,#v_f_query_submit,#v_f_cart_checkout,#v_f_cart_update,#v_f_cart_save,a.remove,#submit');
	}

	// Replace Font (Exclude IE5&6)
	//if (/MSIE\s(5\.5|6\.)/.test(navigator.userAgent) == false) {
		Cufon
		.replace('h1, h2, .price, #announcement .pad p',{
			fontFamily:'Minion Pro'
		});
	//}

	// Homepage

		// Make Entire Block Clickable

		$("#feat-categories li,#category #products .product")
			.css("cursor","pointer")
			.hover(
				function(){
					$(this).addClass("hover")
				}, 
				function(){
					$(this).removeClass("hover")
				}
			)
			.click(function(){
				window.location=$(this).find("a").attr("href"); return false;
			});

		$("#brand-logos a")
			.hover(function(){
				$('#brand-logos a').not($(this)).stop().fadeTo(250,0.35);
			},function(){
				$('#brand-logos a').not($(this)).stop().fadeTo(250,1);
			});

	// Categories Formatting
	$("#categories li:first").addClass("start");
	$("#categories li:last").addClass("end");

	// Abbreviate Category Name to Fit
	$("#categories li li a:contains('Traditional')").each(function(){
		$(this).text($(this).text().replace("Traditional","Trad."));
	});

	// Load Order Totals
	$.post(v_url_root + "store/cart/index.codebehind.php",{
		'v_action':'Load Totals'
	},function(data){
		f_ord(data.t_ord[0]);
	},"json");
	
	// Nullify Cart Update Button
	$("#v_f_cart_update").click(function(){return false;});

});

var delay_ord_disc_code;

// Display Order Totals
function f_ord(a_ord) {
	$("#minicart-contents").hide(); // Added - PR
	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)
			.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").hide().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(
		$("<a/>")
			.addClass("control")
			.append("View Cart")
			.click(function(){
				if ($(this).text() == "View Cart") {
					$("#cart").addClass("open");
					$("#cart-contents").empty().append($("<p/>").addClass("product").append("Loading…"));
					$(this).text("");
					// 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 {
					$("#cart").removeClass("open");
					$("#minicart-contents").slideUp("fast");
					$("#minicart-discount,#minicart-delivery").hide();
					$(this).text("View Cart");
					//$("#cart form").fadeOut("3000");
				}
			})
	)
	.append(
		$("<span/>")
			.addClass("amounts")
			.append("Total " + v_ord_total_inctax + ((v_cntry_tr == '0%') ? '' : ' (inc VAT)'))
	);
}

// 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_id + "/" + this.v_prd_img_id + "/S.jpg")
						)
					)
					.append(
						$("<div/>").addClass("txt")
						.append(
							$("<p/>")
								.append(
									$("<input/>")
										.addClass("qty")
										.attr("value",this.v_ord_prd_qty)
										.keyup(function(){
											var v_ord_prd_qty = $(this).val();
											clearTimeout(delayed);
											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]);
														$("#minicart-total .control").text("Hide Cart");
													}
												},"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]);
													$("#minicart-total .control").text("Hide Cart");
												}
											},"json");
										})
								)
						)
						.append(
							$("<h5/>").append(this.v_prd_title)
						)
						.append(
							((this.v_prd_opt_title != null) ? $("<p/>").append('• ' + this.v_prd_opt_title.replace('\n','<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-total .control").text("Hide Cart");
	$("#minicart-contents").slideDown("fast",function(){});
	$("#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;
    }
};