var product_variations = '';
var test = '';

function changeColour(variations, obj){ // console.log('changeColour='+obj.value, obj);
	var image = '';
	var images = [];
	if(obj.value){
		
		var objValue = obj.value;
		var products = product_variations[objValue];
		var c =0;
		var sizes = $('sizes');

		/* reset size drop down */
		$('sizes').options.length = 0;

		/* default selection */
		var option = document.createElement("OPTION");
		option.value = '';
		option.text = 'SELECT';
		if (BrowserDetect.browser == 'Explorer'){
			sizes.options.add(option); 			
		}else {
			sizes.appendChild(option);
		}
		
		/* generate size drop down */
		for (i in products){   
			if (products[i].id && products[i].title){  
				var option = document.createElement("OPTION");
				var text = products[i].title.split('Size=');
				option.value = products[i].id;
				if (products[i].stock<=0){ option.value += '~soldout'; }				
				option.text = text[1];
				if (products[i].stock<=0){ option.text += ' - This product has now sold out'; }	
		
				if (BrowserDetect.browser == 'Explorer'){
					sizes.options.add(option); 			
				}else {
					sizes.appendChild(option);
				}
				if (c==0){
					updateSize(option.value, products[i].rrpPrice, products[i].specialPrice, products[i].onSpecial);
					if (products[i].image){
						image = products[i].image;
						images = products[i].images;
					}
				}else if (!image && products[i].image){
					image = products[i].image;
					images = products[i].images;
				}
				c++;
			}
		}  
		changeProductImage(image,images);	
		
		if ($('sizes').value==''){
			$('qty_addtocart').style.display = 'none';
			$('addCart').style.display = 'none';
		}
		
	}
}


function changeSizeColour(variations, colourObj, sizeObj){  // console.log('changeSizeColour', 'size='+sizeObj.value);
	var image = '';
	var images = [];
	if(colourObj && colourObj.value) { //alert(colourObj.value);
		if (sizeObj.value){
			var objValue = colourObj.value;
			var products = product_variations[objValue];
			for (i in products){ 
				if (products[i].id && products[i].title){  
					if (products[i].id==sizeObj.value && products[i].image){
						image = products[i].image;
						images = products[i].images;
					}
				}
			}
			changeProductImage(image, images);
		}
	}
}



function changeProductImage(image,images){ //console.log('changeProductImage');
	if (Lightbox){
		if (image){
			$('imgPL').src = '/cms/image.php?f='+image+'&s=300x400&q=90';
			if ($('slimbox_href')){
				$('slimbox_href').href='/cms/image.php?f='+image+'&s=780x500&q=90';
			}
		}
		
		//clear images from previous product
		if (Lightbox.anchors){
			for(i=Lightbox.anchors.length-1; i>0; i--){ 
				Lightbox.anchors.pop();	
			}
		}
		$('imagesContainer').innerHTML = '';
		
		//insert images on currect product
		if (images.length>0){  
			for (i=0; i<images.length;i++){  
				newElement = document.createElement("A");				
				newElement.setAttribute('rel','lightbox[product]');
				newElement.setAttribute('href','cms/image.php?f='+images[i].file+'&s=780x500&q=90');
				newElement.innerHTML='<img src="/cms/image.php?f='+images[i].file+'&s=59x79&q=90" id="imgPL" border="0" alt="'+images[i].title+'"/>';
				
				Lightbox.anchors.push(newElement);
//				newElement.injectInside($('imagesContainer'));   //CAUSING PROB IN IE
				newElement.onclick = Lightbox.click.pass(newElement, Lightbox);
				$('imagesContainer').appendChild(newElement);
			}
		}
	}
//	console.log(Lightbox.anchors.length);
}

