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 () {
	jQuery('.add-to-cart-disabled').tooltip({
	    delay: 0,
	    track: true,
	    showURL: false,
	    fixPNG: true,
	    top: -25,
	    left: -10,
	    bodyHandler: function() {
	        return __select_msg; 
	    }
	});
	
	jQuery('.add-to-wishlist').tooltip({
	    delay: 0,
	    track: true,
	    showURL: false,
	    fixPNG: true,
	    top: -25,
	    left: -10,
	    bodyHandler: function() {
	        return __select_msg; 
	    }
	});
}

$(document).ready(setTooltips);

var refreshSwatches = function() {
	$('.swatch').click(function(){
		//debugger;
        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');
      
 	this.colorid=__colorid;
 	this.image=__colorid;
 	//debugger;
 	
 	
 	
 	if(FlashDetect) {
 		// FLASH NOT INSTALLED - SHOW JPG OF PRODUCT
 		if(!FlashDetect.installed){
 			
 			// get product variation image
 			 var src = $('.swatch .selected a').attr("rel");
 		
 			 // 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, "", "475", "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');
					}
				}
			}
		
			var __fb=document.getElementById("fbhl");
			if (__fb) {
				__fb.href=__fb.href.substring(0,__fb.href.indexOf("Product-Show"));
				__fb.href=__fb.href + "Product-Show?pid="+__pid+"&v=true&color="+__colorid;
				}
			
			if(__productArray !== undefined) { 
				// Change Color Selected Name
				var __csname = $('#' + __pid + '_color_name', __parent);
				
				//throws JS error in IE
				//if(__csname.length > 0)
				//	__csname[0].innerHTML = __colorname;
				
				//s.golden - use this instead of innerHTML above to make IE happy
				if(__csname.length > 0)
				{
					$(__csname[0]).html(__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);
			}
			// END FLASH IS INSTALLED - SHOW SWF
		}
	}
	
    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;
				}
			}
		}
	}	
}

var setTechTabs= function () {
	//reorder technologies
	if($('#product-technologies')) {
		var techimages = $('img', $('#product-technologies'));
		var techdesc = $('.contentasset p:last-child', $('#product-technologies'));
		var techcollector = new Array();
		
		//hide container
		$('#product-technologies > div').css({'display':'none'});
		
		$('#product-technologies .tab-inner .contentasset').each(function (i, contentitem) {
			
		techcollector[i] = new Object();
				
			$('p', contentitem).each(function (j, pitem) {
				
				if($('img', pitem).length == 1) // "p" element containing the technology image
				{
					techcollector[i]['imgsrc']    = pitem.getElementsByTagName("img")[0].src;
					techcollector[i]['imgwidth']  = pitem.getElementsByTagName("img")[0].width;
					techcollector[i]['imgheight'] = pitem.getElementsByTagName("img")[0].height;
				}
				else if($('strong', pitem).length == 1) // "p" element containing the textual description
				{
					techcollector[i]['techdesc'] = $(pitem).html();
					//technology title
					techcollector[i]['techtitle'] = $('strong', pitem).html().replace(/ /g, "_");
					if(techcollector[i]['techtitle'].indexOf('Guts')>0){
						techcollector[i]['techtitle'] ='Bloodnguts';
					}
					//cut off end of headline after TM or (R)
					var tmpend = techcollector[i]['techtitle'].search(/[®™]{1}/);
					if(tmpend != "-1") {
						techcollector[i]['techtitle'] = techcollector[i]['techtitle'].substring(0, tmpend);
					}
					
					//special case: techlite needs a hyphen, Insect Blocker asset uses a hyphen
					if(techcollector[i]['techtitle'] == 'Techlite') {
						techcollector[i]['techtitle'] = 'Tech-Lite';
					}
					else if(techcollector[i]['techtitle'] == 'Blood_\'N_Guts') {
						techcollector[i]['techtitle'] = 'Bloodnguts';
					}
					else if(techcollector[i]['techtitle'] == 'Insect_Blocker' || techcollector[i]['techtitle'] == 'INSECT_BLOCKER') {
						techcollector[i]['techtitle'] = 'Insect-Blocker'; 
					}
				}
			});
		});
		
		//local description tree
		var tmpdesc;
		
		for(var i = 0; i < techcollector.length; i++)
		{
			//if no image is available -> do not show this technology
			if(typeof(techcollector[i]['imgsrc']) == "undefined")
			{
				continue;
			}
			
			//if technology has no description, set it to empty
			if(typeof(techcollector[i]['techdesc']) == "undefined")
			{
				techcollector[i]['techdesc'] = "";
			}
	
			 $('#pdtechbar').append('<div class="technologyiconbox" id="technologyiconbox'+i+'">' +
								   '<img src="' + techcollector[i]['imgsrc'] + 
								   // '" width="' + techcollector[i]['imgwidth'] + 
								   // '" height="' + techcollector[i]['imgheight'] + '" alt="" ' +
								   '" onclick="javascript:showTechDesc(\'techdesc' + i + '\');" style="display: block; cursor:pointer" />' +
								   '</div>');
			if(i == 0)
			{
				tmpdesc = '<div id="techdesc' + i + '">' + techcollector[i]['techdesc'] + 
						  '<div style="margin-top:2px;">' + 
						  '<a class="learn-more" href="' + $('#techmorelinkdesign a').attr('href') + '_' + techcollector[i]['techtitle'] + '" rel="video:/media/short.flv">Learn More »</a>' + 
						  '</div>' +
						  '</div>';
			}
			else
			{
				tmpdesc = '<div id="techdesc' + i + '" style="display:none">' + techcollector[i]['techdesc'] + 
						  '<div style="margin-top:2px;">' + 
						  '<a class="learn-more" href="' + $('#techmorelinkdesign a').attr('href') + '_' +  techcollector[i]['techtitle'] + '" rel="video:/media/short.flv">Learn More »</a>' + 
						  '</div>' +
						  '</div>';
			}
								   
			$('#product-technologies').append(tmpdesc);
		}
	
	 	$('#pdtechbar').append('<div style="clear:both"> </div>');
	 	
	 	
	}
}

function showTechDesc(techDescDiv)
{
	//test, whether this is already shown, then do nothing
	if($("#product-technologies > div[id='" + techDescDiv + "']").css("display") != 'block') {
		$('#product-technologies > div').hide(100);
		$('#' + techDescDiv).show(200);
	}
	
	return;
}

function getWindowLocation() 
{
	var url = window.location.toString();
	
	return url;
}



