jQuery(document).ready(function(){
	
	initProductPaging();
	initHomepage();
	initHomepageBorder()
	
	if(jQuery(".brandlist .active").length > 0){
		jQuery(".brandlist").show();
	}
	
	if(jQuery(".tpl_14").length > 0){
		jQuery(".brandlist").show();
	}
	
	jQuery("a.brands").click(function(){
		jQuery(".brandlist").slideToggle('slow');
	});
	
	
	if(jQuery("#mygallery").length > 0){
		//initCarousel();
	}
	
	initErrorPopups();
	initCheckout();
	//initCouponcode();
	initAntiOpenImage();

});

function initAntiOpenImage() {
	$('.productThumbs.onshow a').click(function(e){
		e.preventDefault();
	});
}

function initProductPaging(){
	$(".num").each(function(){
		$("li:eq(0)", this).addClass('first');
		if($("li a:eq(0)", this).text() == "1"){
			$("li a:eq(0)", this).css('padding-right', '5px');
			$("li a:eq(0)", this).css('background', 'none').css('font-weight', 'bold');
		}
	});
}

function initHomepageBorder(){
}

function initHomepage(){
	$("#homepage_wrapper a").each(function(){
		$(this).prepend("<div class='darkblocker'></div>");
	});
	$(".darkblocker").css('opacity', 0);
	$("#homepage_wrapper a.categories").each(function(i){
	
		$(this).hover(function(){
			$("#homepage_wrapper a span:eq(" + i + ")").css('display', 'block');
			$("#homepage_wrapper a span:not(:eq(" + i + "))").css('display', 'none');
		}, function(){
			
		});
	
	});
	
	$("#homepage_wrapper a.callouts").each(function(i){
	
		$(this).hover(function(){
			$("#homepage_wrapper a.categories span").css('display', 'block');
		}, function(){
			
		});
	
	});
	
	$("#homepage_wrapper").hover(function(){
	
	}, function(){
		$("#homepage_wrapper a span").css('display', 'block');
	});
}

function initCarouselPane(){



}

function initPageFlip(){
	jQuery("#pageflip").hover(function() { //On hover...
	jQuery("#pageflip img , .msg_block").stop()
		.animate({ //Animate and expand the image and the msg_block (Width + height)
			width: '307px',
			height: '319px'
		}, 500);
	} , function() {
	jQuery("#pageflip img").stop() //On hover out, go back to original size 50x52
		.animate({
			width: '79px',
			height: '79px'
		}, 220);
	jQuery(".msg_block").stop() //On hover out, go back to original size 50x50
		.animate({
			width: '77px',
			height: '77px'
		}, 200); //Note this one retracts a bit faster (to prevent glitching in IE)
	});
}

function initCouponcode(){

	jQuery("#couponcode").hide();

	jQuery("#haveCode").click(function(e){
		e.preventDefault();
		jQuery(this).replaceWith('<p>Enter your code:</p>');
		jQuery("#couponcode").show();
	});
	
	jQuery("#removeCode").click(function(e){
		e.preventDefault();
		jQuery("#removeCoupon").val("removeCoupon");
		jQuery("#couponcode").trigger("submit");
	});

}

var currency = 'hkd';

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function initCheckout(){
	
	currency = jQuery.cookie('currency');
	if(currency == 'null'){
		currency = 'hkd';
	}
	
	jQuery("body").addClass("hkdActive");
	
	jQuery(".priceToConvert").each(function(){
		var hkd = jQuery(this).text();
		var hkdToFload = parseFloat(hkd.replace(",", ""))
		var usd = roundNumber((hkdToFload) * 0.129032258064516, 1);
		jQuery(this).html("<span class='hkdVal'>" + hkd + "</span>");
		jQuery(this).append("<span class='usdVal'>" + usd + " </span>");
		
	});
	
	jQuery("#payment_cup,#payment_alipay").submit(function(){
		jQuery("a#usd").trigger('click');
	});
	
	
	
	
	
	jQuery(".currency_switch a").click(function(e){
		e.preventDefault();

		currency = jQuery(this).attr("id");
		jQuery.cookie('currency', currency, {path: "/", domain: 'www.gizzynacho.com'});//path: '/'
		jQuery("body").removeClass('usdActive');
		jQuery("body").removeClass('hkdActive');
		jQuery("body").addClass(currency + 'Active');
		jQuery(".currencyLabel").text(jQuery(this).text());
		
		jQuery(".merchantId").each(function(){
			var newCode = jQuery(this).parents("form").find(".merCode" + currency).text();
			jQuery(this).val(newCode);
		});
		
		jQuery(".currCode").each(function(){
		
			var newCode = jQuery(this).parents("form").find(".currCode" + currency).text();
			jQuery(this).val(newCode);
		
		});
		
		if(currency == "hkd"){
			var total = jQuery("#checkoutTotal .hkdVal").text();
			total = parseInt(total);
			jQuery(".checkoutAmount").val(total);
		} else {
			total = parseInt(total);
			var total = jQuery("#checkoutTotal .usdVal").text();
			jQuery(".checkoutAmount").val(total);
		}
		
	});

	jQuery(".currency_switch a#" + currency).trigger("click");

	jQuery("img.color").hide();
	
	jQuery("div#payments_accepted > a").click(function(e){
		e.preventDefault();
		var id = jQuery(this).attr('id');
		if(id == "cup" || id == "alipay"){
			jQuery("a#usd").trigger('click');
		}
		
		var selector = "#payment_" + jQuery(this).attr('id');
		jQuery("#payment_methods form").hide();
			jQuery(selector).show('fast');
			jQuery("div#payments_accepted > a").removeClass('active');
			jQuery(this).addClass('active');
			jQuery(this).children("img.color").show();
			jQuery(this).children("img.black").hide();
			jQuery(this).siblings().children("img.color").hide();
			jQuery(this).siblings().children("img.black").show();
	});
	
	jQuery("#payment_methods form").each(function(){
		jQuery(this).submit(function(e){
			if(currency == "hkd"){
				var total = jQuery("#checkoutTotal .hkdVal").text();
				total = parseInt(total);
				jQuery(".checkoutAmount").val(total);
			} else {
				total = parseInt(total);
				var total = jQuery("#checkoutTotal .usdVal").text();
				jQuery(".checkoutAmount").val();
			}
			
		});
	});
	
}

