/**
* wires up the color and size selections, and tabifies the content.
* This file was modified for the demandware implementation. If you merge
* it please keep the function setupProductDesign and updateVariationProduct.
* function used in rf.js
*/
var setupProductDesign = function () {
   
    var $ = jQuery,
        ie = $.browser.msie,
        ie6 = ie && parseInt($.browser.version) == 6;
    ///
    
    jQuery('.add-to-cart-disabled').tooltip({
        delay: 0,
        track: true,
        showURL: false,
        fixPNG: true,
        top: -25,
        left: -10,
        bodyHandler: function() {
            return __select_msg; 
        }
    });
    
    // turn <select id="fit"> into a slider.
    var fit = document.getElementById('fit');
    if(fit){
        $(fit)
            .selectToUISlider({labels:0})
            .css({'display':'none'})
            .before('<img class="ui-slider-labels" src="/images/slider/labels.gif"/>');
        //
    }
    
    // product size tabs on the product detail page and quick shop layer/dialog
    $('#tabs').tabs();
    $('#tabs').bind('tabsselect', fixTabsSelects);
    function fixTabsSelects(event, ui){
        function callMeLater(){
            fixTabsSelects(event, ui);
        }
        function recallCondition(){
            return $('.rfselect', ui.panel).size() > 0 && $('.rfselect-skin',ui.panel).size() == 0;
        }
        if(recallCondition() && !ie6){
            rf.styleSelects($('select',ui.panel));
            if(recallCondition()){
                setTimeout(callMeLater, 50);
            }
        }
    };
    
    //initial check provides disabling invalid sizes/colors
    if(typeof(checkedAttributes) != 'undefined')
    {
    	jQuery('.product-detail-form').each(function(){
			updateVariationProduct(checkedAttributes[$(this).attr("rel")], jQuery("input", this), $(this));
    	});
    } 

    // Hack here
    $('#product-technologies').tabs();

    // tab the stuff on the ensemble page 
    //$('.ensemble-tabs').tabs();
    
    //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, "_");
					
					//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
					if(techcollector[i]['techtitle'] == 'Techlite') {
						techcollector[i]['techtitle'] = 'Tech-Lite';
					}
					else if(techcollector[i]['techtitle'] == 'Blood_\'N_Guts') {
						techcollector[i]['techtitle'] = 'Bloodnguts';
					}
				}
			});
		});
    	
    	//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">' +
								   '<img src="' + techcollector[i]['imgsrc'] + 
								   '" width="' + techcollector[i]['imgwidth'] + 
								   '" height="' + techcollector[i]['imgheight'] + '" alt="" ' +
								   'onclick="javascript:showTechDesc(\'techdesc' + i + '\');" style="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>');
     	
     	
    }
    

    var colorLabelSelectedIndex = 0;
    
    // select the color labels in the color and size selection
    var colorLabels = $('.select-color label');
    // when you select a color
    colorLabels.click(function(){
        
        $this = $(this);
        
        var __imgid = "";
        var __img;
        __el = $(this);
        if(__el) {
        	__imgid = __el.attr('imageid');
        
            if(__imgid)
            	if(!(__imgid == "")) {
            		__img = document.getElementById(__imgid);
            		if(__img)
            			__img.src = __el.attr('rel');
            	}            	
        }
        
        // do not do anything on disabled labels
        // labels which are out of stock are disabled
        if(!$this.hasClass('disabled')){        
            
            var relax = false;
            if($this.parent().parent().parent().hasClass('product-filter-group')) {
                
                if ($this.hasClass('selected')) {
                  $this.removeClass('selected');
                  relax = true;
                }
                else {
                   
                   $this.addClass('selected');
                }
            }
            else {
                // only remove the selected labels from this form
            	//debugger;
                jQuery('.select-color label', this.form).removeClass('selected');              
                
                // add selected label to this button
                $this.addClass('selected');
                //alert($this.parent().parent().parent().attr('class'));
                // show the name of the current selection in the elemnt of the parentNode DOM node with the class selection               
            }
            
            $('.selection',this.parentNode).html( $('abbr',this).attr('title') || $('img',this).attr('alt') || $this.html() );
            
            if($this.parent().parent().parent().hasClass('product-filter-group')){
                //this label is in the filter section.
                //var url = '?size='+($('abbr',this).attr('title') || $('img',this).attr('alt') || $this.html());
                var url = $this.parent().attr('href');

                // save selected color:
                var color = ($this.attr("id").split("-"))[1];
                addRefinementColor(color,relax);
                
                url = getRefineUrl();
                
                rf.filterResults(url);
            } else if($this.parents().eq(4).hasClass('quick-shop-dialog')){
                var item = rf.getLastClickedGridItem();
                $('img',item).eq(0).attr('src', $this.attr('rel'));
            } else {
                // save selected variationColor in checkedAttributes map
                checkedAttributes[jQuery(this.form).attr('rel')]["variationColor"] = $("#"+$this.attr("for")).val();
                updateVariationProduct(checkedAttributes[jQuery(this.form).attr("rel")], jQuery("input", jQuery(this.form)), jQuery(this.form), false);
                // if the SWFObject function is defined
                // normally this is only the case on the product details page

                if(typeof(SWFObject) != "undefined" && document.getElementById("flashcontent") !== undefined && document.getElementById("flashcontent") !== null) {
                  	var so = new SWFObject($this.attr('rel'), $this.attr('title'), "475", "502", "9", "#FFFFFF");
                    so.addParam("wmode", "transparent");
                    so.addParam("allowScriptAccess", "always");
        			so.addParam("flashVars", "allowScriptAccess=always");
                    so.write("flashcontent");
                    
                    var strstyleid = $this.attr('rel');
                    var strcolorid = $this.attr('rel');
                    //GET THE COLOR ID FROM THE S7 IMAGE NAME
                    strcolorid = strcolorid.split('_')[2];
                    strstyleid = strstyleid.split('_')[1];
                    
                    var replacedata = "pid="+strstyleid+"&colorid="+strcolorid
                    
                    if($('a.360spinner-modal').length > 0) {
	                    // TODO: replace url attribute with a valid attribute
	                    // from XHTML 1.1 spec
	                    // http://www.w3.org/TR/xhtml-modularization/abstract_modules.html#s_hypertextmodule
	                    // 
	                    
	                    // read the oldURL from the button for the 360 degree image
	                    var oldURL = $('a.360spinner-modal').attr("url");
	                    // replace the current pid with the pid taken from the
	                    // title attribute of the image inside the label
	                    var newURL = oldURL.replace(/pid=([^&]*)/, replacedata);
	                    // set the attribute url of the button
	                    $('a.360spinner-modal').attr("url", newURL);
	                    
                    }

                    
                    var oldURL2 = $('a.scene7enlarge-modal').attr("url");
                    var newURL2 = oldURL2.replace(/pid=([^&]*)/, replacedata);
                    
                    //$('a.scene7enlarge-modal').append(newURL2);
                    $('a.scene7enlarge-modal').attr("url", newURL2);
                    
                } else if(document.getElementById(jQuery(this.form).attr("rel")+'-image')) {
                	var changeImage = jQuery("#"+$this.attr('pid')+"-image");
                	changeImage.attr("src", $this.attr('rel'));
                }
                // $('.s7-stack img').eq(0).attr('src', $this.attr('rel'));
                //this label is on the product detail page.
                // [[ scene 7 integration point ]]
                // [[ show large image which corresponds to the chosen color ]]
            }
        }
        else {
          // is disabled.
          //alert('is disabled');
        }
        return false;
    }).each(function(){
        if($('#'+$(this).attr('for')).attr('disabled')){
            $(this).addClass('disabled');
        } else {
            $(this).append($('<span><span></span></span>'));
        }
    });
    
    // Click onto size labels at category refinements
    var sizeLabels = $('.select-size label');
    sizeLabels.click(function(){
        $this = $(this);
        // do not do anything on disabled labels
        // labels which are out of stock are disabled
        if(!$this.hasClass('disabled')){
             
            
            var relax = false;
            if($this.parent().parent().parent().parent().parent().attr('id') == 'product-filter-tabs'){
                
                if ($this.hasClass('selected')) {
                  $this.removeClass('selected');
                  relax = true;
                }
                else {
                   
                   $this.addClass('selected');
                }
            }
            else {
            
                // remove all selected classed from the labels in the size labels in this form
                jQuery('.select-size label', this.form).removeClass('selected');           
                $this.addClass('selected');
                $('.selection',this.parentNode).html( $('abbr',this).attr('title') || $('img',this).attr('alt') || $this.html() );
                //alert($this.parent().parent().parent().parent().parent().attr('id') );
            }
            if($this.parent().parent().parent().parent().parent().attr('id') == 'product-filter-tabs'){
                //this label is in the filter section.
                //var url = '?size='+($('abbr',this).attr('title') || $('img',this).attr('alt') || $this.html());
                var size = ($this.attr("id").split("-"))[1];

                addRefinementSize(size,relax);
                var url = $this.parent().attr('href');
                url = getRefineUrl();
                rf.filterResults(url);
            } else {
                // save selected variationSize in checkedAttributes map
                //alert('Save: ' + $("#"+$this.attr("for")).val());
                //debugger;
                checkedAttributes[jQuery(this.form).attr('rel')]["variationSize"] = $this.attr("title");
                updateVariationProduct(checkedAttributes[jQuery(this.form).attr("rel")]
                                                         , jQuery("input"
                                                         , jQuery(this.form))
                                                         , jQuery(this.form)
                                                         , ((checkedAttributes[jQuery(this.form).attr('rel')]["variationDimension"]) === undefined ? true : false));
            }
        }
        return false;
    }).each(function(){
        if($('#'+$(this).attr('for')).attr('disabled')){
            $(this).addClass('disabled');
        }
    });
    
    // Click onto dim labels at category refinements
    var sizeLabels = $('.select-dimension label');
    sizeLabels.click(function(){
        $this = $(this);
        // do not do anything on disabled labels
        // labels which are out of stock are disabled
        if(!$this.hasClass('disabled')){
             
            
            var relax = false;
            if($this.parent().parent().parent().parent().parent().attr('id') == 'product-filter-tabs'){
                
                if ($this.hasClass('selected')) {
                  $this.removeClass('selected');
                  relax = true;
                }
                else {
                   
                   $this.addClass('selected');
                }
            }
            else {
            
                // remove all selected classed from the labels in the size labels in this form
                jQuery('.select-dimension label', this.form).removeClass('selected');           
                $this.addClass('selected');
                $('.selection',this.parentNode).html( $('abbr',this).attr('title') || $('img',this).attr('alt') || $this.html() );
            }
            if($this.parent().parent().parent().parent().parent().attr('id') == 'product-filter-tabs'){
                //this label is in the filter section.                
                var size = ($this.attr("id").split("-"))[1];
                addRefinementDimensions(size,relax);
                var url = $this.parent().attr('href');
                url = getRefineUrl();
                rf.filterResults(url);
            } else {
                // save selected variationSize in checkedAttributes map
                checkedAttributes[jQuery(this.form).attr('rel')]["variationDimension"] = $this.attr("title");
                updateVariationProduct(checkedAttributes[jQuery(this.form).attr("rel")], jQuery("input", jQuery(this.form)), jQuery(this.form), true);
            }
        }
        return false;
    }).each(function(){
        if($('#'+$(this).attr('for')).attr('disabled')){
            $(this).addClass('disabled');
        }
    });
    
}

