/**
 * Javascript-Functions - shop.held.de
 * (c) CLICKSPORTS DIGITAL SOLUTIONS
 * http://www.clicksports.de
 * 
 * $Rev: 39 $
 * $Author: cs $
 * $Date: 2011-03-29 08:31:19 +0200 (Di, 29 Mrz 2011) $
 */

// IE6 Browser sniffing
Prototype.Browser.IE6=Prototype.Browser.IE && parseInt(navigator.userAgent.substring (navigator.userAgent.indexOf("MSIE")+5))==6;

document.observe('dom:loaded', function() {
	
	$$('a[rel=external]').each(function(elm) {
		
		elm.writeAttribute({ target: '_blank' });
	});
	
	startTabs('description_tabs');
	createJumpMenu('filter');
});

/**
 * Start a new instance of Control.Tabs on target element
 * @param {Object} elm Element to use
 */
function startTabs(elm) {
	
	var elm = $(elm);
	if(!elm) return;

	$$('.tab_content').invoke('hide')	
	var tab = new Control.Tabs(elm);
}

/**
 * Create a jump menu for all selects with given classname
 * @param {Object} cn Classname for selects
 */
function createJumpMenu(cn) {
	
	$$('select.' + cn).each(function(sel) {
		
		sel.observe('change', function(e) {
			
			var val = Event.element(e).getValue();
			if(val.length != 0 && val !== undefined) {
				
				document.location.href=val;
			}
		});
	});
}

var CLICKSPORTS_getMerchant = Class.create({
	
	initialize: function(opts) {

		this.opts = Object.extend({
			url: '/merchantapi_connector.php',
			method: 'post',
			minchars: 2,
			zip: false,
			country: false,
			getAction: 'apiZip'
		}, opts || {});
		
		this.container = $('held-merchants');
		this.merchantnr = $('shippmethod:aitoc_checkout_169');
		this.location = $('shippmethod:aitoc_checkout_171');
		
		this.fieldwrapper = $('additional-checkout-shipping').hide();
		
		var heading = '<h2>Wählen Sie bitte Ihren Held Servicepartner aus</h2>';
		
		this.available = new Element('ul', { id: 'available_merchants' }).hide();
		this.container.insert(heading);
		this.container.insert(this.available);
		
		this.available.observe('click', this.clickListener.bind(this));
		this.merchantnr.writeAttribute({ readonly: true });
		this.location.writeAttribute({ readonly: true });
	},

	/**
	 * Handle clicks for available merchants
	 * @param {Object} e
	 */
	clickListener: function(e) {
		
		var clicked = Event.findElement(e, 'li');
		var active_id = this.getMerchantId(clicked) 

		this.merchantnr.writeAttribute({ readonly: false });
		this.merchantnr.value = active_id;
		this.merchantnr.writeAttribute({ readonly: true });

		var postaldata = clicked.down('span.formcontent');

		// Write merchant data to visible field
		this.location.writeAttribute({ readonly: false });
		this.location.value = postaldata.innerHTML.replace('&amp;', '&');
		this.location.writeAttribute({ readonly: true });
		
		this.fieldwrapper.show();
	},
	
	cleanUp: function() {

		//this.container.hide();
		
		this.location.writeAttribute({ readonly: false });
		this.location.value = '';
		this.location.writeAttribute({ readonly: true });

		this.merchantnr.writeAttribute({ readonly: false });
		this.merchantnr.value = '';
		this.merchantnr.writeAttribute({ readonly: true });
	},

	/**
	 * Get the merchant id from an element
	 * @param {Object} elm
	 * @return {String}
	 */
	getMerchantId: function(elm) { return elm.id.replace('merchant_', ''); },
	
	/**
	 * Set minimal char count
	 * 
	 * @param {Number} min
	 * @return {Object} CLICKSPORTS_getMerchant
	 */
	setMinChars: function(min) {
		
		this.opts.minchars = min;
		return this;
	},
	
	setZip: function(zip) {

		this.opts.zip = zip.substring(0, this.opts.minchars);
		return this;
	},
	
	setCountry: function(country) {

		this.opts.country = country;
		return this;
	},
	
	getAvailable: function() {
		
		var req = new Ajax.Request(this.opts.url, {
			method: this.opts.method,
			parameters: {
				action: this.opts.getAction,
				zip: this.opts.zip,
				country: this.opts.country
			},
			onCreate: function(){
				
				this.container.addClassName('searching');
			}.bind(this),
			onSuccess: function(transport) {
				
				this.available.update('');
				var response = transport.responseText.evalJSON();
				
				response.each(function(merchant) {
					
					this.buildMerchantHtml(merchant);
				}, this);
				
				this.available.show().removeClassName('searching');
			}.bind(this)
		});
	},
	
	buildMerchantHtml: function(merchant) {

		var contents = '<table class="merchant"><tbody><tr>';
		contents += '<td class="merchant-name"><strong>' + merchant.haendler_name + '</strong></td>';
		
		contents += '<td class="merchant-icon">';
		
		// Add the merchant logo if he
		// is not a regular merchant
		if(merchant.haendler_kategorie != 0) {

			var cattitle = '';

			// Get the merchant category ids name
			switch(merchant.haendler_kategorie) {
				
				case '1': cattitle = 'Powershop'; break;
				case '2': cattitle = 'Powershop Star'; break;
			}
			
			contents += '<img src="http://www.held.de/files/merchant_' + merchant.haendler_kategorie + '.jpg"';
			contents += ' title="' + cattitle + '"';
			contents += ' alt="" />';
		}
		contents += '</td>';
		
		// Get available sortiments
		contents += '<td class="merchant-sortiments">';
		var sortiment = merchant.r_haendler_sortimente.split('|+|');
		sortiment.each(function(s) {
			
			contents += '<img src="http://www.held.de/files/sortiment_' + s + '.jpg" alt="" />';
		}, this);
		contents += '</td>';

		contents += '<td style="display: none;"><span class="formcontent">' + merchant.haendler_name + "\n" + merchant.haendler_strasse + "\n" + merchant.haendler_plz + ' ' + merchant.haendler_stadt + "\n\n" + merchant.haendler_email + "\n" + merchant.haendler_telefon + '</span></td>';
		contents += '</tr></tbody></table>';

		var me = new Element('li', { id: 'merchant_' + merchant.haendler_nummer, 'className': this.opts.merchant_class }).update(contents);
		this.available.insert(me);
	}
});

