// Swatch Selector Javascript - Copyright 2011 CJM Creative Designs

//Make dropdowns function same as swatches

var selects       = null;
var clickHandler  = null;
var dynamicStatus = 0;
var selecttitle   = "";
var spConfig      = null;
var attoptions    = new Array();

function _init(dStatus, spconfig, selectTitle, attOptions){
    spConfig      = spconfig;
    dynamicStatus = dStatus;
    selecttitle   = selectTitle;
    attoptions    = attOptions;

    if(dynamicStatus == 1){
        var availabilityDiv = document.getElementById('availability'),
        shippingDiv = document.getElementById('shipby');
    }

    selects = document.getElementsByTagName('select');
    var numSelects = selects.length;

    for (var i=0; i<numSelects; i++) {
        setClickHandler(selects[i]);
    }
    //  Patch per autoselect se il primo prodotto non è disponibile
    AutoSelectOnLoad();
}

function AutoSelectOnLoad() {
    var selectValues = new Array()
    $$('.swatchSelect option').each(function(value){
        selectValues.push(value.value)
    })
    
    $$('.swatchContainer a').each(function(value){
        if(!selectValues.find(value.id)){
            $(value.id).addClassName('disabled')
        }
        else if($(value.id).hasClassName('disabled')){
            $(value.id).removeClassName('disabled')
        } else Event.observe(window, 'load', function() {
            AutoSelect('attribute-' + value.id, $(value.id))
        });
    });
    Event.observe(window, 'load', function() {
        baseurl = $$('.swatchSelected:last')[0].readAttribute('onclick')
        baseurl = baseurl.split("value,'")
        baseurl = baseurl[1].split("'")
        miniGallery($('productId').value,baseurl[0])
    });
}

Array.prototype.find = function(searchStr) {
    var returnArray = false;
    for (i=0; i<this.length; i++) {
        if (typeof(searchStr) == 'function' && searchStr.test != undefined) {
            if (searchStr.test(this[i])) {
                if (!returnArray) {
                    returnArray = []
                }
                returnArray.push(i);
            }
        } else {
            if (this[i]===searchStr) {
                if (!returnArray) {
                    returnArray = []
                }
                returnArray.push(i);
            }
        }
    }
    return returnArray;
}
function miniGallery(theId,baseUrl){
    if($('yes').style.display==''){
        jQuery('.img-normal').attr('src', '/skin/frontend/default/default/images/trans.png')
        $('configuratorLoading').show()

    new Ajax.Updater('hiddenList', baseUrl+'configuratorgallery?productId='+theId, {
        evalScripts: 'true', 
        method: 'get', 
        onComplete:function(){
            jQuery('#media-gallery li').remove();
            jQuery('.more_common').clone().appendTo(jQuery('.overview'));
            var firstGalleryImgLink = jQuery('#media-gallery div.viewport a').get(0);
            $('image').src = firstGalleryImgLink.rel;
            $('link-normal').href = firstGalleryImgLink.href;
            jQuery('#media-gallery').tinycarousel({
                display: 2
            });
            $('configuratorLoading').hide()
            $('link-normal').show() 
        }
    });
    }
    
//var theIdBase = jQuery('.swatchSelected:last').attr('id');
    
    
/*if(jQuery('.more'+theId+'')!=jQuery('.more'+theIdBase+'')){
        jQuery('.more'+theIdBase+'').clone().appendTo(jQuery('.overview'));
    }*/
}
function setClickHandler(element) {
    element.onchange = function () {
        var id = this.options[this.selectedIndex].value;
        
        if(id == ''){
            var runMeArgs = [this.id, '', 'optionzero'];
            colorSelected.apply(this, runMeArgs);
        }
        if(document.getElementById(id) && document.getElementById(id) !== null && attoptions.length > 0){
            clickHandler = document.getElementById(id).onclick;
            clickHandler.apply(this);
        }
        if(dynamicStatus == 1){
            availabilityDiv.innerHTML = spConfig.config.mainstock;
            shippingDiv.innerHTML = spConfig.config.mainship;
            if(element.options[element.selectedIndex].config !== undefined && element.options[element.selectedIndex].config.shipsby !== undefined){
                availTxt = element.options[element.selectedIndex].config.customstock;
                shipTxt = element.options[element.selectedIndex].config.shipsby;
                expecTxt = element.options[element.selectedIndex].config.expected;
                if(expecTxt !== ''){
                    availTxt = availTxt + '<br><br>' + expecTxt;
                    availabilityDiv.innerHTML = availTxt;
                    if(shippingDiv !== null){
                        shippingDiv.innerHTML = '';
                    }
                } else {
                    availabilityDiv.innerHTML = availTxt;
                    if(shippingDiv !== null){
                        shippingDiv.innerHTML = shipTxt;
                    }
                }
            }
        }
    }
}

