// This function assumes that content for each tab corresponds to a direct child
// node of the specified content container
//
// And that each tab corresponds to a direct child node of the specified
// tab container
//
// Target tab ID is passed in, as opposed to the target tab itself in other implementations,
// to facilitate a generated Bazaar Voice script
function OnTabClicked(tabContentContainerID, targetTabContentID, targetTabID, otherTabIDsArray)
{
	var tabContentContainer = document.getElementById(tabContentContainerID);
	
	if(tabContentContainer)
	{
		var targetTabContent = document.getElementById(targetTabContentID);
		
		for(var i = 0; i < tabContentContainer.childNodes.length; i++)
		{
			// This filters the childNodes to legitimate html controls
			if(tabContentContainer.childNodes[i].tagName && tabContentContainer.childNodes[i].tagName.length > 0)
			{
				if(targetTabContent && targetTabContent == tabContentContainer.childNodes[i])
				{
					tabContentContainer.childNodes[i].style.visibility = "visible";
					tabContentContainer.childNodes[i].style.display = "";
				}
				else
				{
					tabContentContainer.childNodes[i].style.visibility = "hidden";
					tabContentContainer.childNodes[i].style.display = "none";
				}
			}
		}
	}
	
	var targetTab = document.getElementById(targetTabID);
	
	if(targetTab && targetTab.className.indexOf("Selected") < 0)
	{
		targetTab.className = targetTab.className + "Selected";
	}
	
	for(var j = 0; j < otherTabIDsArray.length; j++)
	{
		var otherTab = document.getElementById(otherTabIDsArray[j]);
		
		if(otherTab)
		{
			otherTab.className = otherTab.className.replace("Selected", "");
		}
	}
}
var addToCartUpsell = false;
function UpsellClick(){
addToCartUpsell = true;
}
function Validate_CustomizationUpsell(source, args){
args.IsValid = true;
if(addToCartUpsell){
	var customizationValue = jQuery.trim(args.Value);
	args.IsValid = customizationValue != '';
}
}
function Validate_Customization(source, args){
var customizationValue = jQuery.trim(args.Value);
args.IsValid = customizationValue != '';
}

/**Customizations**/
function CustomizationTextBox(singleLineTextBox, customizationSetKey, delimiter, index){
	this.textBox = singleLineTextBox;
	this.customizationSetKey = customizationSetKey;
	this.delimiter = delimiter;
	this.index = index;
	this.update = function(value){
			this.textBox.val(value);
		};
}
function CustomizationDropDown(dropDown, customizationSetKey){
	this.dropDown = dropDown;
	this.customizationSetKey = customizationSetKey;
	this.textBoxes = new Array();
	this.updateValues = function(dropDownValue){
		for(var j = 0; j < this.textBoxes.length; j++)
		{
			this.textBoxes[j].update('');
			var values = dropDownValue.split(this.textBoxes[j].delimiter);
			if(this.textBoxes[j].index <= values.length)
			{
				this.textBoxes[j].update(values[this.textBoxes[j].index - 1]);
			}
		}
	};
	var $textBoxes = $("input[dropdown=" + customizationSetKey + "]");
	for(var i = 0; i < $textBoxes.length; i++)
	{
		var $textBox = $($textBoxes[i]);
		var delim = $textBox.attr("delimiter");
		var index = $textBox.attr("delimiterIndex");
		if(delim === '' || index == '')
		{
			continue;
		}
		this.textBoxes.push(new CustomizationTextBox($textBox, this.customizationSetKey, delim, index));
	}
}
function CustomizationHelper(){
	this.dropDowns = new Array();
	this.updateValues = function(customizationSetKey, value){
		for(var i = 0; i < this.dropDowns.length; i++)
		{
			if(this.dropDowns[i].customizationSetKey === customizationSetKey)
			{
				this.dropDowns[i].updateValues(value);
			}
		}
	};
}
var customizationHelper = new CustomizationHelper();
function PopulateHelper(){
	customizationHelper = new CustomizationHelper();
	var $dropdowns = $("select[dropdown]");
	for(var i = 0; i < $dropdowns.length; i++)
	{
		var $dropdown = $($dropdowns[i]);
		var customizationSetKey = $dropdown.attr("dropdown");
		if(customizationSetKey === '')
		{
			continue;
		}
		customizationHelper.dropDowns.push(new CustomizationDropDown($dropdown, customizationSetKey));
		$dropdown.change(function(){
			var $this = $(this);
			var customizationSetKey = $this.attr("dropdown");
			customizationHelper.updateValues(customizationSetKey, $this.val());
		});
	}
}

