/**
* 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.
*
* @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.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.GConfig = Class.create();
Product.GConfig.prototype = {
	initialize: function(config){
		this.config     = config;
		this.taxConfig  = this.config.taxConfig;
		/* GWE MOD */
		this.settings   = $$('.super-attribute-select'+this.config.productId);
		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=true;
			}
			$(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) {
		this.toggleRequired(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();
		//      Calculator.updatePrice();
	},

	toggleRequired : function (element) {
		// this.config.attributes is array of attributes
		//if(attributeId && this.config.attributes[attributeId]) {

		// disable required state if qty = 0
		var qty = $('qty'+this.config.productId);
		var attributeId = element.id.replace(/[a-z]*/, '');
		var prod_id   = this.config.productId;
		for (var i in this.config.attributes){
			var attr = this.config.attributes[i];
			if (attr.id!=attributeId){
				var attrelem = $('attribute'+attr.id);
				if (qty.value=="" || qty.value==0) {
					attrelem.removeClassName('required-entry');
					attrelem.removeClassName('validation-failed');
					attrelem.addClassName('xrequired-entry');
				}
				else {
					attrelem.removeClassName('xrequired-entry');
					attrelem.addClassName('required-entry');
				}

				var adviceElem = $('advice-required-entry-attribute'+attr.id);
				if (adviceElem){
					adviceElem.remove();
				}
			}
		};


	},
	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);
		var choosetext = this.config.attributes[attributeId].label;
		//element.options[0] = new Option(this.config.chooseText, '');
		element.options[0] = new Option(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++;
				}
			}
		}
	},

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

		}
	}
}


GweCookies= {};
GweCookies.set = function(name, value){
	value = value.toJSON();
	var argv = arguments;
	var argc = arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : '/';
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
};

GweCookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
		return GweCookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
		break;
	}
	return null;
};

GweCookies.getCookieVal = function(offset){
	var endstr = document.cookie.indexOf(";", offset);
	if(endstr == -1){
		endstr = document.cookie.length;
	}
	value = unescape(document.cookie.substring(offset, endstr));
	return value.evalJSON();
};
var swatchskus = new Array();
var swatchdescriptions = new Array();

function requestswatch(sku,name ){
	// Find swatch module
	var swatchdiv = $("swatches");
	if (!swatchdiv) return;
	swatchdiv.style.display="block";

	var swatchrows = $("swatchrows");

	var rows = $A(swatchrows.getElementsByTagName('div'));
	if (document.getElementById(sku)){
		alert("You have already selected this swatch");
		return;
	}
	if (rows.length>=5){
		alert("You can only request 5 swatch samples please remove one or more and try again");
		return false;
	}
	var style=rows.length%2;
	var html = '<div class="row'+style+'">xxx</div>';

	var html = '<div class="row'+style+'" id="'+sku+'"> \
	    	<img src="/store/media/catalog/product/fabrics/'+sku+'.jpg" alt="'+name+'"/><span>'+name+'</span><a href="#remove" onclick="return removeSwatch(\''+sku+'\');"><img src="/store/skin/frontend/gwe_theme/default/images/media/removeswatch.gif" alt="Remove Swatch" class="removeswatch" /></a> \
	    </div>'; 

	swatchrows.insert({bottom:html});

	// now add to the cookies
	swatchskus = GweCookies.get("swatchskus");
	swatchdescriptions = GweCookies.get("swatchdescriptions");
	if (swatchskus && swatchdescriptions){

	}
	else {
		swatchskus=new Array();
		swatchdescriptions =new Array();
	}
	var addin=true;
	for (var s=0;s<swatchskus.length;s++){
		if (swatchskus[s]==sku){
			addin=false;
			break;
		}
	}
	if (addin){
		swatchskus.push(sku);
		swatchdescriptions.push(name);
	}

	GweCookies.set("swatchskus",swatchskus);
	GweCookies.set("swatchdescriptions",swatchdescriptions);
	
	return false;
}

function removeSwatch(sku)
{
	var swatch = $(sku);
	if (!swatch) return;
	swatch.remove();
	
	for (var s=0;s<swatchskus.length;s++){
		if (swatchskus[s]==sku){
			swatchdescriptions = swatchdescriptions.without(swatchdescriptions[s]);
			swatchskus = swatchskus.without(sku);			
			GweCookies.set("swatchskus",swatchskus);
			GweCookies.set("swatchdescriptions",swatchdescriptions);
			break;
		}
	}	
	
	// ensure the classes on the rows are correct
	var swatchrows = $("swatchrows");
	var rows = $A(swatchrows.getElementsByTagName('div'));
	for (var r=0;r<rows.length;r++){
		var oldclass = "row"+(r+1)%2;
		var newclass = "row"+r%2;
		$(rows[r]).removeClassName(oldclass);
		$(rows[r]).addClassName(newclass);
	}
	
	if (swatchskus.length==0){
		var swatchdiv = $("swatches");
		if (!swatchdiv) return;
		swatchdiv.style.display="none";		
		
		deliverswatch = false;
		document.getElementById("swatchrequest").style.display="none";
		
	}

	
}

function setupSwatches(){
	swatchskus = GweCookies.get("swatchskus");
	swatchdescriptions = GweCookies.get("swatchdescriptions");
	if (swatchskus && swatchdescriptions){
		for (var s=0;s<swatchskus.length;s++){
			requestswatch(swatchskus[s],swatchdescriptions[s]);
		}
	}
}

function clearSwatches(){
	for (var s=swatchskus.length-1;s>=0;s--){
		removeSwatch(swatchskus[s]);
	}
}

var deliverswatch = false;
function deliverSwatches(){
	if (deliverswatch){
		var name = document.getElementById("yourname");
		var address = document.getElementById("address");
		if (name.value==""){
			alert("please enter your name");
			return false;
		}
		if (address.value==""){
			alert("please enter your address");
			return false;
		}
		var requestObject = new Object();
		requestObject.name = name.value;
		requestObject.address = address.value;
		requestObject.sku =swatchskus;

		var json = Object.toJSON(requestObject);
		//?start_debug=1&debug_host=127.0.0.1&debug_port=10000&debug_stop=1
		new Ajax.Request('/gwutils/swatches.php', {
		  method:'get',
		  onSuccess: function(transport){
		     var json = transport.responseText.evalJSON();
		     if (json.result==1){
		     	alert("Your request has been sent.  Thank you.");
		     	clearSwatches();
		     }
		     else {
		     	alert("Sending your request failed - please try again later");
		     }
		   },
		  onFailure: function(transport){
		  	 alert("I failed");
		     var json = transport.responseText.evalJSON();
		   },
		   parameters : "json="+json
		})
		
	}
	else {
		document.getElementById("swatchrequest").style.display="block";
		deliverswatch=true;
	}
	return false;
}

var moreinfovisible = false;
function togglemoreinfo(){
	if (moreinfovisible){
		moreinfovisible=false;
		document.getElementById('moreinfo').style.display='none';
		imgsrc = document.getElementById('moreinfoimg').src;
		document.getElementById('moreinfoimg').src=imgsrc.replace('lessinfo','moreinfo');
	}
	else {
		moreinfovisible=true;
		document.getElementById('moreinfo').style.display='block';
		imgsrc = document.getElementById('moreinfoimg').src;
		document.getElementById('moreinfoimg').src=imgsrc.replace('moreinfo','lessinfo');
	}
}