var $ = jQuery;

document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
	var __children = (parentElement || document.body).getElementsByTagName((tagName || '*'));
	var __child, __attributeValue;
	var __elements = new Array();
	for(var ___e=0;___e < __children.length-1;___e++) {
		__child = __children[___e];
		__attributeValue = __child.getAttribute(attribute);
		if(!value || __attributeValue == value)
			__elements.push(__child);
	}
	return __elements;
}

var setTooltips = function () {

	$('.add-to-cart-disabled').tooltip({
	    delay: 0,
	    track: true,
	    showURL: false,
	    fixPNG: true,
	    top: -25,
	    left: -10,
	    bodyHandler: function() {
	        return 'Please select a color and a size first.'; 
	    }
	});
	
	$('.add-to-wishlist').tooltip({
	    delay: 0,
	    track: true,
	    showURL: false,
	    fixPNG: true,
	    top: -25,
	    left: -10,
	    bodyHandler: function() {
	        return 'Please select a color and a size first.'; 
	    }
	});
}

$(document).ready(setTooltips);

var refreshSwatches = function() {
	$('.swatch').click(function(){

        if($('a', this.parentNode).hasClass('plus')) return;
        
        $('.innerswatch', $(this).parentNode).removeClass('selected');
        $('.innerswatch', $(this)).addClass('selected');
      
        var __imgid = this.attributes['imageid'].value;
        var __el = document.getElementById(__imgid);
        
        if(__el) __el.src = $('a', $(this)).attr('rel');
        
        return false;
    });
}

$('.swatch').click(function(){
	
	var __imgid = this.attributes['imageid'].value;
	var __swf = this.attributes['swf'];
	var __colorid = this.attributes['colorid'].value;
	var __pid = ParseID(this.attributes['pid'].value);
	
	var __colorname = this.attributes['colorname'].value;
	var __el = document.getElementById(__imgid);
	var __parent = document.getElementById(__pid + "_product_variations");	
	
	$('.innerswatch', $('.' + __pid + '_container')).removeClass('selected');
    $('.innerswatch', $('.' + __pid + '_' + __colorid)).addClass('selected');

    
    
    if(FlashDetect) {
 		// FLASH NOT INSTALLED - SHOW JPG OF PRODUCT
 		if(!FlashDetect.installed){
 			
 			
 			// get product variation image - this will always be the first variation/swatch/colorid (Sorel only)
 			var src = $('.selected img').attr("src");
 			 
 			// get the correct colorid
 			var colorid = $('.selected').parent().attr("colorid");
 			
 			// get the current image URL up to the last /
 			var url = src.substr(0,src.lastIndexOf('/') + 1);
 			
 			// get imageid - will be the first variation - needs to be replaced w/ colorid
 			var imageid = src.substr(src.lastIndexOf('/') + 1);
 			
 			// replace the bad colorid w/ the correct colorid, located at index 2 if we split the image string at the underscores
 			var imageStr = imageid.split("_");
 			imageStr[2] = colorid;
 			
 			// the sorel image ending in _f was is not correct - should be _r
 			// _r is the picture w/ the two boots
 			// located at index 3, and also contains the beginnings of the query
 			imageStr[3] = "r?$pgrid";
 			
 			imageid = "";
 			// var newImageID = imageStr[0];
 			// rebuild the imageid
 			for (i = 0; i < imageStr.length; i++)
 			{
 				
 				imageid += imageStr[i];
 				
				if (i != imageStr.length - 1) 
 				{
 					imageid += "_";
 				}
 			}
 			
 			url += imageid;
 			
 			src = url;
 			
 			// remove pgrid_sm from the url - add pgrid_large to get the large image
 			src = src.replace('$pgrid_sm$','$pgrid_large$')

 			 
 			 // replace product image src w/ large image
 			 $('#product-img img').attr('src', src);

 			
 			// show jpg, hide flash
 			$('#product-img').show();
 			$('#flashcontent').hide();
 			
			if(__productArray !== undefined) { 
				// Change Color Selected Name
				var __csname = $('#' + __pid + '_color_name', __parent);
				
				if(__csname.length > 0)
				{
					$(__csname[0]).html(__colorname);
				}

				ProcessVariantAttributeSelection(__pid, __colorid, "", 'color');		
				CheckEnableAddToCart(__pid);
			}
		}
 		
 		// FLASH IS INSTALLED - SHOW PRODUCT SWF
 		else {
 	
 			// hide non-flash jpg
 			$('#product-img').hide();
    
    
	    
	    
			if(!(__swf.value == "")) {
				// <![CDATA[
				var so = new SWFObject(__swf.value, "", "551", "502", "9", "#FFFFFF");
				so.addParam("wmode", "transparent");
				so.addParam("allowScriptAccess", "always");
				so.addParam("allowFullScreen", "true");
				so.addParam("flashVars", "allowScriptAccess=always");
				so.write("flashcontent");
				// ]]>
			} else {
				if(__el) {
					__el.src = $('a', $(this)).attr('rel');
				} else {
					var __el = $('#' + ParseID(__imgid) + '_primary', document.body);
		
					if(__el) {
						for(var ___sw=0; ___sw<__el.length;___sw++)
							__el[___sw].src = $('a', $(this)).attr('rel');
					}
				}
			}
		
			if(__productArray !== undefined) { 
				// Change Color Selected Name
				var __csname = $('#' + __pid + '_color_name', __parent);
			
				if(__csname.length > 0)
					__csname[0].innerHTML = __colorname;
				
				// 360 Spinner and Enlarge
				var __a360 = $('a.scene7enlarge-modal');
				var __aEnlarge = $('a.360spinner-modal');
				
				if(__a360.length > 0) {
					var __a360url = __a360.attr("url").split("=")[0] + '=' + __pid + "&colorid=" + __colorid;
					__a360.attr("url", __a360url);
				}
				if(__aEnlarge.length > 0) {
					var __aEnlargeUrl = __aEnlarge.attr("url").split("=")[0] + '=' + __pid + "&colorid=" + __colorid;
					__aEnlarge.attr("url", __aEnlargeUrl);
				}
		
				ProcessVariantAttributeSelection(__pid, __colorid, "", 'color');		
				CheckEnableAddToCart(__pid);
			}
	
 		}
    }
    return false;
});

