/////////////////////////////////////////////////////////
//
// basket.js  - JS required by product pages and basket
//
/////////////////////////////////////////////////////////
//
// copyright 2008 web-engineer - www.web-engineer.co.uk
// last edit by C.Lawson 24.11.2008
//
/////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////
//
//
var maxgridln = 5;
var ctrlDown = false;
/*
document.onkeydown = function(k) { if (k.ctrlKey) ctrlDown = true};
if(document.captureEvents && Event.KEYUP ) { document.captureEvents( Event.KEYUP ); }
document.onkeyup = function(k) { if (!k.ctrlKey) ctrlDown = false};
*/
function drawsizegrid(dims){
	var grid = new Array();
	var i=0;
	var j=dims;
	var k=0;
	var label;
	var warn;
	var oldwarn;
	var warn2=0;
	var oldwarn2=0;
	document.write('<table cellspacing="0" cellpadding="0" border="0">');
	// iterate through the descriptors and if they are too long, stick them on the end
	// initialize grid
	for(i=dims; i<sizegrid.length; i++){
		label = sizegrid[i -dims];
		sizegrid[i]=sizegrid[i].replace(/([.]*)[#]*$/, "$1");
		grid[i-dims]=(label+'#'+sizegrid[i]).split('#');
	}

	// fix grid element lengths
	for(i=0; i<j; i++){
		if(grid[i].length > maxgridln+2){ // + 2 due to the label being attached
			//		if(gridIndex > maxgridln+2){ // + 2 due to the label being attached
			var namearray = Array(grid[i][0]);
			grid[j]=namearray.concat(grid[i].slice(maxgridln+1,grid[i].length)); // move the rest to the end!
			//grid.push('');
			grid[i]=grid[i].slice(0,maxgridln+1); // slice the former
			j=j+1;	// update the size of the grid
			warn2=1;
		} else warn2=0;

		oldwarn2=warn2;
	}
	// there may be some rows to shunt
	var rc = 0
	var move = Array();
	if(grid.length % 2 == 1){
		var maxlen = grid[0].length;
		for(i=1; i<grid.length; i++){
			if(grid[i].length>=maxlen){
				maxlen = grid[i].length;
			} else {

				for(j=0;j<grid.length;j++){
					if(grid[i][0]==grid[j][0]){
						rc++;
					}
				}
				if(rc==1){
					move[move.length] = grid[i];
					grid[i]='';
				}
			}
		}
	}
	var moddims = dims;
	var skipped = 0;
	if(move.length>0){
		for(i=0;i<move.length;i++){
			grid[grid.length]=move[i];
			moddims = dims-1;
		}
	}
	// Draw the grid
	for(i=0; i<grid.length; i++){
		if(grid[i]!=''){
			document.write('<tr><td class="small">'+grid[i][0]+'</td>');
			for(j=1; j<grid[i].length; j++){
				document.write('<td class="small" align="center">&nbsp;'+grid[i][j]+'</td>');
			}
			document.write('</tr>');
			if(i>0 && grid[i][0]!=grid[i-1][0]){
				if((i-skipped)%moddims==(moddims-1)){
					document.write('<tr><td colspan="'+(dims+1)+'"><img src="/images/spacer.gif" width="1" height="5"/></td></tr>');
				}
			}
		} else {
			skipped++;
		}
	}
	document.write('</table>');
}
var Basket = Class.create({
	basketButtonHTML: '<a class="mainlevel_mmenu" title="Basket" href="/basket.php"><img src="/images/a_cart.gif" alt="your order..." width="50" height="34" border="0"/></a>',
	initialize: function(){
		this.shown = false;
		this.canAdd = false;
		this.view = "product_add";
		//var src_c = $('src_colours'); //htmlselect elemenet
		//this.selectColoursSrc = src_c ? src_c.innerHTML : '';
		//if(src_c) src_c.innerHTML = '';
		this.formTarget = $('product_info');
		this.initHTML = this.target ? this.target.innerHTML : '';
		this.data = null; //sku data for the selected product
		this.items = []; //array container for the items on the order
		this.selectColours = null;
		
		if($('sel_qty')){
			$('sel_qty').value = '';
			if($('sel_colourway').selectedIndex>0){
				this.doSelectColour();
			}
			$('sel_continue').observe('click',this.progressOrder.bind(this));
			//
			this.basketButton = $('div_basket');
			if(this.basketButton){
				this.basketButton.innerHTML = this.basketButtonHTML;
			}
			this.validate();
		}
	},
	doSelectColour: function(){
		if(!this.selectColours) this.selectColours = $('sel_colourway');
		var n = this.selectColours.selectedIndex;
		this.selectedColour = this.selectColours.options[n].value; // eg. RED
		if(n>0){
			this.loadSizes();
		}
		this.validate();
	},
	loadSizes: function(){
		if(this.data==null){
			new Ajax.Request('/includes/get_order_cwy.php', {method: 'get', parameters: {p: product_instance}, onSuccess: this.dataLoaded.bind(this)});
		} else {
			this.processColour();
		}
	},
	dataLoaded:function(transport){
		this.data = transport.responseXML;
		this.processColour();
	},
	processColour:function(){
		var nodes = this.data.getElementsByTagName("sku"); // array of sku colour options
		var sz = $('sel_size'); // size select form ctrl
		var domxml,e,optionVal,domsizes;
		// empty the size list
		for (i = sz.length - 1; i>=0; i--) {
			sz.remove(i);
		}
		// got the selected sku from the size xml
		nodes = this.data.getElementsByTagName("sku");
		for(i=0; i<nodes.length; i++){
			if(nodes[i].getAttribute('colour')==this.selectedColour){
				domxml = nodes[i];
				break;
			}
		}
		if(domxml){
			try {
				sz.add(new Option('- select -',''), null); // standards compliant; doesn't work in IE
			} catch(ex) {
				sz.add(new Option('- select -','')); // IE only
			}
			domsizes = domxml.getElementsByTagName("size");
			for(i=0; i<domsizes.length; i++){
				optionVal = domsizes[i].getAttribute('name');
				try {
					sz.add(new Option(optionVal,optionVal), null); // standards compliant; doesn't work in IE
				}catch(ex) {
					sz.add(new Option(optionVal,optionVal)); // IE only
				}
			}
			$('sel_size_container').show();
		}else{
			$('sel_size_container').hide();
		}
	},
	sizeChange: function(){
		this.validate();
		$('sel_qty').focus();
	},
	validate: function(){
		if((parseInt($F('sel_qty'))>0)&&($('sel_colourway').selectedIndex>0)&&($('sel_size').selectedIndex>0)){
			$('sel_continue').src = '/images/btns_grey/add_to_order.png';
			$('sel_continue').setStyle({"cursor":"hand"});
			this.canAdd = true;
		} else {
			$('sel_continue').src = '/images/btns_grey/disabled/add_to_order.png';
			//$('sel_continue').observe('click',null);
			$('sel_continue').setStyle({"cursor":"normal"});
			this.canAdd = false;
		}
		
		/*
		#sel_container .styleGood{
			background-color:#FFFFFF;
			color:#333333;
			border:#CCCCCC 1px solid;
		}
		#sel_container .styleBad{
			background-color:#FF3333;
			color:#FFFFFF;
			border:#CCCCCC 1px solid;
		}
		*/
		
		if(!this.canAdd){
			$('sel_colourway').className = $('sel_colourway').selectedIndex>0 ? 'styleGood' : 'styleBad';
			$('sel_size').className = $('sel_size').selectedIndex>0 ? 'styleGood' : 'styleBad';
			$('sel_qty').className = parseInt($('sel_qty'))>0 ? 'styleGood' : 'styleBad';
		}else{
			$('sel_colourway').className = 'styleGood';
			$('sel_qty').className = 'styleGood';
			$('sel_size').className = 'styleGood';
		}
		if($('sel_colourway').selectedIndex>0){
			$('sel_size_container').show();
			if($('sel_size').selectedIndex>0){
				$('sel_qty_container').show();
			}else{
				$('sel_qty_container').hide();
			}
		}else{
			$('sel_size_container').hide();
			$('sel_qty_container').hide();
		}

	},
	progressOrder: function(){
		//
		if(this.canAdd){
			switch(this.view){
				case "product_add":
				//add the row to the order and show the basket
				new Ajax.Request('/includes/update_order.php?sku=NEW_'+escape(product_code)+'_'+escape($F('sel_colourway'))+'_'+escape($F('sel_size'))+'_'+$F('sel_qty'),{method: 'get', onSuccess: this.orderUpdated.bind(this)})
				break;
				default:
				console.warn('unhandled view '+this.view);
				break;
			}
		}
	},
	orderUpdated: function(){
		//show basket
		window.location.href = '/basket.php';
	}
});