$(function(){
	PopulateHelper();
});


/**
 * Zoom plugin
 *
 * @version 0.1
 * @requires jQuery v1.3
 * @author Kevan Davis
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Modified by Sam Hewitt on 1/4/2010 to remove css height and width on mouseout, absolute positioning on img.
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Usage:
 *   $(".thumbnails").zoom({ container: $("#fullsizeimage") })
 *   With 1 or more thumbnail images selected, zoom will make it so when you are mousing over them, a fullsize version
 *   will pan around in a medium sized container.  Examples can be found on any product page at www.gilt.com
 *
 * Required parameters:
 *   container:  a jquery object for the full size image parent
 *
 * Optional parameters:
 *   triggerEvent:  the event that triggers the zoom effect, by default it's mouseover, but if you want, you can attach it to something else,
 *   easing:        easing function for the panning effect, default is "swing", "easeOutElastic" looks cool too
 *   panSpeed:      speed at which to pan around, default is "normal",
 *   zoomInSpeed:   speed at which to zoom in, default is "slow",
 *   zoomOutSpeed:  speed at which to zoom out, default is "fast",
 *   useZoomInEffect: whether or not to use the zoom in effect, default is true,
 *   useZoomOutEffect: whether or not to use the zoom out effect, default is true
 */
(function(A){A.fn.zoom=function(M){var C=A.extend({},A.fn.zoom.defaults,M);var B=A(this);var D;var F;var E;B.each(function(N,P){var O=A("<img/>").attr("src",A(P).attr("fullsrc")).hide();O.load(function(){A(P).data("zoomed",{src:A(P).attr("fullsrc"),height:O.height(),width:O.width()})}).appendTo("body")});if(C.useZoomInEffect){C.zoomInSpeed=A.speed(C.zoomInSpeed).duration;C.panSpeed=A.speed(C.panSpeed).duration}if(!C.container||C.container.data("iszoomconfigured")){return B}var G=C.container.find("img");if(!G.length){G=A("<img/>")}C.container.data("iszoomconfigured",true).empty().css({position:"relative"}).append("<div/>").children("div").css({overflow:"hidden",position:"relative",height:"100%",width:"100%"}).append(G).children("img").css({top:0,left:0});var I=(C.container.filter(":hidden").length>0);var K;var H;var L;var J=function(O){if(!O.pageX&&!O.pageY){return }var T=O.pageX;var S=O.pageY;var Q={top:((S-E.top)/D.height())*100,left:((T-E.left)/D.width())*100};var U={top:(F.height*Q.top/100)-C.container.height()/2,left:(F.width*Q.left/100)-C.container.width()/2};if(F.width-C.container.width()<U.left){U.left=F.width-C.container.width()}else{if(0>U.left){U.left=0}}if(F.height-C.container.height()<U.top){U.top=F.height-C.container.height()}else{if(0>U.top){U.top=0}}var N;var V={marginTop:-U.top,marginRight:F.width-U.left,marginBottom:F.height-U.top,marginLeft:-U.left};if(!L){L=true;if(C.useZoomInEffect){G.css({marginTop:0,marginRight:0,marginBottom:0,marginLeft:0})}else{G.stop(true,false).css(V);return }}if(C.useZoomInEffect){var P=(new Date()).getTime();H+=P-K;K=P;if(G.height()!=F.height||G.width()!=F.width){var R;if(H<C.zoomInSpeed){R=C.panSpeed/(C.zoomInSpeed-H);if(1<R){R=1}N=A.extend({},V,{height:F.height,width:F.width})}}}G.stop(true,false);if(N){G.animate(N,{duration:C.zoomInSpeed-H,easing:"linear"})}G.animate(V,{duration:C.panSpeed,easing:C.easing})};B.bind(C.triggerEvent,function(){D=A(this);E=D.offset();F=D.data("zoomed");if(!F){return }var N=G.data("unzoomed");if(N){A.extend(N,{src:G.attr("src")})}else{N={src:G.attr("src"),height:G.height(),width:G.width()}}G.data("unzoomed",N);G.attr("src",F.src).stop(true,true);if(!C.useZoomInEffect){G.height(F.height).width(F.width)}if(I){C.container.show()}K=(new Date()).getTime();H=0;L=false;A().mousemove(J).mousemove()});return B.mouseout(function(){A().unbind("mousemove",J);if(I){C.container.hide()}D=null;E=null;F=G.data("unzoomed");if(!F){return }G.attr("src",F.src).stop(true,false);if(C.useZoomOutEffect){G.animate({margin:0,height:F.height,width:F.width},{duration:C.zoomOutSpeed}).css('height','').css('width','')}else{G.css({margin:0,height:F.height,width:F.width}).css('height','').css('width','')}F=null})};A.fn.zoom.defaults={triggerEvent:"mouseover",easing:"swing",panSpeed:"normal",zoomInSpeed:"slow",zoomOutSpeed:"fast",useZoomInEffect:true,useZoomOutEffect:true}})(jQuery);