function updateSize(id, rrpPrice, specialPrice, onSpecial){   //console.log('updateSize','id=',id);
	if (id){
		id = id.toString();
		var soldout = id.split('~');
		
		if (soldout[1] && soldout[1]=='soldout'){
			id = soldout[0];	
			$('qty_addtocart').style.display = 'none';
			$('addCart').style.display = 'none';
		}else {
			if ($('qty_addtocart')) { $('qty_addtocart').style.display = 'block'; }
			if ($('addCart')) { $('addCart').style.display = 'block'; }
		}
		
		if (id && document.shoppingFrm.id){  
			document.shoppingFrm.id.value = id;	
		}
		/*update price*/
		if (rrpPrice){
			if (onSpecial>0){
				if ($('price')){
					$('price').innerHTML = '<strike>'+rrpPrice+' ea. </strike>  <span class="special">'+specialPrice+' ea. </span>'; 
				}
			}else {
				$('price').innerHTML = rrpPrice+' ea.';	
			}
		}else {  
			if ($('colour') && product_variations[$('colour').value]){
				var temp = product_variations[$('colour').value]; 
				var c =0;
				for (i in temp){
					if (temp[i].id && temp[i].id==id){ 
						if (temp[i].rrpPrice){
							rrpPrice = temp[i].rrpPrice;
							if (temp[i].onSpecial>0){
								specialPrice = temp[i].specialPrice;
								$('price').innerHTML='<strike>'+rrpPrice+' ea. </strike>  <span class="special">'+specialPrice+' ea. </span>';
							}else {
								$('price').innerHTML=rrpPrice+' ea.';	
							}
						}
					}
				}
			}
		}
	}else {
		$('qty_addtocart').style.display = 'none';
		$('addCart').style.display = 'none';
	}

}

function checkQtyKeyStroke(obj,e){
	//detect type of key stroke
	if (e && e.which){
		characterCode = e.which;	
	}else {
		characterCode = e.keyCode;	
	}  
	switch (characterCode){
		case '8':    	//backspace
		case '9':		//tab
		case '37':		//arrow left
		case '39':		//arrow right
		case '46':		//delete
			return false;
			break;
		default:
			if (characterCode<48 || characterCode>57){
				return false;	
			}
	}
	return true;
}

function checkQtyWithStock(obj){	 console.log('checkQtyWithStock');
	var productstock = 0;
	$('errorMsgProd').innerHTML='';
	
	if(obj.value && obj.value>0){
		if ($('product_id').value){
			var id = $('product_id').value;
			
			for(i in product_variations){
				if (product_variations[i]){
					var products = product_variations[i];
					for(c in products){
						if (products[c].id && products[c].id==id){
							productstock = products[c].stock;
						}	
					}
				}
			}
			if (productstock && obj.value>productstock){
				$('errorMsgProd').innerHTML='Sorry, the quantity you have selected is not available. <br>Please adjust your order quantity.';
				obj.value = 1;
				//obj.value = productstock;
			}	
		}
		$('addCart').style.display='block';
	}else {		
		$('errorMsgProd').innerHTML='Please enter the quantity of your order'; 
		$('addCart').style.display='none';
	}
}


/* VIP FORM */
function removeAChild(id){
	if ($('numberofchildren').value>0){
		$('numberofchildren').value--;
		if ($('numberofchildren').value>=10){
			$('addChildBt').style.display = 'none';
		}else 	$('addChildBt').style.display = 'block';
	}

	var classObj = 'child_'+id

	$(classObj).style.display = "none";
	$(classObj).remove();
}

/**
 * Used on the Send to Friend form
 */
function addFriend() {
	var names = '';
	var emails = '';
	var friends = parseInt($('numberoffriends').value);
	for(i = 0; i < friends; i++) {
		names += '<input type="text" id="friend_name_'+i+'" class="text'+(i == 0 ? ' required':'')+'" name="friend_names[]" value="'+$("friend_name_"+i).value+'" tabindex="'+(((i+1)*2)-1)+'" />';
		emails += '<input type="text" id="friend_email_'+i+'" class="text'+(i == 0 ? ' required':'')+' validate-email" name="friend_emails[]" value="'+$("friend_email_"+i).value+'" tabindex="'+(((i+1)*2))+'" />';
	}
	names += '<input type="text" id="friend_name_'+i+'" class="text'+(i == 0 ? ' required':'')+'" name="friend_names[]" value="" tabindex="'+(((i+1)*2)-1)+'" />';
	emails += '<input type="text" id="friend_email_'+i+'" class="text'+(i == 0 ? ' required':'')+' validate-email" name="friend_emails[]" value="" tabindex="'+(((i+1)*2))+'" />';
	$('friend_names').innerHTML = names;
	$('friend_emails').innerHTML = emails;
	$('numberoffriends').value = friends + 1;
}

