var $CE = function(tagName, attributes, styles) {
      var el = document.createElement(tagName);
      if (attributes)
            $H(attributes).each(function(pair){
                  eval("el." + pair.key + "='" + pair.value + "'");
            });
      if (styles)
            $H(styles).each(function(pair){
                  el.style[pair.key] = pair.value;
            });

      return $(el);
};

Element.addMethods({
	clearChildren: function(element) {
		element = $(element);
		$A(element.childNodes).each(function(e){
			  e.parentNode.removeChild(e);
		});
		return element;
	},
	append: function(element, tagName, attributes, styles) {
		element = $(element);
		var newEl = $CE(tagName, attributes, styles);
		element.appendChild(newEl);
		return newEl;
	},
	appendText: function(element, text){
		element = $(element);
		var t = document.createTextNode(text);
		element.appendChild(t);
		return element;
	  }
});

var webShop = Class.create({

	colors: new Array(),
	sizes: new Array(),
	images: new Array(),
	
	product_id: false,
	theme_id: false,
	
	docColor: false,
	docSize: false,
	docPrice: false,
	docQuant: false,
	docImage: false,
	loopImage: false,
	
	initialize: function(id, theme_id) {
		this.product_id = id;
		this.theme_id = theme_id;
    },
    
    initHtmlObj: function () {
		this.docColor = document.getElementById('productColor');
		this.docSize = document.getElementById('productSize');
		this.docPrice = document.getElementById('productPrice');
		this.docQuant = document.getElementById('productQuant');
		this.docImage = document.getElementById('vImage');
		this.loopImage = document.getElementById('lImage');
    },
    
	addColorCombi: function(color, size, price) {
		if(typeof(this.colors[color]) == 'undefined') {
			this.colors[color] = new Array();
		}
		var key = this.colors[color].length;
		this.colors[color][key] = new Array();
		this.colors[color][key][0] = size;
		this.colors[color][key][1] = price;
	},
	
	addSizeCombi: function(size, color, price) {
		if(typeof(this.sizes[size]) == 'undefined') {
			this.sizes[size] = new Array();
		}
		var key = this.sizes[size].length;
		this.sizes[size][key] = new Array();;
		this.sizes[size][key][0] = color;
		this.sizes[size][key][1] = price;
	},
	
	addImageCombi: function(color, image, thumb) {
		if(typeof(this.images[color]) == 'undefined') {
			this.images[color] = new Array();
		}
		var key = this.images[color].length;
		this.images[color][key] = new Array();
		this.images[color][key][0] = image;
		this.images[color][key][1] = thumb;
	},
	
	rewriteSizes: function(nsize) {
		if(typeof(this.sizes[nsize]) != 'undefined') {
			this.initHtmlObj();
			//this.formFillSelectBox(this.docColor, this.sizes[nsize]);
			
			this.formSetPrice(this.docPrice, this.sizes[nsize], this.docColor.value, this.docQuant.value);
		}
	},
	
	rewriteColors: function(ncolor) {
		if(typeof(this.colors[ncolor]) != 'undefined') {
			this.initHtmlObj();
			
			currentSize = this.docSize.value;
			this.formFillSelectBox(this.docSize, this.colors[ncolor]);
			
			var opt = this.colors[ncolor].find( function(csize) {
				return (csize[0] == currentSize);
			});
			if(typeof(opt) != 'undefined') {
				this.docSize.value = currentSize;
			}

			this.formSetPrice(this.docPrice, this.colors[ncolor], this.docSize.value, this.docQuant.value);
			
			if(typeof(this.images[ncolor]) != 'undefined') {
				this.rewriteImages(ncolor);
			}
		}
	},
	
	rewritePrice: function() {
		
		var quantity = parseInt(this.docQuant.value);
		if(isNaN(this.docQuant.value) || quantity <= 0) {
			quantity = 1;
		}
		this.docQuant.value = quantity;
		
		this.initHtmlObj();
		if(typeof(this.colors[this.docColor.value]) != 'undefined') {
			this.formSetPrice(this.docPrice, this.colors[this.docColor.value], this.docSize.value, quantity);
		}
	},	

	rewriteImages: function(color) {
		var loopBox = this.loopImage;
		
		$(loopBox).update('');

		if(this.images[color].length > 1) {
			this.images[color].each( function(img, key){
				$(loopBox).append('A',{href:'javascript:ws.rewriteImage(' + key + ');'}).append('IMG',{src:img[1], alt:''});
			});
		}
		this.rewriteImage(0);
	},
	
	rewriteImage: function(key) {
		this.initHtmlObj();
		
		var color = this.docColor.value;
		this.docImage.src = this.images[color][key][0];
	},
	
	formSetPrice: function(elm, data, combiMatch, quantity) {
		data.each( function(combi, k) {
			if(combi[0] == combiMatch) {
				var f = combi[1] * quantity
				var D = Math.pow(10, 2);
				f = Math.round(f * D) / D;
				elm.innerHTML = f + ' &euro;';

				return combi[1];
			}
		});
		
		return 0;
	},
	
	formFillSelectBox: function(elm, data)
	{
        for(var k, k=elm.options.length-1; k >= 0; k--) {
        	elm.remove(k);
        }

        data.each( function(combi, k) {
		    var option = document.createElement('option');
		    option.appendChild(document.createTextNode(combi[0]));
		    option.setAttribute('value', combi[0] );
		    elm.appendChild(option);
        });
	},
	
	addToBasket: function() {
		this.initHtmlObj();
		
		var q = 'mod=shop_addbasket&'
			  + 'color=' + this.docColor.value + '&'
			  + 'size=' + this.docSize.value + '&'
			  + 'quant=' + this.docQuant.value + '&'
			  + 'product_id=' + this.product_id + '&'
			  + 'theme_id=' + this.theme_id;
	    new Ajax.Request( '/index.php',
                { method: 'post', 
	    		    postBody: 'ajax=1&' + q,
	  		        onFailure: requestError,
				    onException: requestError,
 				    onSuccess: requestComplete,
  				    encoding: 'ISO-8859-1',
 				    evalScripts: true
  		      });
		
		return false;
	}
});
function showProgress(tr) {
	if(typeof(tr) == 'undefined' || tr.length == 0) {
		tr = 'shopContent';
	}
	
    var so = new SWFObject('/swf/indicator.swf', 'BgcIndi', '100', '100', '6', '#ffffff');
    so.addParam('quality', 'high');
    so.addParam('wmode', 'transparent');
    so.addParam('scale', 'noscale');
    so.addParam('allowScriptAccess', 'sameDomain');
    so.addParam('swLiveConnect', 'true');
    so.write(tr);
}
function orderInit() {
	rptShipCosts($('countryLocator').value);
}