/**
 * Get the wanted merchants for a zip
 * 
 * @todo Check dependencies in views and remove this script if there are no known occurences any more
 * @deprecated Was replaced by CLICKSPORTS_getmerchant above! Do not use this code anymore.
 * 
 * @param {Element} inp Input field
 * @param {Element} hidden Hidden field to populate
 * @param {Array} opts Options
 */
var getMerchant = Class.create({

	response: '',
	
	/**
	 * Initialize app
	 * @constructor
	 * @return this
	 */
	initialize: function(inp, hidden, postal, opts) {

		this.opts = Object.extend({
			url: '/merchantapi_connector.php',
			method: 'post',
			minchars: 2,
			maxchars: 5,
			getAction: 'apiZip'
		}, opts || {});
		
		this.inp = $(inp);
		this.hidden = $(hidden);
		this.postal = $(postal);
		
		this.initDom().initListeners();
		return this;
	},
	
	/**
	 * Initialize dom objects
	 * 
	 * @return {Object}
	 */
	initDom: function() {
		
		this.available = new Element('ul', { id: 'available_merchants' }).hide();
		this.inp.up().insert(this.available);

		this.inp.value = '';
		this.hidden.value = '';
		this.postal.value = '';
		
		this.hidden.writeAttribute({ readonly: true }).setStyle({ cursor: 'default', border: 'none' });
		this.postal.writeAttribute({ readonly: true }).setStyle({ cursor: 'default', border: 'none' });
		
		return this;
	},
	
	/**
	 * Initialize Event Listeners
	 */
	initListeners: function() {
		
		// If we already have a value, set the default
		
		this.inp.observe('keyup', this.keyupListener.bind(this));
		this.available.observe('click', this.clickListener.bind(this));
		return this;
	},
	
	/**
	 * Change listener for all needed objects
	 * @param {Object} e
	 */
	keyupListener: function(e) {

		this.hidden.writeAttribute({ readonly: false });
		this.hidden.value = '';
		this.hidden.writeAttribute({ readonly: true });

		this.postal.writeAttribute({ readonly: false });
		this.postal.value = '';
		this.postal.writeAttribute({ readonly: true });

		this.cleanUpMerchants();

		var elm = this.inp;
		var value = elm.getValue();
		this.zip = value;

		if(
			(value.length >= this.opts.minchars && value.length <= this.opts.maxchars) &&
			!isNaN(value)
		) {
			
			this.getMerchants(value);
		}
	},

	/**
	 * Handle clicks for available merchants
	 * @param {Object} e
	 */
	clickListener: function(e) {
		
		var clicked = Event.findElement(e, 'li');
		var active_id = this.getMerchantId(clicked) 

		this.hidden.writeAttribute({ readonly: false });
		this.hidden.value = active_id;
		this.hidden.writeAttribute({ readonly: true });

		var postaldata = clicked.down('span.formcontent');

		// Write merchant data to visible field
		this.postal.writeAttribute({ readonly: false });
		this.postal.value = postaldata.innerHTML;
		this.postal.writeAttribute({ readonly: true });

		
		this.cleanUpMerchants();
	},
	
	/**
	 * Send a ajax request to the proxy to get the merchants
	 * @param {String} val
	 * @return this
	 */
	getMerchants: function(val) {
		
		var req = new Ajax.Request(this.opts.url, {
			method: this.opts.method,
			parameters: {
				action: this.opts.getAction,
				zip: val
			},
			onCreate: function(){
				
				this.inp.addClassName('searching');
				this.inp.writeAttribute({ readonly: true });
			}.bind(this),
			onSuccess: function(transport) {
				
				this.available.update('');
				this.inp.removeClassName('searching');
				var response = transport.responseText.evalJSON();
				this.response = response;
				
				response.each(function(merchant) {
					
					this.buildMerchantHtml(merchant);
				}, this);
				
				this.available.show();
				this.inp.writeAttribute({ readonly: false });
			}.bind(this)
		});
	},

	/**
	 * Build a merchant from a json string
	 * @param {Object} merchant
	 */
	buildMerchantHtml: function(merchant) {

		var contents = '<table class="merchant"><tbody><tr>';
		contents += '<td class="merchant-name"><strong>' + merchant.haendler_name + '</strong></td>';
		
		contents += '<td class="merchant-icon">';
		
		// Add the merchant logo if he
		// is not a regular merchant
		if(merchant.haendler_kategorie != 0) {
			
			contents += '<img src="http://www.held.de/files/merchant_' + merchant.haendler_kategorie + '.jpg" alt="" />';
		}
		contents += '</td>';
		
		// Get available sortiments
		contents += '<td class="merchant-sortiments">';
		var sortiment = merchant.r_haendler_sortimente.split('|+|');
		sortiment.each(function(s) {
			
			contents += '<img src="http://www.held.de/files/sortiment_' + s + '.jpg" alt="" />';
		}, this);
		contents += '</td>';

		contents += '<td style="display: none;"><span class="formcontent">' + merchant.haendler_name + "\n" + merchant.haendler_strasse + "\n" + merchant.haendler_plz + ' ' + merchant.haendler_stadt + '</span></td>';
		contents += '</tr></tbody></table>';

		/*var contents = '<strong>' + merchant.haendler_name + '</strong>';
		
		// Add the merchant logo if he
		// is not a regular merchant
		if(merchant.haendler_kategorie != 0) {
			
			contents += '<img src="http://www.held.de/files/merchant_' + merchant.haendler_kategorie + '.jpg" alt="" />';
		}
		
		contents += '<br />' +  ' (' + merchant.haendler_strasse + ', ' + merchant.haendler_plz + ' ' + merchant.haendler_stadt + ')';
		contents += '<span class="formcontent" style="display: none;">' + merchant.haendler_name + "\n" + merchant.haendler_strasse + "\n" + merchant.haendler_plz + ' ' + merchant.haendler_stadt + '</span>';*/
		var me = new Element('li', { id: 'merchant_' + merchant.haendler_nummer, 'className': this.opts.merchant_class }).update(contents);
		this.available.insert(me);
	},
	
	/**
	 * Clean up the merchants container
	 */
	cleanUpMerchants: function() { this.available.update('').hide(); },
	
	/**
	 * Get the merchant id from an element
	 * @param {Object} elm
	 * @return {String}
	 */
	getMerchantId: function(elm) { return elm.id.replace('merchant_', ''); }
});