jQuery(document).ready(setupProductDesign);


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;
}

// remove is the pid of the product which should be removed
function updateVariationProduct(attrs, basketButton, form, enable) {
    // if the basket button is undefined try to find one
    if(basketButton === undefined) {
        basketButton = jQuery('#basket-button');
    }
    // if it is still not available
    if(basketButton === undefined) {
        alert("Can't find basket button.");
        return;
    }
    // grey out variations which are not available, not in stock etc.
    // remove swatches which are not available and mark swatches which are out of stock
    // as out of stock
    // go through all variations
    jQuery(".variation-select label", form).each(function () {
        var $this = jQuery(this);
        
        if($this.hasClass("selected")) {
            $('.selection',this.parentNode).html( $('abbr',this).attr('title') || $('img',this).attr('alt') || $this.html() );
        }
        $this.attr("for").match(/^(.*)-/);
        var attributeKey = RegExp.$1;
        // reset availCheckAttr
        var availCheckAttr = {};
        // assign all values from attrs to availCheckAttr   
        for(var i in attrs) {
            availCheckAttr[i] = attrs[i];
        }
        availCheckAttr[attributeKey] = $this.attr("title");
        var variant = getVariantAvailibilityByAttributes(availCheckAttr, form.attr("rel"));
        // if the variant exists
        if(variant !== undefined) {
           //debugger;
           if(variant.inStock == false || variant.online == false) {
        	   if(attributeKey == "variationColor")
        		   $this.css({'display':'none'});
        	   else
        		   $this.addClass("disabled");
           } else {
        	   $this.show();
               if(attributeKey == "variationColor")
        		   $this.css({'display':'block'});
        	   else
        		   $this.removeClass("disabled");
           }
        } else {
            $this.hide();
        }
    });
    
    // if not all properties are set in attrs just return.
    for(var property in attrs) {
        if(attrs[property] === undefined) {
            return;
        }
    }
    
    // append all the attribute values to one string
    // size: "L", color: "010"
    // becomes: "L010"
    // FIXME: What happens if I have color 00, 0 and size 00, 0. What would '000' be?
    var attrToStr = function(attrObj) {
        var result = "";
        jQuery.each(variations[form.attr("rel")].variations.attributes, function(){
            result += attrObj[this.id];
        });
        return result;
    }
    
    var attrsStr = attrToStr(attrs);
    var found;
    for (var i=0; i< variations[form.attr("rel")].variations.variants.length; i++) {
        variant = variations[form.attr("rel")].variations.variants[i];
        if (attrToStr(variant.attributes) === attrsStr) {
            found = variant;
        }
    }
    
    // TODO: add other price display
    // jQuery("#price").html(found.price);
    if(enable) {
	    if(found === undefined || !found.inStock) {
	        // disabled buttons do not fire onmouseover events, so just emulate disabled property
	        // jQuery("#basket-button").attr("disabled", "disabled");
	        basketButton.addClass("add-to-cart-disabled");
	        basketButton.unbind("click");
	        basketButton.bind("click", function () {
	            return false;
	        });
	    } else {
	    	//debugger;
	        // jQuery("#price").html(found.price);
	        jQuery(".pid", form).val(found.id);
	        // disabled buttons do not fire onmouseover events, so just emulate disabled property
	        // jQuery("#basket-button").removeAttr("disabled")
	        basketButton.removeClass("add-to-cart-disabled");
	        basketButton.tooltip({});
	        basketButton.unbind("click");
	        // assign handler which will assign product to basket
	        basketButton.bind("click", function() {
	            if($('body').attr('className').indexOf('wish-list') > -1) {
		        	return true;
	            } else {
	            	app.minicart.add(form, 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});
		            });
		        	return false;
	            }
	        });
	        
	        // update wishlist link with selected variation
	        var wishListLink = jQuery("#wishlistlink");
	        // only do this if the wishlist link is available
	        // this is not the case on the wishlist page
	        if(wishListLink.length > 0) {
		        var wishListURL = wishListLink.attr("href");
		        wishListURL = wishListURL.substr(0,wishListURL.search("pid=")) + "pid=" + found.id;
		        wishListLink.attr("href",wishListURL);
	        }
	    }
    }
}

