jQuery.noConflict();

jQuery(document).ready(function() {
    Uize.module ({
          required:[
            'UizeDotCom.Page.Example.library',
            'UizeDotCom.Page.Example',
            'Uize.Widget.Drag',
            'Uize.Fade.xFactory',
            'Uize.Curve.Rubber',
            'Uize.Curve.Mod'
          ],
          builder:function () {
            /*** create the example page widget ***/
              var page = window.page = new UizeDotCom.Page.Example ({evaluator:function (code) {eval (code)}});

            /*** configuration variables ***/
              var totalFrames = totalFramesInit;
              var frameUrlArray = frameUrlArrayInit;

            /*** state variables ***/
              var
                rotation = 0,
                lastFrameNo = -1,
                dragStartRotation
              ;

            /*** create the Uize.Widget.Drag instance ***/
              var rotationViewer = page.addChild (
                'rotationViewer',
                Uize.Widget.Drag,
                {
                  cancelFade:{duration:5000,curve:Uize.Curve.Rubber.easeOutBounce ()},
                  releaseTravel:function (speed) {
                    var
                      deceleration = 5000, // measured in pixels/s/s
                      duration = speed / deceleration
                    ;
                    return {
                      duration:duration,
                      distance:Math.round (speed * duration / 2),
                      curve:function (_value) {return 1 - (_value = 1 - _value) * _value}
                    };
                  },
                  html:function (input) {
                    var
                      htmlChunks = [],
                      frameNodeIdPrefix = input.idPrefix + '-frame'
                    ;
                    for (var frameNo = 0; ++frameNo <= totalFrames;) {
                      htmlChunks.push (
                        '<img' +
                          ' id="' + frameNodeIdPrefix + frameNo + '"' +
                          ' src="' + Uize.substituteInto (frameUrlArray[frameNo-1]) +'"' +
                        '/>'
                      );
                    }
                    return htmlChunks.join ('');
                  },
                  built:false
                }
              );

            /*** wire up the drag widget with events for updating rotation degree ***/
              function updateRotation (newRotation) {
                rotation = ((newRotation % 360) + 360) % 360;
                var frameNo = 1 + Math.round (rotation / 360 * (totalFrames - 1));
                if (frameNo != lastFrameNo) {
                  rotationViewer.showNode ('frame'+ lastFrameNo,false);
                  rotationViewer.showNode ('frame'+ (lastFrameNo = frameNo));
                }
              }
              rotationViewer.wire ({
                'Drag Start':function () {dragStartRotation = rotation},
                'Drag Update':function (e) {updateRotation (dragStartRotation - e.source.eventDeltaPos [0] / 2.5)}
              });

            /*** function for animating spin ***/
              function spin (degrees,duration,curve) {
                Uize.Fade.fade (updateRotation,rotation,rotation + degrees,duration,{quantization:1,curve:curve});
              }

            /*** initialization ***/
              Uize.Node.wire (window,'load',function () {spin (360,2700,Uize.Curve.easeInOutPow (4))});

            /*** wire up the page widget ***/
              page.wireUi ();
          }
        });
  });
    
    if(typeof selectedAssocProducts=='undefined') {
        var selectedAssocProducts = {};
    }
    var productNo;