/**
 * Adds a simple form submit observer (Submits the form if one value is changed)
 * @param {Object} f
 */
var Clicksports_Checkout_Observer = Class.create({

	/**
	 * @constructor
	 * @param {Object} f
	 */
	initialize: function(f) {
		
		if(!(this.f = $(f))) return false;
		this.f.select('input').each(function(inp) {
			
			inp.observe('change', function(e) { this.f.submit(); }.bind(this));
		}, this);
	}
});

/**************************** CONFIGURABLE PRODUCT **************************/
/**
 * This is a needed override for using the Product.config of default magento
 * in a different way. The original code class is located in varien/product.js
 */
var ClicksportsOptionChooser = Class.create();
ClicksportsOptionChooser.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.activeOptions = null;

        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=true;
            }
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;
            childSettings.push(this.settings[i]);
        }
    },

	/**
	 * Get parameters from url
	 * This code was moved from ClicksportsOptionChooser::initialize()
	 * so we can call our custom event handler when whe have any
	 * separators set (#ta2752)
	 * 
	 * @see ClicksportsColorChooser::initialize()
	 */
	getParamsFromUrl: function() {

        // 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));
			
			return true;
        } else return false;
	},

    configure: function(event){
        var element = Event.element(event);
        this.configureElement(element);
		
		// Because IE sets listeners in reverse order, we need to use a custom event here.
		// @see ClicksportsColorChooser::changeListner()
		element.fire('clicksports:colorchooser');
    },

    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);
            }
        }
        else {
            this.resetChildren(element);
        }
        this.reloadPrice();
    },

    reloadOptionLabels: function(element){
        var selectedPrice;
        if(element.options[element.selectedIndex].config){
            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) {
            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);
                    element.options[index].config = options[i];
                    index++;
                }
            }
			
			// Edit by CLICKSPORTS: Add default option
			var myIndex = this.settings.indexOf(element);
			if(myIndex !== this.settings.length && i == 1) {

				element.options[i].selected = true;
				var nextElm = this.settings[myIndex+1];

				if(nextElm) {
					this.fillSelect(nextElm);
					nextElm.disabled = false;
				}
			}
        }
    },

    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(){
        var price = 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);
            }
        }

        optionsPrice.changePrice('config', price);
        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].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;
            }
        }
    }
};