function productQty(selector, quantity){
	jQuery(".quantity", selector).val(quantity);
	jQuery("form", selector).trigger('submit');
}

function initErrorPopups(){
	jQuery("span.error_holder").each(function(){
		var count = 0;
		jQuery(".error", this).each(function(i){
			if(i > 0){
				jQuery(this).remove();//just show one at a time.
			}
			count++;
		});
		
		if(count > 0){
			jQuery(this).show();
		}
	});
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}


function initProduct(){
	
	if(colorLinked != "" && typeof(color_options) != 'undefined'){
		var counter = 0;
		for(var color_code in color_options[colorLinked]){
			//
			if(counter == 0){
				$("#size option[value=" + color_code + "]").attr('selected', 'selected');
				selectedColor = colorLinked;
				setColors();
			}
			counter++;
		}
	}
	
	jQuery(".productThumbs").hide();
	
	var left = "<a title='Click to scroll through photos' class='thumbs_left' href='#'>WORLD</a><div class='thumb_band_holder'><div class='thumb_band'>";
	var right = "</div></div><a class='thumbs_right' href='#' title='Click to scroll through photos'>&gt;</a>";
	
	jQuery("#product_shot_large .productThumbs").each(function(i){
		var id = "thumbs_" + jQuery(this).attr("id");
		var thumbs = "";
		jQuery("img", this).each(function(){
			thumbs += "<a href='" + jQuery(this).attr("src") + "' target='_blank'><img style='width: 80px; height: 80px' src='" + jQuery(this).attr("longdesc") + "' alt='' /></a>";
		});
		
		jQuery("#product_shot_thumbs").append("<div class='thumbstrip' id='" + id + "'>" + left + thumbs + right +"</div>");
		scrollIndexes[i] = 2;
		thumbPanes[i] = jQuery("#" + id);
	});
	
	
	
	initProductThumbSlide();
	
	jQuery(".productThumbs:eq(0)").show();
	
	jQuery("#size").change(function(e){
		setColors();
	});
	
	jQuery("#colors_in_size").live('change', function(e){
		var color_code = jQuery(this).val();
		jQuery(".productThumbs, .thumbstrip").hide().removeClass('onshow');
		jQuery("#color_" + color_code).show().addClass('onshow');
		
		if(jQuery("#color_" + color_code).length == 0){
			jQuery("#color_noimage").show().addClass('onshow');
		}
		
		jQuery('#color_' + color_code + ' a:eq(0) img').css('display','inline');
		jQuery("#thumbs_color_" + color_code).show();
		selectedColor = color_code;
	});
	
	jQuery(".productThumbs").each(function(){
		var images = jQuery("img", this);
		jQuery(images).each(function(i){
			if(i == 0){
			
			} else {
				jQuery(this).hide();
			}
		});
	});
	
	setColors();
	
	jQuery("#add_to_cart").click(function(e){
		e.preventDefault();
		jQuery("#cart_form").submit();
	});
}

var scrollIndexes = Array();
var thumbPanes = Array();