/**
* This function checks for a map of attributes if
* variants with that configuration are available and
* if they are in stock.
* If no variant is available it will return undefined.
* If one is available it will return a map with the key inStock.
*/
function getVariantAvailibilityByAttributes(attrs, formRel) {
    // flag that shows that at least one variant with the attribute values
    // was found    
    var variantFound;
    // loop through all variants
    for (var i=0; i< variations[formRel].variations.variants.length; i++) {
        var goToNextVariant = false;
        var variant = variations[formRel].variations.variants[i];
        // alert(attrToStr(variant.attributes)+" === "+attrsStr);
        // loop through all the required attributes
        for(var property in variant.attributes) {
            // if the variant does not match one attribute
            if(attrs[property] !== undefined && variant.attributes[property] != attrs[property]) {
                // go to next variant
                goToNextVariant = true;
                break;
            }
        }
        // if the current variant didn't match
        if(goToNextVariant) {
            // go to next
            continue;
        }
        // if the current variant matched and is in stock
        if(variant.inStock) {
        	//debugger;
            // return map which tells that this product is in stock
            return {inStock:true, variant:variant.online};
        }
        // even if it was not in stock say at least that a variant was found
        variantFound = {inStock:false, online:false};
    }
    // if no variant was in stock return variantFound which could be probably undefined
    return variantFound;
}