/**
 * Create a color chooser from given select fields
 * 
 * @param {Object} scroller Scroller Element
 * @param {Object} config Product configuration
 * @param {Object} carouselInstance Instance of the color carousel
 * 
 * @return ClicksportsColorChooser
 */
var ClicksportsColorChooser = Class.create({
	
	initialize: function(scroller, config, carouselInstance) {

		if(
			!(this.scroller = $(scroller)) ||
			!(this.color = $('attribute80')) ||
			!(this.medium = $('main_image'))
		) return false;

		// If we only have one config option (which is color in this case), we
		// need to set the input button to this field instead the previous one
		var fieldcount = $('attribute80').up('form').select('dd select');
		if(fieldcount.length === 1) this.input = this.color;			
		else if(!(this.input = $('attribute80').up().previous('dd').down('select'))) return false;

		// Set translatable text
		this.choose_text = 'Bitte wählen Sie Ihre Größe!';

		this.configInstance = config;
		this.config = config.config.attributes;
		this.colors = this.config[80].options;
		this.availableProducts = [];

		this.carouselInstance = carouselInstance;
		this.getElements().initListeners();

		// #ta2752: Try to get config parameters from url
		if(this.configInstance.getParamsFromUrl()) this.changeListener(this.input);
				
		return this;
	},
	
	/**
	 * Get configuration elements
	 * @return {Object} ClicksportsColorChooser
	 */
	getElements: function() {
		
		this.lis = this.scroller.select('li');
		return this;
	},
	
	/**
	 * Remove default elements
	 * @return {Object} ClicksportsColorChooser
	 */
	removeElements: function() {
		
		this.scroller.down('ul').select('li').invoke('remove');
		return this;
	},
	
	/**
	 * Start events
	 * @return {Object} ClicksportsColorChooser
	 */
	initListeners: function() {

		this.lis.each(function(li) {
			
			li.down('img').observe('click', this.clickListener.bind(this, li.title)).setStyle({ 'cursor': 'pointer' });

			// Nasty fix to get usage of the urls from title tags
			li.alt = li.title;
			li.title = '';
		}, this);
		this.input.observe('clicksports:colorchooser', function(e) { this.changeListener(Event.element(e)); }.bind(this));
		this.color.observe('change', this.changeColor.bind(this));
		return this;
	},

	/**
	 * Monitor the input for changes
	 */	
	changeListener: function(elm) {

		var opts = [];
		var availableProducts = [];
		var tmp = [];
		this.showscroller = false;
		
		if(elm !== this.input) return;
		
		if(elm.value === '') return;
		
		this.removeElements();

		// Get option values
		this.color.select('option').each(function(o) {

			if(o.value !== '') opts.push(o.value);
		});

		this.colors.each(function(c) {
			
			if(opts.indexOf(c.id) !== -1) {
				
				tmp = availableProducts.concat(c.products);
				availableProducts = tmp;
			}
		});
		
		this.availableProducts = availableProducts.uniq();
		
		this.lis.each(function(li) {

			var cls = li.className.split(' ');
			cls.each(function(c) {
				
				if(this.availableProducts.indexOf(c) !== -1) {
					this.scroller.down('ul').insert(li);
					this.showScroller = true;
					throw $break;;
				}
			}, this);
		}, this);
		
		if(this.showScroller) {
			
			this.scroller.show();
			this.carouselInstance.elements = this.carouselInstance.container.childElements();
			this.carouselInstance.updateSize();
			this.carouselInstance.scrollTo(0);
		} else {
			
			this.scroller.hide();
		}
	},
	
	/**
	 * Reload media image
	 * 
	 * @param {Object} url
	 * @param {Object} e
	 */
	clickListener: function(url, e) {

		var links = [this.medium.up('a'), $('carousel_zoom').down('a')];
		var urls = url.split('|');

		var image = new Image();
		image.src = urls[0];
		
		this.medium.writeAttribute({ 'src': urls[0] });
		links.invoke('writeAttribute', { 'href': urls[1] });
		
		// Try to enable the option
		// Caution: Only reset the dropdown if
		// this is not called by changeColor()
		if(e !== undefined && !this.color.disabled) {

			var elm = Event.element(e);
			var attributeId = elm.id.replace(/[a-z]*/, '');

			this.color.select('option[selected=selected]').invoke('writeAttribute', { selected: false });
			var opt = this.color.down('option[value=' + attributeId + ']');
			if (opt !== undefined) this.color.value = opt.value;
			
			// #ta2576: Reload the price if it is different from the original one
			this.configInstance.reloadPrice();
		} else if(this.color.disabled) {
			
			alert(this.choose_text);
		}
	},
	
	/**
	 * Change color according to the given attribute
	 * 
	 * @param {Object} e
	 */
	changeColor: function(e) {
		
		var val = Event.element(e).value;
		if(val === '') return;
		
		// Get the correct image
		var img = $('cc' + val);
		
		if(img !== null) {

			var parent = img.up('li');
			this.clickListener(parent.alt)
		}
	}
});