function AutoSelect(AttrId,element){
    $('add-to-cart').writeAttribute('onclick','productAddToCartForm.submit()')
    if($('add-to-cart').hasClassName('btn-small-off')){
        $('add-to-cart').removeClassName('btn-small-off')
    }
    //inizializzo array per le hidden select
    var selectArr = new Array()
    var selectValues = new Array()
    //creo array e lo popolo con tutti gli ul presenti
    var ulAttribute = $$('.ul-attribute')
    //inizializzo array di appoggio
    var Attrlist = new Array()
    //recupero l' id dell'ul padre il cui figlio è stato selezionato
    AttrId = 'ul-attribute'+AttrId
    
    //inverto l'ordine originale
    ulAttribute.reverse()
    
    
    //genero l'array di attribute id disponibile per il configurabile corrente
    for (i=0;i<ulAttribute.length;i++){
        //se è diverso da quello selezionato popolo array di appoggio
        if(AttrId!=ulAttribute[i].id){
            Attrlist.push(ulAttribute[i])
        }
        //altrimento esco dal ciclo
        if(AttrId==ulAttribute[i].id){
            break;
        }
    }

    Attrlist.reverse()
    //riordino l'array per mantenere l'ordine corretto dei nodi ul-attribute in modo da rispettare la sequenza corretta
    
    Attrlist.each(function(value) {
        //recupero id della select corrente 
        selectId = value.id.split('-');
        
        //popolo l'array con i value della select corrente
        for(i=0;i<$(selectId[1]).options.length;i++)
        {
            if($(selectId[1]).options[i].value!=""){
                selectArr.push($(selectId[1]).options[i].value)
            }
        }
        //accedo al nodo da selezionare
        val = $(value.id).down().down();
        
        //verifico la corrispondenza tra gli id delle ul ed i value della select
        while(!selectArr.find(val.id)){
            if (!val || !val.up() || !val.up().next())
                break;
            //se non trovo corrispondenza passo al nodo successivo
            val = val.up().next().down()
            if(val=='undefined') {
                break;
            }
        }
        if(val!='undefined'){
            //se il nodo successivo è un elemento 'a' trovato allora esegui il click associato
            //considerato che il modulo gira attorno all'evento onclick ho dovuto utilizzare l'eval 
            
            tmp = val.readAttribute('onclick').split(';');
            execone = tmp[0].split("'");
            exectwo = tmp[1].split("'");
            colorSelected(execone[1],execone[3],execone[5],execone[7]);
            productManager.updateProductPanel(exectwo[1], exectwo[3]);
        }
    });
    
    $('no').hide()
    $('yes').show()
    
    $$('.swatchSelect option').each(function(value){
        selectValues.push(value.value)
    })
    
    $$('.swatchContainer a').each(function(value){
        if(!selectValues.find(value.id)){
            $(value.id).addClassName('disabled')
        }
        else if($(value.id).hasClassName('disabled')){
            $(value.id).removeClassName('disabled')
        }
    })
    
    if($(element.id).hasClassName('disabled')){
        $('no').show()
        $('yes').hide()
        $('add-to-cart').writeAttribute('onclick','return false')
        $('add-to-cart').addClassName('btn-small-off')
    }
}

//Main Swatch Function