var webOrderTotal = 0;
function rptShipCosts(c) {
	var q = 'mod=shop_order_shipcosts'
		  + '&country=' + escape(c);
    new Ajax.Request( '/index.php',
          { method: 'post', 
  		    postBody: 'ajax=1&' + q,
	        onFailure: requestError,
		    onException: requestError,
		    onSuccess: shipComplete,
		    encoding: 'ISO-8859-1',
		    evalScripts: true
	      });
}
function shipComplete(xmlObj, reqObj) {
	var m = new Array();
    m = xmlObj.responseText.split('|');
    
    if(typeof(m[1]) == 'undefined' || typeof(m[3]) == 'undefine') {
    	alert('Invalid response');
    	return false;
    }
    
    $('tc').update(m[1] + ' / ' + m[4]);
    $('totalc').update(m[3]);
}

function requestError() {
	alert('failed');
}
function requestComplete(xmlObj, reqObj) {
    
	var m = new Array();
    m = xmlObj.responseText.split('|');
    
    var msg = 'Invalid response';
    var redirect = 1;
    var alertmsg = 1;
    switch(m[0]) {
		case '100':
			msg = 'The product was updated';
			break;
		case '110':
			msg = 'The product was added';
			alertmsg = 0;
			break;
		case '120':
			msg = 'The product could not be placed in the basket';
			break;
		case '130':
			if(m[1] == 0) {
				redirect = 0;
				msg = 'The product could not be placed in the basket because there are no items on stock';
			}
			else {
				msg = 'This stock is limited and there were ' + m[1] + ' product(s) placed in you basket';
			}
			break;
    }
    if(alertmsg == 1) {
    	alert(msg);
    }
    if(redirect == 1) {
    	window.location = '/index.php?mod=shop_showbasket&product_ref=' + escape(ws.product_id) + '&theme_ref=' + escape(ws.theme_id);
    }
}
function hideBox(e)
{
	var elm = Event.element(e);
	var box = elm.id.replace('Ctr', 'Con');
	
	trig = 0;
	if(document.getElementById(box)) {
		if(elm.hasClassName('isExpanded') ) {
			Effect.SlideUp(box, { duration: 0.5 });
			elm.addClassName('isCollapsed');
			elm.removeClassName('isExpanded');
			trig = 1;
		}
		else if(elm.hasClassName('isCollapsed') ) {
			Effect.SlideDown(box, { duration: 0.5 });
			elm.addClassName('isExpanded');
			elm.removeClassName('isCollapsed');
			trig = 2;
		}
	}
	
	if(trig == 1 || trig == 2) {
	    new Ajax.Request( '/index.php',
	            { method: 'get', 
	    	      parameters: 'mod=front_box_update&act=' + trig + '&id=' + elm.id,
				  encoding: 'ISO-8859-1'
			    });
	}
}
function eventwatch() 
{ 
	var ev = new Array('policyCtr', 'faqCtr', 'paymethodCtr', 'shippingCtr');
	ev.each(function(f) {
		if(document.getElementById(f)) {
			Event.observe($(f), 'click', hideBox);
		}
	});
}