function addChild(){
	var child_1 = '<div id="child_1">'+
                '<h4 class="formElement">Child 1  &nbsp;<a href="javascript:void(0);" onclick="removeAChild(1); return false;" class="removechild">(remove)</a></h4>'+
               '<div class="formElement">'+
                    '<label>Child\'s First Name<span class="star">*</span></label>'+
                    '<input type="text" class="text required" name="child_1_firstname"/>'+
                '</div>'+
                '<div class="formElement">'+
                    '<label>Child\'s Last Name<span class="star">*</span></label>'+
                    '<input type="text" class="text required" name="child_1_lastname"/>'+
                '</div>'+
                '<div class="formElement">'+
                    '<label>Gender<span class="star">*</span></label>'+
                    '<select class="required" name="child_1_gender"/>'+
                    	'<option value="Female">Female</option>'+
                    	'<option value="Male">Male</option>'+
                    '</select>'+
                '</div>'+
               ' <div class="formElement formDOB">'+
                    '<label>Date of Birth<span class="star">*</span></label>'+
                    '<input type="text" class="text dd required" name="child_1_dd" maxlength="2" /><b>-</b>'+
                    '<input type="text" class="text mm required" name="child_1_mm" maxlength="2" /><b>-</b>'+
                    '<input type="text" class="text yy required" name="child_1_yy" maxlength="4" />'+
                    '(dd-mm-yyyy)'+
                '</div>';
				
	var innerhtml = '';
	$('numberofchildren').value ++;
	if ($('numberofchildren').value>=10){
		$('addChildBt').style.display = 'none';
	}else 	$('addChildBt').style.display = 'block';

	var newChild = document.createElement('DIV');
	if (child_1 && $('numberofchildren').value<=10){
		var innerhtmls = child_1.split('1');  
		for(var i=0; i<innerhtmls.length; i++){ 
			if (i>0) { innerhtml += $('numberofchildren').value;  }
			innerhtml += innerhtmls[i];
		}
		newChild.innerHTML = innerhtml;	
	}
	$('children').innerHTML += newChild.innerHTML;
	//newChild.inject($('children'));   //js error on IE6
}

function showStates(obj){
	if (obj.value && 
		(obj.value=="Australia" || obj.value=="New Zealand")){ 
	
		$('statecontainer').innerHTML = '<select name="state" id="state" class="required" onchange="showFavStockist(this,\''+obj.value+'\')"></select>';
	
		if (countryStates && countryStates[obj.value] && countryStates[obj.value].length && countryStates[obj.value].length>0){
			/*
			Use pre-loaded country states			
			*/
			/* Create state list*/
			for(var i=0; i<=countryStates[obj.value].length-1; i++){
				if (countryStates[obj.value][i]){
					createOption(countryStates[obj.value][i], countryStates[obj.value][i], 'state');
					responseValid = true;
				}
			}
			showFavStockist($('state'),obj.value);
			
		}else {
			/*
			Load country states with Ajax Request
			*/	
	
			var request = new Ajax( 
				'custom/updateList.php/?action=states&country='+obj.value,
				{
				method: 'get',
				headers: {'Content Length': 1024},
				evalScript:true, 
				onComplete:function(object){ 
						/* Create suburb list*/
						var response = eval(request.response.text);
						for(i in response){							
							if (response[i].state_code){  
								if ($('state')){ 
									createOption(response[i].state_code, response[i].state_code, 'state');
								}
							}
						}
						showFavStockist($('state'),obj.value);
					}
				}
			).request();
		}
	}else {
		$('statecontainer').innerHTML = '<input type="text" name="state" id="name" class="text required">';
		showFavStockist($('state'),'');
	}
}