function colorSelected(id, value, product_image_src, front_label) {
    var theswitchis = 'off',
    hasimgs = 'no',
    switchCounter = 0,
    k = 0,
    b = 0,
    l= 0,
    thelements = [],
    children = [],
    newchildren = [],
    thisdiv = '',
    thisopt = '',
    nextAttribute = '',
    nextAttrib = [],
    theoptions = [],
    selectedmoreview = [],
    moreviews = [],
    disableDiv = '',
    i,d,e,h,z,dropdown,themoreviewimgs,textdiv,theattributeid,thedropdown,thetextdiv,selectedid,thedivid,thediv,dropdownval,base_image,theSwatch;
    
    //If the dropdown is disabled, do nothing because we are not allowed to select an option yet
    if(document.getElementById(id).disabled){
        return;
    }

    //Get the swatch that was just clicked
    children = document.getElementById('ul-' + id).getElementsByTagName('*');
    
    for(h = 0; h < children.length; h += 1) {
        if (children[h].id === value) {
            theSwatch = children[h];
        }
    }

    //If swatch is disabled, do nothing
    if (theSwatch.className === 'disabledSwatch' || theSwatch.className === 'swatchSelected') {
        return;
    }
    
    if(value !== ''){
        // Set the base image to the selected swatch
        base_image = document.getElementById("image");
        link_image = document.getElementById("link-normal")
        if (product_image_src !== '') {
            document.getElementById('loadingImage').style.visibility = 'visible';
            //base_image.style.visibility = 'hidden';
            //if(base_image.src == product_image_src){
            //    base_image.src = '';
            //}
            if(product_image_src!=undefined){
        //base_image.setAttribute("src", product_image_src);
        //link_image.setAttribute("href", product_image_src);
        }
        }


        // Load the more views for the selected swatch
        selectedmoreview = document.getElementsByName('moreview' + value);
        if (document.getElementById('ul-moreviews') !== null ) {
            themoreviewimgs = document.getElementById('ul-moreviews').getElementsByTagName('li');
        }
        selectedmoreviewtitle = document.getElementById('moreviews-title');
    }

    // ------------------------------------------------------------------------------------------
    // --- RESET ALL SWATCH BORDERS, DROPDOWNS, MORE VIEWS AND TEXT BELOW THE SELECTED SWATCH ---
    // ------------------------------------------------------------------------------------------

    // If Custom Stock Status extension is installed, reset the availability text

    if(dynamicStatus == 1){
        availabilityDiv.innerHTML = spConfig.config.mainstock;
        shippingDiv.innerHTML = spConfig.config.mainship;
    }

    // Go through every swatch attribute on product

    for (i = 0; i < attoptions.length; i += 1)
    {
        theattributeid = attoptions[i];
        thedropdown = 'attribute' + theattributeid;
        thetextdiv = 'divattribute' + theattributeid;
        selectedid = id;

        // If we are on the selected swatch dropdown, turn the switch on
        if (selectedid === thedropdown) {
            theswitchis = 'on';
        }

        // If we are either on the dropdown we selected the swatch from or a dropdown below
        if (theswitchis === 'on')
        {
            // If we are on the dropdown after the selected swatch dropdown, get
            // the next attribute id
            if(switchCounter === 1) {
                nextAttribute = theattributeid;
            }

            dropdown = document.getElementById(thedropdown);
            textdiv =  document.getElementById(thetextdiv);
            if(textdiv !== null) {
                textdiv.innerHTML = selecttitle;
            }
            dropdown.selectedIndex = 0;

            // If we are not on the selected attribute, reset all swatches below so they are all displayed.
            if(switchCounter !== 0) {

                thelements = document.getElementById('ul-attribute' + theattributeid).getElementsByTagName('*');

                for(h = 0; h < thelements.length; h += 1) {
                    if (thelements[h].nodeName.toLowerCase() === 'div' || thelements[h].nodeName.toLowerCase() === 'img') {
                        thedivid = thelements[h].id;
                        thisdiv = document.getElementById(thedivid);
                        thisdiv.className = "swatch";
                    //thisdiv.title = thisdiv.alt;
                    }
                }
            }

            // Go through all the swatches of this attribute and reset
            for (z = 1; z < dropdown.options.length; z += 1)
            {
                dropdownval = dropdown.options[z].value;
                moreviews = document.getElementsByName('moreview' + dropdownval);
                thediv = document.getElementById(dropdownval);
                // Unselect the swatch
                if (thediv !== null ) {
                    thediv.className = "swatch";
                //thisdiv.title = thisdiv.alt;
                }
                // Hide the more view images of the swatch
                if (moreviews !== null ) {
                    for(d = 0; d < moreviews.length; d += 1) {
                        moreviews[d].style.display = 'block';
                    }
                }
            }
            switchCounter += 1;
        }
    }

    // If there is only one attribute on this product, set the
    // next attribute to none
    if(nextAttribute === null || nextAttribute === '') {
        nextAttribute = 'none';
    }

    // ------------------------------------------------------------------------
    // ------------------- SELECT THE CORRECT SWATCH --------------------------
    // ------------------------------------------------------------------------

    if(value !== ''){
        
        dropdown = document.getElementById(id);

        for (i = 0; i < dropdown.options.length; i += 1)
        {
            if ( dropdown.options[i].value === value )
            {
                if(document.getElementById('div' + id) !== null) {
                    if(front_label !== 'null') {
                        document.getElementById('div' + id).innerHTML = front_label;
                    }
                    else {
                        document.getElementById('div' + id).innerHTML = dropdown.options[i].text;
                    }
                }
                
                document.getElementById(value).className = "swatchSelected";

                if ( selectedmoreview !== null ) {
                    for(e = 0; e < selectedmoreview.length; e += 1) {
                    //selectedmoreview[e].style.display = 'block';
                    }
                }
                dropdown.selectedIndex = i;
                break;
            }
        }

        //If there are moreviews displayed, display the more views title
        if(themoreviewimgs !== undefined && themoreviewimgs.length > 0){
            for(h = 0; h < themoreviewimgs.length; h += 1) {
                if (themoreviewimgs[h].style.display === 'block' || themoreviewimgs[h].style.display === '') {
                    hasimgs = 'yes';
                    break;
                }
            }
        /*if(hasimgs === 'yes' ) {
				selectedmoreviewtitle.style.display = 'block'; }
			else {
				selectedmoreviewtitle.style.display = 'none'; }*/
        }

        spConfig.configureElement($(id));
    }
    

    //FOR CUSTOM STOCK STATUS EXTENSION
    //Set the availability text and shipping date when a swatch is clicked

    swatcher = document.getElementById(id);

    if(dynamicStatus == 1){
        if(swatcher.options[swatcher.selectedIndex].config !== undefined && swatcher.options[swatcher.selectedIndex].config.shipsby !== undefined){
            availTxt = swatcher.options[swatcher.selectedIndex].config.customstock;
            shipTxt = swatcher.options[swatcher.selectedIndex].config.shipsby;
            expecTxt = swatcher.options[swatcher.selectedIndex].config.expected;
            if(expecTxt !== ''){
                availTxt = availTxt + '<br><br>' + expecTxt;
                availabilityDiv.innerHTML = availTxt;
                if(shippingDiv !== null){
                    shippingDiv.innerHTML = '';
                }
            } else {
                availabilityDiv.innerHTML = availTxt;
                if(shippingDiv !== null){
                    shippingDiv.innerHTML = shipTxt;
                }
            }
        }
    }

    // END CUSTOM STOCK CODE

    // -------------------------------------------------------------------------
    // -------------------- HIDE UNAVAILABLE SWATCHES --------------------------
    // -------------------------------------------------------------------------

    // If there is more then one swatch attribute on this product
    if(nextAttribute !== 'none' && value !== '') {

        // Get all the swatches of the next attribute
        children = document.getElementById('ul-attribute' + nextAttribute).getElementsByTagName('*');
        // Set the next attributes dropdown
        nextAttrib = document.getElementById('attribute' + nextAttribute);

        // Get all wanted option values
        for(h = 0; h < nextAttrib.options.length; h += 1) {
            if(nextAttrib.options[h].value !== '') {
                theoptions[b] = nextAttrib.options[h].value;
                b += 1;
            }
        }

        //Get all divs and imgs
        for(h = 0; h < children.length; h += 1) {
            if (children[h].nodeName.toLowerCase() === 'div' || children[h].nodeName.toLowerCase() === 'img') {
                newchildren[k] = children[h].id;
                k += 1;
            }
        }

        for(h = 0; h < newchildren.length; h += 1) {
            thisdiv = newchildren[h];
            if(theoptions[l]) {
                thisopt = theoptions[l];
                if(thisopt === thisdiv) {
                    disableDiv = document.getElementById(thisdiv);
                    disableDiv.className = 'swatch';
                    l += 1;
                } else {
                    disableDiv = document.getElementById(thisdiv);
                    disableDiv.className = 'disabled';
                //disableDiv.title += ' - Not Available';
                }
            } else {
                disableDiv = document.getElementById(thisdiv);
                disableDiv.className = 'disabled';
            //disableDiv.title += ' - Not Available';
            }
        }
    }
// Not sure if this is still needed
//this.reloadPrice();
}