pDetail = {};

pDetail.Collections = {};

pDetail.Product = {};

pDetail.Product.Images = {
    seriesCache: {},

    configure: function(mainPhotoDivId) {
        pDetail.Product.Images.mainPhotoDiv = function() {
            return $(mainPhotoDivId);
        };
    },
	//Creates an image from a path so it can be stored in the cache.
    createImage: function(path, width, height) {
        var image = new Image();
        image.src = path;
        if (width) {
            image.width = width;
        }
        if (height) {
            image.height = height;
        }
        return image;
    },
	//Adds an image to the series cache, so it can be swapped back in later
    storeSeriesImage: function(seriesId, path, width, height) {
        var seriesHash = pDetail.Product.Images.seriesCache;
        if (!seriesHash) {
            seriesHash = {};
            pDetail.Product.Images.seriesCache = seriesHash;
        }
        var image = pDetail.Product.Images.createImage(path, width, height);
		seriesHash[seriesId] = { image: image };
    },
    // Primary method to swap out an image for an html element based on the series and color
    swap: function(el, seriesId, key) {
        var o = pDetail.Product.Images.getCachedImage(seriesId, key);
        if (o) {
            if (el.length) {
				if (o.width) {
					el.width(o.width);
				}
				if (o.height) {
					el.height(o.height);
				}
				el.find("img:first").attr("src", o.src);
				el.find("img:first").attr("fullsrc", o.src.replace(/\-P\./,"-F."));
				el.show();
			}
        }
    },
    // Gets image based on series from the cache. May return null.
    getCachedImage: function(seriesId, key) {
        var seriesHash = pDetail.Product.Images.seriesCache;
        if (seriesHash) {
            var images = seriesHash[seriesId];
            if (images) {
                return images[key];
            }
        }
        return null;
    }
};


pDetail.Product.Thumbnail = {
    showZoom: function(thumb, seriesId, zoom) {
        pDetail.Product.Images.swap(pDetail.Product.Images.mainPhotoDiv(), seriesId, 'med');
        if (zoom) {
			var $thumbnail = $(thumb);
			if($thumbnail.data("zoomed"))
			{
				$thumbnail.data("zoomed").src = $thumbnail.attr("fullsrc"); 
				$thumbnail.trigger("zoomstart");
			}
        }
    }
};

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
jQuery.extend( jQuery.easing,
{
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	}
});

pDetail.applyZoom = function(containerId) {
	//An img with class zoom defines an image that the zoom effect needs to be applied.
    var imgs = $("img.zoom");
    var i = imgs.length;
	//Add a fullsrc attribute to hold the src of the large image.
    while (i--) {
        imgs.eq(i).attr("fullsrc", imgs.eq(i).attr("src").replace(/\-A\./,"-F."));
    }
	imgs.zoom({
		container: $(containerId),
		triggerEvent: "zoomstart",
		useZoomInEffect: false,
		useZoomOutEffect: false,
		panSpeed: 500,
		easing: "easeOutCubic"
	});
};