/**
 * Quantity check for configurable products per ajax
 * 
 * @param {Object} form
 * @param {Object} container
 * @param {Object} lang
 * @return {boolean}
 */
var ClicksportsQtyCheck = Class.create({
	
	opts: {
		url: '/clicksports_checkout.php',
		classes: { available: 'available', unavailable: 'unavailable' },
		msg: {
			de: {
				prefix: 'Verfügbarkeit: ',
				available: 'sofort lieferbar',
				not_available: 'aktuell nicht lieferbar. Bitte Fragen Sie bei Ihrem Held-Fachhändler nach, ob er diesen Artikel auf Lager hat.'
			},
			en: {
				prefix: 'Verfügbarkeit: ',
				available: 'sofort lieferbar',
				not_available: 'nicht sofort lieferbar'
			}
		}
	},
	
	/**
	 * @constructor 
	 */
	initialize: function(field, container, lang) {
		
		if(
			!(this.container = $(container)) ||
			!(this.elm = $(container).down('span')) ||
			!(this.field = $(field))
		) return false;
		this.lang = lang;
		
		this.available = false;
		
		this.elm.hide();
	},
	
	/**
	 * Get availability for the wanted product
	 * 
	 * @return {Object} ClicksportsQtyCheck
	 */
	checkAvailability: function() {
		
		var product_id = this.field.value;
		new Ajax.Request(this.opts.url, {
			parameters: { pid: product_id },
			asynchronous: false,
			onSuccess: function(transport) {
				
				var ret = transport.responseText;
				var msg = '';
				var cls = '';
				
				if(ret == '0') {
					
					msg = this.opts.msg[this.lang].prefix + this.opts.msg[this.lang].available;
					cls = this.opts.classes.available;
					this.available = true;
				} else {
					
					msg = this.opts.msg[this.lang].prefix + this.opts.msg[this.lang].not_available;
					cls = this.opts.classes.unavailable;
					this.available = false;
				}
				
				this.elm.update(msg).addClassName(cls).show();
			}.bind(this)
		});
		
		return this;
	},
	
	/**
	 * Get the availability
	 * 
	 * @return {Object} boolean
	 */
	getAvailability: function() { return this.checkAvailability().available; }
});