function initProductThumbSlide(){
	var width = 92;
	
	jQuery('.thumb_band').each(function(){
		var imageWidth = jQuery("img", this).length * width;
		jQuery(this).width(imageWidth);
	});
	
	jQuery('.thumb_band').each(function(){
		jQuery("a", this).each(function(i){
			jQuery(this).click(function(e){
				e.preventDefault();
				jQuery(".productThumbs img").hide();
				jQuery(".onshow img:eq(" + i + ")").show();
			});
		
		});
		
	});
	
	jQuery(".thumbs_left").each(function(i){
	
		jQuery(this).click(function(e){
			e.preventDefault();
			var scrollIndex = scrollIndexes[i];
			var parent = thumbPanes[i];
			var images = jQuery("img", parent);
			//console.log(scrollIndex);
			if(scrollIndex > 2){
				jQuery(".thumb_band", parent).animate({
					left: '+=' + width
				}, 500, 'swing', function(){
					scrollIndexes[i]--;
				});
			} else {
				//rubber banding
				jQuery(".thumb_band", parent).animate({
					left: '+=20'
				}, 150).animate({
					left: '-=20'
				}, 150);
			}
		});
	});
	
	jQuery(".thumbs_right").each(function(i){
	
		jQuery(this).click(function(e){
			e.preventDefault();
			var scrollIndex = scrollIndexes[i];
			var parent = thumbPanes[i];
			var images = jQuery("img", parent);
			if(images.length > 3 && images.length > (scrollIndex+1)){
				jQuery(".thumb_band", parent).animate({
					left: '-=' + width
				}, 500, 'swing', function(){
					scrollIndexes[i]++;
				});
				
			} else {
				//rubber banding
				jQuery(".thumb_band", parent).animate({
					left: '-=20'
				}, 150).animate({
					left: '+=20'
				}, 150);
			}
		});
	});
}

var selectedColor = '';

function setColors(){
	var chosen_size = jQuery("#size").val();
	jQuery("#colors_in_size option").remove();
	
	if(typeof(size_options) != 'undefined'){
	
		for(var color_code in size_options[chosen_size]){
			var toDisplay = jQuery('#color').find('option.'+ color_code).text();
			var option = "<option value='" + color_code + "'>" + toDisplay + "</option>";
			jQuery("#colors_in_size").prepend(option);
		}
	
	}
	
	
	if(selectedColor != ""){
		jQuery("#colors_in_size option[value=" + selectedColor + "]").attr("selected", "selected");
		if(jQuery("#colors_in_size option[value=" + selectedColor + "]").length == 0){
			alert("Sorry, we don't have this product in that size/color combination");
			jQuery("#colors_in_size").trigger("change");
		} else {
			jQuery("#colors_in_size").trigger("change");
		}
	} else {
		jQuery("#colors_in_size").trigger("change");
	}

	
	
}

function ShowHide(id, visibility) {
    obj = document.getElementsByTagName("div");
    obj[id].style.visibility = visibility;
}

function initCarousel(){

	/*
stepcarousel.setup({
		galleryid: 'mygallery', //id of carousel DIV
		beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
		panelclass: 'panel', //class of panel DIVs each holding content
		autostep: {enable:false, moveby:1, pause:3000},
		panelbehavior: {speed:500, wraparound: true, persist:true},
		defaultbuttons: {enable: true, moveby: 1, leftnav: [site_url + 'web_assets/images/left-arrow.png', 10, 174], rightnav: [site_url + 'web_assets/images/	right-arrow.png', -120, 174]},
		statusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
		contenttype: ['inline'] //content setting ['inline'] or ['ajax', 'path_to_external_file']
	})
*/

}

/**
 * Cookie plugin
 *
 * 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;
    }
};

/**
*
*	simpleTooltip jQuery plugin, by Marius ILIE
*	visit http://dev.mariusilie.net for details
*
**/
(function($){ $.fn.simpletooltip = function(){
	return this.each(function() {
		var text = $(this).attr("title");
		$(this).attr("title", "");
		if(text != undefined) {
			$(this).hover(function(e){
				var tipX = e.pageX + 12;
				var tipY = e.pageY + 12;
				$(this).attr("title", ""); 
				$("body").append("<div id='simpleTooltip' style='position: absolute; z-index: 100; display: none;'>" + text + "</div>");
				if($.browser.msie) var tipWidth = $("#simpleTooltip").outerWidth(true)
				else var tipWidth = $("#simpleTooltip").width()
				$("#simpleTooltip").width(tipWidth);
				$("#simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
			}, function(){
				$("#simpleTooltip").remove();
				$(this).attr("title", text);
			});
			$(this).mousemove(function(e){
				var tipX = e.pageX + 12;
				var tipY = e.pageY + 12;
				var tipWidth = $("#simpleTooltip").outerWidth(true);
				var tipHeight = $("#simpleTooltip").outerHeight(true);
				if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
				if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
				$("#simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
			});
		}
	});
}})(jQuery);