/**************************** CONFIGURABLE PRODUCT **************************/
Product.Config = Class.create();
Product.Config.prototype = {
    initialize: function(config){
        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        this.settings   = $$('.super-attribute-select');
        this.state      = new Hash();
        this.priceTemplate = new Template(this.config.template);
        this.prices     = config.prices;

       /* this.settings.each(function(element){
            Event.observe(element, 'change', this.configure.bind(this))
        }.bind(this));*/

        // fill state
        this.settings.each(function(element){
            var attributeId = element.id.replace(/[a-z]*/, '');
            if(attributeId && this.config.attributes[attributeId]) {
                element.config = this.config.attributes[attributeId];
                element.attributeId = attributeId;
                this.state[attributeId] = false;
            }
        }.bind(this))

        // Init settings dropdown
        var childSettings = [];
        for(var i=this.settings.length-1;i>=0;i--){
            var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
            var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
            if(i==0){
                this.fillSelect(this.settings[i])
            }
            else {
                this.settings[i].disabled=false;
            }
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;
            childSettings.push(this.settings[i]);
        }

        // try retireve options from url
        var separatorIndex = window.location.href.indexOf('#');
        if (separatorIndex!=-1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            this.values = paramsStr.toQueryParams();
            this.settings.each(function(element){
                var attributeId = element.attributeId;
                element.value = this.values[attributeId];

                this.configureElement(element);
            }.bind(this));
        }
    },

    configure: function(event){
        var element = Event.element(event);
        this.configureElement(element);
    },

    configureElement : function(element) {
        
        //hack for IE7
        if (navigator.userAgent.indexOf('IE 7') != -1) {
            jQuery('input[name="'+element.name+'"]').removeAttr('checked');
            element.writeAttribute('checked', 'checked');
        }
        
        this.reloadOptionLabels(element);
        if(element.value){
           this.state[element.config.id] = element.value;
           if(element.parentNode.nextSetting){
               element.parentNode.nextSetting.disabled = false;
               this.fillSelect(element.parentNode.nextSetting);
               this.resetChildren(element.parentNode.nextSetting);
           }           
        }
        else {
            this.resetChildren(element.parentNode);
        }
        this.reloadPrice();
//      Calculator.updatePrice();
        /***** Load Associated Image : This should come after this.resetChildren is called *****/

        for (var a in this.config.attributes)
        {
            //var out = Form.getInputs('product_addtocart_form','radio','super_attribute['+a+']').find(function(radio) {return radio.checked;});
            var outQ = jQuery('input[name="super_attribute['+a+']"]:checked').val();
            
            if(outQ) {
                var vall = outQ;
            }
            
            for (i = 0; i < this.config.attributes[a].options.length; i++)
            {
                if (this.config.attributes[a].options[i].id != vall) continue;
                selectedAssocProducts[a] = this.config.attributes[a].options[i].products;
            }
        }        
        if(element.name) {
            var attributeId = element.name.replace(/[a-z_\[]*/, '');
            attributeId = attributeId.substr(0,attributeId.length-1);

            var intersect_value = intersect(selectedAssocProducts);
            if(intersect_value instanceof Array) {
                intersect_value = intersect_value[0];
            }
            
            var productNo = intersect_value || selectedAssocProducts[attributeId][0];
            
            if(productNo > 0) {
                hideImages();
                $('conf_'+productNo).addClassName('shown');
            } 
        }  
    },

    reloadOptionLabels: function(element){
        var selectedPrice;
        if(element.config){        
            selectedPrice = parseFloat(element.config.price)
        }
        else{
            selectedPrice = 0;
        }
        for(var i=0;i<element.parentNode.childNodes.length;i++){
            if(element.parentNode.childNodes[i].config){
                element.parentNode.childNodes[i].text = this.getOptionLabel(element.parentNode.childNodes[i].config, element.parentNode.childNodes[i].config.price-selectedPrice);                
            }
        }
    },

    resetChildren : function(element){
        if(element.config) {
            delete selectedAssocProducts[element.config.id]; // Added
        }
        if(element.childSettings) {       
            for(var i=0;i<element.childSettings.length;i++){
                element.childSettings[i].selectedIndex = 0;
                element.childSettings[i].disabled = false;               
                delete selectedAssocProducts[element.childSettings[i].config.id]; // Added
                if(element.config){
                    this.state[element.config.id] = false;                   
                }
            }
        }
    },

    fillSelect: function(element){    
        var attributeId = element.id.replace(/[a-z]*/, '');
        var options = this.getAttributeOptions(attributeId);
        var clickMe = null;
        
        this.clearSelect(element);

        var prevConfig = false;
        if(element.prevSetting){
            for (c=0;c<element.prevSetting.childNodes.length-1;c++)
            {
                var selected = element.prevSetting.childNodes[c];
                if (selected.checked)
                {
                    prevConfig = selected;
                }
            }            
        }

	if(options) {
            var index = 0;
            for(var i=0;i<options.length;i++){
                var allowedProducts = [];
                if(prevConfig) {     
                    for(var j=0;j<options[i].products.length;j++){
                        if(prevConfig.config.allowedProducts
                            && prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
                            allowedProducts.push(options[i].products[j]);
                        }
                    }
                } else {
                    allowedProducts = options[i].products.clone();
                }
                
                if(allowedProducts.size()>0){
                    options[i].allowedProducts = allowedProducts;
                        var newElement = document.createElement("input");
                        var newElementId = element.getAttributeNode("name").value + "_" + options[i].id;
                        newElement.type = "radio";
                        newElement.value = options[i].id;
                        newElement.id = newElementId;
                        newElement.name = element.getAttributeNode("name").value;
                        newElement.config = options[i];
                        newElement.style.marginTop = "-4px";
                        newElement.className= "pr_attr";

			Event.observe(newElement, 'click', this.configure.bind(this))

                        var labelElement = document.createElement("label");
                        labelElement.htmlFor = newElementId;
			
			var labelText;
                        if(this.config.attributes[attributeId] && this.config.attributes[attributeId].code=='color' && options[i].code)
                        {
                            $colorCode = options[i].code;
                            $regExpr = /#[A-Za-z0-9]{6}/;
                            $hexCode = $regExpr.exec($colorCode);                         
                            if ($hexCode!=null)
                            {
				var colorDivElement = document.createElement("div");
				colorDivElement.className = "colorSelector" + " " + newElementId.toString();
				colorDivElement.style.height = "30px";
				colorDivElement.style.width = "30px";
				labelElement.style.styleFloat = "left";
				labelElement.style.cssFloat = "left";
				labelElement.style.height = "30px";
				labelElement.style.paddingLeft = "5px";
                                colorDivElement.style.backgroundColor = $hexCode.toString();
				labelElement.appendChild(colorDivElement);
				newElement.style.marginTop = "0";
				newElement.style.styleFloat = "left";
				newElement.style.cssFloat = "left";
				newElement.style.height = "30px"

				var heightElement = document.createElement("span");
				heightElement.style.height = "30px";
				heightElement.style.display = "inline-block";
				element.appendChild(heightElement);
                            }
                            else
                            {
                                var colorLabel = document.createTextNode(" " + options[i].label);
				labelElement.appendChild(colorLabel);
                            }

                            labelText = document.createTextNode(" " + this.getOptionLabelWithoutOptionName(options[i], options[i].price));
                        }
                        else
                        {
                            labelText = document.createTextNode(" " + this.getOptionLabel(options[i], options[i].price));
                        }   

                        if (index==0)
                        {
                            clickMe = newElement;
                        }

                        labelElement.appendChild(labelText);                     
                        
                        var breakElement = document.createElement("div");
			breakElement.style.clear = "both";
            breakElement.style.height = "0";

			element.appendChild(newElement);
			element.appendChild(labelElement);
			element.appendChild(breakElement);

                    index++;
                }
            }
            
        } 
        clickMe.click();
    },

    getOptionLabel: function(option, price){
        var price = parseFloat(price);
        if (this.taxConfig.includeTax) {
            var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
            var excl = price - tax;
            var incl = excl*(1+(this.taxConfig.currentTax/100));
        } else {
            var tax = price * (this.taxConfig.currentTax / 100);
            var excl = price;
            var incl = excl + tax;
        }

        if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
            price = incl;
        } else {
            price = excl;
        }

        var str = option.label;
        if(price){
            if (this.taxConfig.showBothPrices) {
                str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
            } else {
                str+= ' ' + this.formatPrice(price, true);
            }
        }
        return str;
    },

    getOptionLabelWithoutOptionName: function(option, price){
        var price = parseFloat(price);
        if (this.taxConfig.includeTax) {
            var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
            var excl = price - tax;
            var incl = excl*(1+(this.taxConfig.currentTax/100));
        } else {
            var tax = price * (this.taxConfig.currentTax / 100);
            var excl = price;
            var incl = excl + tax;
        }

        if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
            price = incl;
        } else {
            price = excl;
        }

        var str = "";
        if(price){
            if (this.taxConfig.showBothPrices) {
                str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
            } else {
                str+= ' ' + this.formatPrice(price, true);
            }
        }
        return str;
    },

    formatPrice: function(price, showSign){
        var str = '';
        price = parseFloat(price);
        if(showSign){
            if(price<0){
                str+= '-';
                price = -price;
            }
            else{
                str+= '+';
            }
        }

        var roundedPrice = (Math.round(price*100)/100).toString();

        if (this.prices && this.prices[roundedPrice]) {
            str+= this.prices[roundedPrice];
        }
        else {
            str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
        }
        return str;
    },

    clearSelect: function(element){
        while ( element.childNodes.length >= 1 )
        {
            element.removeChild(element.firstChild);       
        }
    },

    getAttributeOptions: function(attributeId){
        if(this.config.attributes[attributeId]){            
            return this.config.attributes[attributeId].options;
        }
    },

    reloadPrice: function(){
        var price    = 0;
        var oldPrice = 0;
        var selected;
        for(var i=this.settings.length-1;i>=0;i--){
         
            var id = jQuery('input[name="'+this.settings[i].getAttribute('name')+'"]:checked').attr("id");
            for(var j=this.settings[i].childNodes.length-1;j>=0;j--){
                if (this.settings[i].childNodes[j].tagName == 'INPUT' || this.settings[i].childNodes[j].tagName == 'input') {
                    if(typeof(this.settings[i].childNodes[j]) == 'object' && this.settings[i].childNodes[j].getAttribute('id') == id){
                        selected = this.settings[i].childNodes[j];                    
                    }
                }
            }
            
            if(selected != null && typeof(selected) !== 'undefined'){
                price    += parseFloat(selected.config.price);
            }
        }
        
        optionsPrice.changePrice('config', {'price': price, 'oldPrice': oldPrice});
        optionsPrice.reload();

        return price;

        if($('product-price-'+this.config.productId)){
            $('product-price-'+this.config.productId).innerHTML = price;
        }
        this.reloadOldPrice();
    },

    reloadOldPrice: function(){
        if ($('old-price-'+this.config.productId)) {

            var price = parseFloat(this.config.oldPrice);
            for(var i=this.settings.length-1;i>=0;i--){
                var selected = this.settings[i].childNodes[this.settings[i].selectedIndex];
                if(selected.config){
                    price+= parseFloat(selected.config.price);
                }
            }
            if (price < 0)
                price = 0;
            price = this.formatPrice(price);

            if($('old-price-'+this.config.productId)){
                $('old-price-'+this.config.productId).innerHTML = price;
            }

        }
    }
}

    function intersect(ar) // ar can be an array of arrays or an asssociative array
    {
            if (ar == null) return false;
       
            var a = new Array();

            if (ar.length == undefined) // Associate Array
            {       
                for (var i in ar){
                 a.push(ar[i]);   
                }  
            }     
            else
             a = ar;

            if (a.length == 1) return false; // Single array ? Nothing to intersect with

            var common = new Array();
            var arq = new Array();
            
            function loop(a, alll,index, s_index, e_index)
            {               
                if (index == null) index = 0;
                if (s_index == null) s_index = 0;
                if (index == alll) return;
                if (a[index] == null) e_index = 0;
                if (e_index == null) e_index = a[index].length;

                arq.push(index);
                for (var i = s_index; i < e_index; i++)
                {
                    if (common.indexOf(a[index][i]) != -1) continue;
                    for (var j = 0; j < a[index + 1].length; j++)
                    {
                        if (a[index][i] != a[index+1][j]) continue;                       
                        
                        loop(a, alll, index + 1, j, j + 1);
                        
                        if (index + 1 == a.length - 1) {
                            common.push(a[index][i]);
                            break;
                        }                       
                    }
                }           
            }
            
            var alll = a.length - 1;
            
            loop(a, alll);
            return common;
    }
    function hideImages(){
        var items = $$('img.configure') ;
        for (var i = 0; i < items.size(); i++) {
                    items[i].removeClassName('shown');
        }
    }