/**
 * Create a slider on startpage
 * 
 * @param {Object} elm Parent element to fill
 * @param {Object} images Images Hash
 */
ClicksportsHomeTeaser = Class.create({
	
	opts: {
		interval: 12,
		imgpath: 'http://www.held.de/files/'
	},
	
	/**
	 * @constructor
	 * @return {Object} ClicksportsHomeTeaser
	 */
	initialize: function(elm, images, url_prefix) {
		
		if(!(this.elm = $(elm))) return false;
		this.images = images;
		this.url_prefix = '/' + url_prefix + '/';
		
		this.initDom().createLis().initScroller().initInterval();
		
		return this;
	},
	
	/**
	 * Initialize DOM
	 * 
	 * @return {Object} ClicksportsHomeTeaser 
	 */
	initDom: function() {
		
		this.imageContainer = new Element('div', { 'className': 'image_container' });
		this.container = new Element('div', { 'className': 'container' });
		this.prevBtn = new Element('div', { 'className': 'previous_button' });
		this.nextBtn = new Element('div', { 'className': 'next_button' });
		this.ul = new Element('ul');
		
		this.elm.insert(this.prevBtn).insert(this.container).insert(this.nextBtn);
		this.container.insert(this.ul);
		this.elm.wrap(this.imageContainer);

		this.imageContainer.observe('mouseover', this.stopInterval.bind(this));
		this.imageContainer.observe('mouseout', this.initInterval.bind(this));

		return this;
	},
	
	/**
	 * Create all lis
	 * 
	 * @return {Object} ClicksportsHomeTeaser
	 */
	createLis: function() {

		var counter = 0;
		this.images.each(function(i) {

			var val = i.value;
			var img = '<img src="' + this.opts.imgpath + val.teaser + '" alt="" />';
			var li = new Element('li').insert(img);
			
			li.observe('click', this.updateTeaser.bind(this, val.big, val.url)).setStyle({ 'cursor': 'pointer' });
			
			this.ul.insert(li);
			
			counter++;

			// Automatically get last image to show first			
			if(counter === this.images.keys().length)
				this.updateTeaser(val.big, val.url);
			
		}, this);

		return this;
	},
	
	/**
	 * Initialize the UI Scroller
	 * 
	 * @return {Object} ClicksportsHomeTeaser
	 */
	initScroller: function() {
		
		this.scroller = new UI.Carousel(this.elm.id, { scrollInc: 1 });
		return this;
	},

	/**
	 * Start the interval
	 * 
	 * @return this
	 */
	initInterval: function() {

		if(this.interval !== undefined) this.stopInterval();
		this.interval = new PeriodicalExecuter(function() { this.showNext(); }.bind(this), this.opts.interval);
		return this;
	},

	/**
	 * Clear the interval
	 * 
	 * @return this
	 */
	stopInterval: function() {

		if(this.interval !== undefined) this.interval.stop();
		return this;
	},

	/**
	 * Show next image
	 * 
	 * @return this
	 */
	showNext: function() {

		var index = this.scroller.currentIndex();
		
		if(index === (this.scroller.elements.length - this.scroller.nbVisible)) {

			if(this.lastIndex === undefined) this.lastIndex = index++;
			else this.lastIndex++;

			if(this.lastIndex === this.scroller.elements.length) {
				
				this.scroller.scroll(1 * this.scroller.elements.length * this.scroller.computeElementSize());
				this.lastIndex = undefined;
			}
		} else this.scroller.scroll(-1 * this.scroller.options.scrollInc * this.scroller.computeElementSize());

		if(this.lastIndex !== undefined) var active = this.images.get(this.lastIndex);
		else var active = this.images.get(index);

		this.updateTeaser(active.big, active.url);

		return this;
	},
	
	/**
	 * Update the teaser image
	 * 
	 * @param {Object} img
	 * @param {Object} url
	 * @return {Object} ClicksportsHomeTeaser 
	 */
	updateTeaser: function(img, url) {
		
		var preload = new Image();
		preload.src = this.opts.imgpath + img;
		var image = new Element('img', { 'src': this.opts.imgpath + img });
		
		if(!this.mainlink) {

			this.mainlink = new Element('a');
			this.imageContainer.insert(this.mainlink);
			if(!Prototype.Browser.IE6) this.imageContainer.insert('<div class="rtl rc"></div><div class="rtr rc"></div><div class="rbl rc"></div><div class="rbr rc"></div>');						
		}
		
		// If we have a full url, use this as href, else use shop internal links
		if(url.startsWith('http') || url.startsWith('https')) var href = url;
		else href = this.url_prefix + url;
		
		this.mainlink.writeAttribute({ 'href': href }).update(image);
		
		return this;
	}
	
});