$('.size').click(function(){

	if($('.innersize', $(this)).hasClass('disabled')) return;
	
    $('.innersize', $(this).parentNode).removeClass('selected');
    $('.innersize', $(this)).addClass('selected');
    
	var __pid = ParseID(this.attributes['pid'].value);
	var __sizeid = this.attributes['sizeid'].value;
	var __parent = document.getElementById(__pid + "_product_variations");
	var __colorSelected = $('.selected', $('.swatch', __parent));
	var __colorid;

	if(__colorSelected)
		__colorid = __colorSelected[0].parentNode.attributes['colorid'].value
	
	if(!(__colorid === undefined)) {
		ProcessVariantAttributeSelection(__pid, __colorid, __sizeid, 'size');
	}

	CheckEnableAddToCart(__pid);
	
    return false;
});

$('.dimension').click(function(){

	if($('.innerdimension', $(this)).hasClass('disabled')) return;

	var __pid = ParseID(this.attributes['pid'].value);
	
    $('.innerdimension', $(this).parentNode).removeClass('selected');
    $('.innerdimension', $(this)).addClass('selected');

    CheckEnableAddToCart(__pid);
    
    return false;
});

$('.add-to-cart').click(function() {

	var __pid = ParseID($(this).attr("id"));
	var __form = $('#' + __pid + '_product_detail_form', document.body);
	
	if($(this).hasClass('add-to-cart-disabled') == true) return;
	
	app.minicart.add(__form[0], jQuery(this).attr('rel'), undefined, function() {
        // redraw scollpane to prevent problems with firefox and safari
        // untested in ie
        $('#minicart-content ul').jScrollPane({showArrows:true, scrollbarWidth: 21, arrowSize: 19});
    });
	$('.checkout_link').show();
	
});

function ParseID(id)
{
	var __oldid = id.split("_");
	var __idlen = __oldid.length-1;
	var __newid = "";
	var __el;

	for(var ___i=0;___i<__oldid.length;___i++)
	{
		if(!(__idlen == ___i))
			__newid += __oldid[___i];
		
		if(___i < __idlen-1)
			__newid += "_";
	}
	
	return __newid;
}