function showFavStockist(obj,country){ 
	if (obj && obj.value){ 

		$('1st_favourite_stockist').options.length = 0;
		$('2nd_favourite_stockist').options.length = 0;
		$('3rd_favourite_stockist').options.length = 0;

		$('stockist').style.display = "block";

		var request = new Ajax( 
			'custom/updateList.php/?action=favstockist&country='+country+'&state='+obj.value,
			{
				method: 'get',
				headers: {'Content Length': 1024},
				evalScript:true, 
				onComplete:function(obj){ 
						/* Create suburb list*/
						createOption('None', 'None', '1st_favourite_stockist');
						createOption('None', 'None', '2nd_favourite_stockist');
						createOption('None', 'None', '3rd_favourite_stockist');
						var response = eval(request.response.text);
						for(i in response){
							if (response[i].name && response[i].suburb){  
								createOption(response[i].name+', '+response[i].suburb, response[i].name, '1st_favourite_stockist');
								createOption(response[i].name+', '+response[i].suburb, response[i].name, '2nd_favourite_stockist');
								createOption(response[i].name+', '+response[i].suburb, response[i].name, '3rd_favourite_stockist');
							}
						}
				}
			}
		).request();
	}else {
		$('stockist').style.display = "none";
	}
}



function createOption(text, value, id){
	/*Empty List*/
	/*if (empty==true){
		document.getElementById(id).options.length = 0;
	}*/
	
	var option = document.createElement("OPTION") ;
	option.text = text;
	option.value = value;

	document.getElementById(id).options.add(option);
}

function addGiftWrap(obj){
	if (obj.value){
		$('giftwrap').submit();	
	}
}

function showCheckoutStates(obj,id){
	if (obj.value && 
		(obj.value=="Australia" || obj.value=="New Zealand")){ 	
		
		
		if (countryStates && countryStates[obj.value] && countryStates[obj.value].length && countryStates[obj.value].length>0){
			/*
			Use pre-loaded country states			
			*/
			$(id).innerHTML = '<select name="'+id+'" id="'+id+'_input" class="required"></select>';
			/* Create suburb list*/
			for(var i=0; i<=countryStates[obj.value].length-1; i++){
				if (countryStates[obj.value][i]){
					createOption(countryStates[obj.value][i], countryStates[obj.value][i], id+'_input');
					responseValid = true;
				}
			}
			
			
		}else {
			
			/*
			Load country states with Ajax Request
			*/	
			var responseValid=false;
			var url = 'custom/updateList.php/?action=states&country='+obj.value;
			var request = new Ajax( 
				url,
				{
					method: 'get',
					headers: {'Content Length': 1024},
					evalScript:true, 
					onComplete:function(object){ 
							$(id).innerHTML = '<select name="'+id+'" id="'+id+'_input" class="required"></select>';
							/* Create suburb list*/
							response = eval(request.response.text);
							for(i in response){							
								if (response[i].state_code && $(id+'_input')){  
									createOption(response[i].state_code, response[i].state_code, id+'_input');
									responseValid = true;
								}
							}
					}
				}
			).request();
		}
		
		/* if no valid value on pre-loaded or Ajax request response */
		if (!responseValid){
			$(id).innerHTML = '<input type="text" name="'+id+'" id="'+id+'_input" class="text required">';
		}
		
		
	}else {
		$(id).innerHTML = '<input type="text" name="'+id+'" id="'+id+'_input" class="text required">';
	}
	
	return true;
}

function selectMenuHeight(){
	var smHeight = 0;
	var selectMenus = [$('selectContainer1'), $('mustHave'), $('buyOnline')];

	if ($('selectContainer1') && $('mustHave') && $('buyOnline')){
		for (var i=0; i<selectMenus.length; i++){
			if (smHeight<selectMenus[i].offsetHeight){
				smHeight = selectMenus[i].offsetHeight;
			}	
		}
		for (var i=0; i<selectMenus.length; i++){
			selectMenus[i].style.height = smHeight+'px';
		}
	}
}


function searchFilterValidation(obj){
	var defaultKeyword = 'enter keyword';
	if(obj.keyword.value==defaultKeyword && obj.gender.value=='' && obj.age.value=='' && obj.productsrc.value==''){ 
		alert('Please enter search filter'); 
		return false; 
	}else if(obj.keyword.value==defaultKeyword){
		obj.keyword.value='';
		return true;
	}	
	
}
