// UTF8‼

$(document).ready(function(){

	if (/MSIE\s(5\.5|6\.)/.test(navigator.userAgent)) {
		DD_belatedPNG.fix('#announcement,#cart input');
	}


	// Categories Formatting
	$("#categories li li a").prepend("• ");
	$("#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."));
	});

	// Replace Font (Exclude IE5&6)
	if (/MSIE\s(5\.5|6\.)/.test(navigator.userAgent) == false) {
		Cufon
		.replace('#breadcrumb, #cart legend label, #content h1, #content h2, #product #images h3, #product #related h3, #content .nav a, #announcement',{
			fontFamily:'Myriad Pro'
		})
		.replace('#nav li a, #head a, #categories a',{
			fontFamily:'Myriad Pro',
			hover:true
		});
	}

	// Detect Current Location
	if ($.cookie('v_cur_code') === null) {		
		if (typeof google != 'undefined' && google.loader.ClientLocation) {
			if (google.loader.ClientLocation.address.country_code == 'GB') {
				$.cookie('v_cur_code','GBP',{path:'/',expires:10});
			} else {
				$.cookie('v_cur_code','USD',{path:'/',expires:10});
			}
		}
	}

	// 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;});

	// Currency Selection
	$('<div/>')
		.attr('id','currency')
		.html('<span/>')
		.append(
			$('<ul/>')
			.css("cursor","pointer")
			.append(
				$('<li/>')
					.attr('id','currency-selection')
					.addClass((($.cookie('v_cur_code') == 'USD') ? 'us' : 'gb'))
					.html('Currency <em> - change</em>')
			)
			.append(
				$('<li/>')
					.addClass((($.cookie('v_cur_code') == 'GBP') ? 'selected' : ''))
					.addClass('gb')
					.click(function(){
						$.cookie('v_cur_code','GBP',{path:'/',expires:10});
						location.href = location.href;
						$("#currency-selection").addClass('gb');
					})
					.html('Great Britain')
			)
			.append(
				$('<li/>')
					.addClass((($.cookie('v_cur_code') == 'USD') ? 'selected' : ''))
					.addClass('us')
					.click(function(){
						$.cookie('v_cur_code','USD',{path:'/',expires:10});
						location.href = location.href;
						$("#currency-selection").addClass('us');
					})
					.html('United States')
			)
			.hover(function(){
				$(this).css({overflow: "visible"});
			},function(){
				$(this).css({overflow: "hidden"});
			})
		)
		.insertAfter("#nav");

});

var delay_ord_disc_code;

// Display Order Totals
function f_ord(a_ord) {
	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").insertBefore('#minicart-total');
		}
		$("#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 Items")
			.click(function(){
				if ($(this).text() == "View Items") {
					$("#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 {
					$("#minicart-contents").slideUp("fast");
					$("#minicart-discount,#minicart-delivery").hide();
					$(this).text("View Items");
				}
			})
	)
	.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.Redirect != 'undefined') {
														location.href = data.Redirect;
													}
													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 Items");
													}
												},"json");
											},750);
										})
								)
								.append(
									$("<a/>")
										.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.Redirect != 'undefined') {
													location.href = data.Redirect;
												}
												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 Items");
												}
											},"json");
										})
								)
						)
						.append(
							$("<h3/>").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")
					)
			)
		});
		$("#minicart-total .control").text("Hide Items");
	} else {
		$("#minicart-contents").append($("<p/>").addClass("product").append("There are no items in your order."));
	}
	$("#minicart-contents").slideDown("fast",function(){});
	$("#minicart-discount,#minicart-delivery").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;
    }
};