/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Varien
 * @package     js
 * @copyright   Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
if (typeof Product == 'undefined') {
    var Product = {};
}

/**************************** CONFIGURABLE PRODUCT **************************/
Product.Config = Class.create();
Product.Config.prototype = 
{
	"defaultMedia": null,
    "initialize": function(config)
    {
        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        if (config.containerId) 
        {
            this.settings   = $$('#' + config.containerId + ' ' + '.super-attribute-select');
        } 
        else 
        {
            this.settings   = $$('.super-attribute-select');
        }
        
        this.state      = new Hash();
        this.priceTemplate = new Template(this.config.template);
        this.prices     = config.prices;
        
        // Set default values from config
        if (config.defaultValues) 
        {
            this.values = config.defaultValues;
        }
        
        // Overwrite defaults by url
        var separatorIndex = window.location.href.indexOf('#');
        if (separatorIndex != -1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            var urlValues = paramsStr.toQueryParams();
            if (!this.values) {
                this.values = {};
            }
            for (var i in urlValues) {
                this.values[i] = urlValues[i];
            }
        }
        
        // Overwrite defaults by inputs values if needed
        if (config.inputsInitialized) 
        {
            this.values = {};
            this.settings.each(function(element) 
            {
                if (element.value) 
                {
                    var attributeId = element.id.replace(/[a-z]*/, '');
                    this.values[attributeId] = element.value;
                }
            }.bind(this));
        }
        
        // Put events to check select reloads 
        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;  
            
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;

            if (i == 0)
            {
                this.fillSelect(this.settings[i]);
                if (nextSetting)
                {
                    this.fillSelect(nextSetting);
                }
                
                var optionProduct = this.settings[i].options[this.settings[i].selectedIndex];
                if(optionProduct.config.price != 0)
                {
                	this.reloadPrice();
                }
     
                var parentContainer = document.getElementById("main-visual");
                var media_identifier = 'content_media_conf_' + this.settings[i].value;
                
                if($(media_identifier) != null)
                {
        	        var 
        	        	url = $(media_identifier).readAttribute('add_content_media_conf_url'),
        	        	_this = this
        	        ;

        			driver.addClass(parentContainer, "loading");
        	        new Ajax.Request(
        	        		url, {
        					method: 'GET',
        					evalJS: true,
        					onComplete: function(response) 
        					{
        	        			_this.updateMedia.call(_this, eval('(' + response.responseText + ')'));
        						driver.removeClass(document.getElementById("main-visual"), "loading");
        					}.bind(this)
        				}
        			);
                }
            }
            /*
            else
            {
                this.settings[i].disabled = true;
            }
            */
            childSettings.push(this.settings[i]);
        }

        // Set values to inputs
        this.configureForValues();
        document.observe("dom:loaded", this.configureForValues.bind(this));
    },
    
    // FIXME : il serait beaucoup plus simple d'updater le contenu de "main-visual"
    // le script du slider en fait parti
    "updateMedia": function(data)
    {    	
        var 
        	_this = this,
	    	_contentMedia = $("media_product_conf") || null,
	    	_contentSlide = $("media_product_conf_slide") || null,
	    	_contentTitle = $('product_name_selected') || null,
	    	_contentFlash = $('product_perso_preview') || null,
	    	_contentDescription = $('product_description_selected') || null,			
	    	_handleMediaSlider = function(data)
			{
				_executeAfterOnload.push(function()
				{
					var _productZoom = document.getElementById("main-visual");
					if (typeof productView == "undefined"|| !_productZoom)
					{
						return false;
					}
					if (productView.elements.container == _productZoom)
					{
						productView.destroy();
					}
					
					// Update de l'image de preview 
					productView.init(
					{
						"container": _productZoom,
						"content": driver.find(_productZoom, ".scroll-content")[0] || null, 
						"links": driver.find(_productZoom, ".menu-item a"),
						"slides": driver.find(_productZoom, ".slide-item")
					});
					if (typeof window.parsePersonalizeOptions != "undefined")
					{
			            window.parsePersonalizeOptions(data.product_personalization || null);	
					}	
					
					// Paramètrage du flash	
					if (typeof _saveConfigPreview != "undefined")
					{
						if (typeof data["MF"] != "undefined")
						{
							_saveConfigPreview("MF", data["MF"] || null);
						}
						if (typeof data["MMC"] != "undefined")
						{
							_saveConfigPreview("MMC", data["MMC"] || null);
						}
						if (typeof data["TMC1"] != "undefined")
						{
							_saveConfigPreview("TMC1", data["TMC1"] || null);
						}
						if (typeof data["TMC2"] != "undefined")
						{
							_saveConfigPreview("TMC2", data["TMC2"] || null);
						}
						if (typeof data["TF1"] != "undefined")
						{
							_saveConfigPreview("TF1", data["TF1"] || null);
						}
						if (typeof data["TF2"] != "undefined")
						{
							_saveConfigPreview("TF2", data["TF2"] || null);
						}
					}
				})
			}
	    ;        
	    
        // Stockage des valeurs par défaut
    	if (typeof data == "undefined" || !data || !this.defaultMedia)
    	{
        	this.defaultMedia = {
    			"product_media": (_contentMedia) ? _contentMedia.innerHTML : "", 
    			"product_slide": (_contentSlide) ? _contentSlide.innerHTML : "",
    			"product_name": (_contentTitle) ? _contentTitle.innerHTML.toString() : "",
    	    	"product_perso": (_contentFlash) ? _contentFlash.innerHTML.toString() : "",
    			"product_description": (_contentDescription) ? _contentDescription.innerHTML.toString() : "",
    			"product_personalization": ""
    		};
        	_handleMediaSlider(this.defaultMedia);
    		return false;
    	}

    	var data = data || this.defaultMedia || null;        
        if (!data)
        {
        	return false;
        }
        
        this.currentData = data;

	  	// Mise à jour du contenu media
        if (_contentMedia)
        {
    		driver.putHTML(_contentMedia, data['product_media']);
        }
        if (_contentSlide)
        {
    		driver.putHTML(_contentSlide, data['product_slide']);
        }
        if (_contentFlash)
        {
    		driver.putHTML(_contentSlide, data['product_perso']);
        }

        // Mise à jour des données
        if (_contentTitle)
        {
        	driver.putHTML(_contentTitle, data['product_name']);
        }
        if (_contentDescription)
        {
        	driver.putHTML(_contentDescription, data['product_description']);
        }
		
		// Lancement du slider
         _handleMediaSlider(data);
         
		if (typeof _handleScriptAfterOnload != "undefined")
		{
			_handleScriptAfterOnload();
		}
    },
    
    configureForValues: function () 
    {
    	// préselection du contenu
        if (this.values && typeof oTryptique == "undefined") 
        {
        	var _this = this;
            this.settings.each(function(element)
            {
                var attributeId = element.attributeId;
                element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
                
                // Update du contenu
                _this.configure.bind(_this, element);
                
            }.bind(this));
        }
        
        // Default
        this.updateMedia();
    },

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

    "configureElement" : function(element) 
    {
        this.reloadOptionLabels(element);
        if(element.value)
        {
            this.state[element.config.id] = element.value;
            if(element.nextSetting)
            {
                element.nextSetting.disabled = false;
                this.fillSelect(element.nextSetting);
                this.resetChildren(element.nextSetting);
            }
        }
        // Etat par défaut
        else 
        {
            this.resetChildren(element);
        	this.updateMedia.call(this, this.defaultMedia);
        }
        this.reloadPrice();
        
        var parentContainer = document.getElementById("main-visual");
        var media_identifier = 'content_media_conf_' + element.value;
        if($(media_identifier) != null)
        {
	        var 
	        	url = $(media_identifier).readAttribute('add_content_media_conf_url'),
	        	_this = this
	        ;
			driver.addClass(parentContainer, "loading");
	        new Ajax.Request(
	        		url, {
					method: 'GET',
					evalJS: true,
					onComplete: function(response) 
					{
						_this.updateMedia.call(_this, eval('(' + response.responseText + ')'));
						driver.removeClass(parentContainer, "loading");
						
					}.bind(this)
				}
			);
        }
    },

    "reloadOptionLabels": function(element){
        var selectedPrice;
        if(element.options[element.selectedIndex].config && !this.config.stablePrices){
            selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
        }
        else{
            selectedPrice = 0;
        }
        for(var i=0;i<element.options.length;i++){
            if(element.options[i].config){
                element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
            }
        }
    },

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

    "fillSelect": function(element)
    {
        var attributeId = element.id.replace(/[a-z]*/, '');
        var options = this.getAttributeOptions(attributeId);
        this.clearSelect(element);
        element.options[0] = new Option(this.config.chooseText, '');

        var prevConfig = false;
        if(element.prevSetting)
        {
            prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
        }  
        if(!options) 
        {
        	return false;
        }
        
        var index = 1;
        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;
                element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
                if (typeof options[i].price != 'undefined') 
                {
                    element.options[index].setAttribute('price', options[i].price);
                }
                if (typeof options[i].selected != 'undefined' && options[i].selected == true)
                {
                	element.selectedIndex = index;
                    element.options[index].setAttribute('selected', 'selected');
                }
                element.options[index].config = options[i];
                index++;
            }
        }

		// FineTuning du select     
		this.fakeSelectElement = new selectElement();
		this.fakeSelectElement.init(element);
    },

    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;
    },

    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){
        for(var i=element.options.length-1;i>=0;i--){
            element.remove(i);
        }
    },

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

    reloadPrice: function(){
        if (this.config.disablePriceReload) {
            return;
        }
        var price    = 0;
        var oldPrice = 0;
        for(var i=this.settings.length-1;i>=0;i--)
        {
            var selected = this.settings[i].options[this.settings[i].selectedIndex];
            if(selected.config){
                price    += parseFloat(selected.config.price);
                oldPrice += parseFloat(selected.config.oldPrice);
            }
        }

        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 (this.config.disablePriceReload) {
            return;
        }
        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].options[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;
            }

        }
    }
}