function CheckEnableAddToCart(pid) {
	var __enable = true;
	var __parent = document.getElementById(pid + "_product_variations");
	
	var __colorid="";
	var __sizeid="0";
	var __dimensionid="0";
	
	var __color = $('.swatch_container', __parent).length;
	var __size = $('.size_container', __parent).length;
	var __dimension = $('.dimension_container', __parent).length;

	if(__color > 0) {
		var __color_selected = $('.selected', $('.swatch', __parent));
		if(__color_selected.length == 0)
			__enable = false;
		else
			__colorid = __color_selected[0].parentNode.attributes["colorid"].value;
	}
	
	if(__size > 0) {
		var __size_selected = $('.selected', $('.size', __parent));
		if(__size_selected.length == 0)
			__enable = false;
		else 
			__sizeid = __size_selected[0].parentNode.attributes["sizeid"].value;
	}
	
	if(__dimension > 0) {
		var __dimension_selected = $('.selected', $('.dimension', __parent));
		if(__dimension_selected.length == 0)
			__enable = false;
		else
			__dimensionid = __dimension_selected[0].parentNode.attributes["dimensionid"].value;
	}
	
	var __addToCartBtn = document.getElementById(pid + "_submit");
	var __wishListLink = document.getElementById("wishlistlink");
	
	if(__enable == true) {
		if(__addToCartBtn) {
		
			$(__addToCartBtn).removeClass('add-to-cart-disabled');
			$(__addToCartBtn).tooltip({});
			$(__wishListLink).tooltip({});
			
			// Find variant product id based on selected attributes
			var __found = false;
			var __product, __variant;
			for(var ___p=0;___p < __productArray.length; ___p++) {
				if(__productArray[___p][0] == pid) {
					__product = __productArray[___p];
					
					for(var ___v=0;___v < __product[1].length; ___v++) {
						__variant = __product[1][___v];

						if((__variant[0] == __colorid) && (__variant[1] == __sizeid) && (__variant[2] == __dimensionid)) {
							var __txtPID = $('#pid', $('#' + pid + '_product_detail_form'));
 							__txtPID[0].value = __variant[5];
							if(__wishListLink) {
								var __wishlisturl = __wishListLink.attributes["wurl"].value;
								
								__wishListLink.onclick = function() {
						            window.location = __wishlisturl + "?pid=" + __variant[5] + "&Quantity=" + $('#Quantity').val(); + "return false;";
						        };
								
								$('#wishlistlink').removeClass('disabled');
							}
							__found=true;
							break;
						}						
					}					
				}
				if(__found)
					break;
			}
		}
	} else {
		var __addToCartBtn = document.getElementById(pid + "_submit");
		if(__addToCartBtn) {
			if($(__addToCartBtn).hasClass('add-to-cart-disabled') == false) {
				$(__addToCartBtn).addClass('add-to-cart-disabled');
				$(document).ready(setTooltips);
			}
		}
		if(__wishListLink) {
			__wishListLink.removeAttribute("href");
			__wishListLink.setAttribute("onclick", "return false;");
			$('#wishlistlink').addClass('disabled');
		}
	}
}

function ProcessVariantAttributeSelection(pid, colorid, sizeid, type) {
	
	var __product, __variant;

	for(var ___p=0;___p < __productArray.length; ___p++) {
		if(__productArray[___p][0] == pid) {
			__product = __productArray[___p];
		
			for(var ___v=0;___v < __product[1].length; ___v++) {
				__variant = __product[1][___v];
				
				switch(type) {
					case "color":
						if(__variant[0] == colorid) {
							var __parent = document.getElementById(pid + "_product_variations");
							var __sizes, __dimensions;
							if(__parent) {
								__sizes = document.getElementsByAttribute("pid", pid + "_size", "div", __parent);
								__dimensions = document.getElementsByAttribute("pid", pid + "_dimension", "div", __parent);

								// SIZES
								var __size, __found, __svariant;
								for(var ___s=0;___s < __sizes.length;___s++) {
									__size = __sizes[___s];
									__found = false;
									for(var ___vs=0;___vs < __product[1].length; ___vs++) {
										__svariant = __product[1][___vs];
										if(__svariant[0] == colorid) {
											if(__svariant[1] == __size.attributes["sizeid"].value) {
											   if(__svariant[3] == true && __svariant[4] == true) {
											   	  __found = true;
											   	  break;
											   }
											}
										}
									}
									var __sz = $('.innersize', __size);
									if(__found) {
										if(__sz) {
											__sz.removeClass('disabled');
											__sz.removeClass('selected');
										}										
									} else {
										if(__sz) {
											__sz.addClass('disabled');
											__sz.removeClass('selected');
										}
									}									
								}
								
								// When a color is chosen, dimensions, if exist are all reset to default, 
								// because size denotes dimensions available
								var __dm;
								for(var ___d=0;___d < __dimensions.length;___d++) {
									__dimension = __dimensions[___d];
									__dm = $('.innerdimension', __dimension);
									if(__dm) {
										__dm.removeClass('disabled');
										__dm.removeClass('selected');
									}
								}
							}
						}
						break;
					case "size":
						if(__variant[0] == colorid && __variant[1] == sizeid) {
							var __parent = document.getElementById(pid + "_product_variations");
							var __dimensions;
							if(__parent) {
								__dimensions = document.getElementsByAttribute("pid", pid + "_dimension", "div", __parent);

								// DIMENSIONS
								var __dimension, __found, __dvariant;
								for(var ___d=0;___d < __dimensions.length;___d++) {
									__dimension = __dimensions[___d];
									__found = false;
									for(var ___vd=0;___vd < __product[1].length; ___vd++) {
										__dvariant = __product[1][___vd];
										if(__dvariant[0] == colorid && __dvariant[1] == sizeid) {
											if(__dvariant[2] == __dimension.attributes["dimensionid"].value) {
											   if(__dvariant[3] == true && __dvariant[4] == true) {
											   	  __found = true;
											   	  break;
											   }
											}
										}
									}
									if(__found) {
										$('.innerdimension', __dimension).removeClass('disabled');
									} else {
										var __o = $('.innerdimension', __dimension);
										if(__o) {
											__o.addClass('disabled');
											__o.removeClass('selected');
										}
									}									
								}
							}
						}
						break;
				}
			}
		}
	}	
}