/**
 * Create an unobstrusive javascript popup for given elements
 * 
 * @param {Object} selector CSS Selector
 * @return {Object} ClicksportsPopup
 */
var ClicksportsPopup = Class.create({

	opts: { width: 500, height: 500 },

	initialize: function(selector) {

		this.elements = $$('a.' + selector);
		if(this.elements.length === 0) return;
		
		this.elements.each(function(l) { l.observe('click', this.clickListener.bind(this)); }, this);
		
		return this;
	},
	
	/**
	 * Watch click events
	 * 
	 * @param {Object} e
	 * @return {Object} ClicksportsPopup
	 */
	clickListener: function(e) {
		
		Event.stop(e);
		var elm = Event.element(e);
		var url = elm.href;
		
		window.open(url, "Popup", 'width=' + this.opts.width + ',height=' + this.opts.height + ',resizable=1');
	}
});

/**
 * Creates a product url configurator for full customized urls according to given values
 * 
 * @param {string} elm Element
 * @param {string} wrapper Element
 * @return {Object} ClicksportsMagentoProductFilterAssistant
 */
var ClicksportsMagentoProductFilterAssistant = Class.create({
	
	initialize: function(elm, wrapper) {
		
		if(
			!(this.elm = $(elm)) ||
			!(this.wrapper = $(wrapper))
		) return this;
		
		this.initListener();
		return this;
	},
	
	/**
	 * Add dom listeners
	 * 
	 * @return {Object} ClicksportsMagentoProductFilterAssistant
	 */
	initListener: function() {
		
		this.elm.observe('click', this.getUrl.bind(this));
		return this;
	},
	
	/**
	 * Get the url from the form
	 * @param {Object} e
	 */
	getUrl: function(e) {
		
		// Dont submit the form
		Event.stop(e);
		
		var url = '';
		var opts = '';

		// Get sku prefix
		var sku = this.wrapper.down('dd').innerHTML;
		sku.trim();

		url = sku;

		this.wrapper.select('select').each(function(s) {
			
			var id = s.id.replace('attribute', '');
			var val = s.value
			
			if(!s.disabled && val.length > 0) {
			
				opts += id + '=' + val + '&';	
			}
		}, this);
		
		if(opts.length !== 0) url += '#' + opts;

		// Print out the result
		var msg = '';
		msg += "Um dieses Produkt im Magento Produktfilter zu verwenden, tragen Sie bitte folgende Zeile in die jeweilige Konfiguration ein:\n\n";
		msg += url;
		msg += "\n\n";
		msg += "Um die Funktion der errechneten Optionen zu testen, verwenden Sie bitte folgende URL:\n\n";
		msg += document.location.protocol + '//' + document.location.hostname + document.location.pathname + '#' + opts;
		alert(msg);
	}
});

/**
 * Dummy Method for magento navigation
 * 
 * @param {Event} e
 * @param {Number} level
 */
function toggleMenu(e, level) {}

