/**** Gift box feature javascript ****/
function removeChildren(nodevar){
	// delete all nodes
	if(!nodevar)
		return false;
	while(nodevar.firstChild) { 
      nodevar.removeChild(nodevar.firstChild);
	}
}

//Unused
function showhideClassElements(varClass,dispvar){
	//varClass - class name for elements involved
	//dispvar - true, display | false, invisible
	//show or hide elements based on class name
	var elementsArr = getElementsByClassName(varClass);

	if(elementsArr && elementsArr.length > 0){
   		for(var i=0; i<elementsArr.length; i++){
			if(dispvar)
				elementsArr[i].style.display = "block";
			else
				elementsArr[i].style.display = "none";
		}
	}
	else
		return false;
}

function removeClassElements(varClass){
// remove all elements of class varClass
	var remArr = getElementsByClassName("packrowRem");
	var i;
	if(remArr && remArr.length > 0){
	    for(i=0; i<remArr.length; i++)
			remArr[i].parentNode.removeChild(remArr[i]);
	}
	// number of elements removed
	return i + 1;
}

function enabledisableClassElements(varClass,dispvar){
	//varClass - class name for elements involved
	//dispvar - true, display | false, invisible
	//show or hide elements based on class name
	var elementsArr = getElementsByClassName(varClass);

//	alert("class arr len: " + elementsArr.length);
	if(elementsArr && elementsArr.length > 0){
   		for(var i=0; i<elementsArr.length; i++){
			if(dispvar){
				elementsArr[i].disabled = false;
			}	
			else{
				elementsArr[i].disabled = true;
			}	
		}
	}
	else
		return false;
}


//Given string replace all \n line feeds in inTxt to repString
function replaceNewline(inTxt, repString){
	if(inTxt && repString){
		return inTxt.replace( new RegExp("\\n", "g"), repString );	
	}
	//return empty if failed
	return "";
}



function giftboxFields(checkparam, packagingDropdown, noteTextarea){
	//checkparam - true,enabled | false, disabled
	//packagingDropdown - packaging dropdown object
	//noteTextarea - personal note text area object
	//enable or disable giftbox fields depending on checkparam value

	
	if(checkparam){
		packagingDropdown.disabled = false;
		document.getElementById("giftboxImageID").style.display = "block";
	}
	// reset fields to default values if unchecked
	else{
		packagingDropdown.selectedIndex = 0;
		packagingDropdown.disabled = true;
		noteTextarea.value = "";
		noteTextarea.parentNode.style.display = "none";
//		noteTextarea.disabled = true;
		document.getElementById("giftboxImageID").style.display = "none";
	}
	
	//if wrapping is "pack with order" enable text area
	if(packagingDropdown.selectedIndex == 1){
		if(noteTextarea)

			// td parent only
     		//noteTextarea.style.display = "block";
			noteTextarea.parentNode.style.display = "block";
			noteTextarea.disabled = false;
	}
	else{
		if(noteTextarea){
			//td parent only
			//noteTextarea.style.display = "none";
			noteTextarea.parentNode.style.display = "none";
			noteTextarea.disabled = true;
			noteTextarea.value = "";
		}
	}
	
}

function setWrappingInstructions(gboxframe_txt, personalNote){
	//set value of gboxframe_txt
	//gboxframe - gboxframe Instructions text area object
	//personalNote - Personal note string to be set on  gboxframe Instructions text area
	if(gboxframe_txt){
		gboxframe_txt.value = personalNote;
		return true;
	}
	else{
		return false;
	}
}


function remakePackaging(){
//remake packaging portion if Gift Box with "Pack order in gift box" wrapping is already in cart

	var pcolumnTd = document.getElementById("productColumnID");
	
	var productAnchors;
	
	if(pcolumnTd)
	    productAnchors = pcolumnTd.getElementsByTagName('a');
	else
		return false;
	
	var pdescriptionDivsArr = getElementsByClassName("productitemcell", "div", document.getElementById("pdescriptionColumnID") );
	var printData;
	
	
	//call remakePackaging on gift voucher update, discount code update, and shipping change event
	
	
	//shipping country change
	if(document.getElementById("shippingCountry")){
		var shipcountryfunc = String(document.getElementById("shippingCountry").onchange );
		shipcountryfunc = shipcountryfunc.substring(shipcountryfunc.indexOf('{') + 1, shipcountryfunc.length - 1);
		if( shipcountryfunc.match(/SetShippingCountry/) )
			document.getElementById("shippingCountry").onchange = function(){ eval(shipcountryfunc); remakePackaging(); };
	}

	//shipping options change
	if(document.getElementById("ShippingOptions") ){
		var shipfunc = String(document.getElementById("ShippingOptions").onchange );
		shipfunc = shipfunc.substring( shipfunc.indexOf('{') + 1, shipfunc.length - 1);
		//only replace onchange function if it is not yet modified
		if( shipfunc.match(/UpdateShipping/) )
			document.getElementById("ShippingOptions").onchange = function(){ eval(shipfunc); remakePackaging(); };
	}
	
	//shipping state change
	if(document.getElementById("shippingState") ){
		var shipstatefunc = String(document.getElementById("shippingState").onchange );
		shipstatefunc = shipstatefunc.substring( shipstatefunc.indexOf('{') + 1, shipstatefunc.length - 1);
		//only replace onchange function if it is not yet modified
		if( shipstatefunc.match(/ApplyTaxRate/) )
			document.getElementById("shippingState").onchange = function(){ eval(shipstatefunc); remakePackaging(); };
	}
	
	
	var discountfunc = String(document.getElementById("DiscountCode").onchange );
	discountfunc = discountfunc.substring(discountfunc.indexOf('{') + 1, discountfunc.length - 1);
	discountfunc = discountfunc.substring(0, discountfunc.indexOf(');') + 1);
	//only replace onchange function if it is not yet modified
	if(discountfunc.match(/ApplyDiscountCode/) )
		document.getElementById("DiscountCode").onchange = function(){ eval(discountfunc); remakePackaging(); return false;};
	
	var voucherfunc = String(document.getElementById("GiftVoucher").onchange );
	voucherfunc = voucherfunc.substring(voucherfunc.indexOf('{') + 1, voucherfunc.length - 1);
	voucherfunc = voucherfunc.substring(0, voucherfunc.indexOf(');') + 1);
	//only replace onchange function if it is not yet modified
	if(voucherfunc.match(/ApplyGiftVoucher/) )
		document.getElementById("GiftVoucher").onchange = function(){ eval(voucherfunc); remakePackaging(); return false;};	

	
	
	
	if(productAnchors && productAnchors.length > 0 && productAnchors.length == pdescriptionDivsArr.length ){
	
		for(var i=0; i<productAnchors.length; i++){
			
			//if(productAnchors[i].innerHTML.match(/Gift Box-Packed/) ){
			if(productAnchors[i].innerHTML.match(/Gift Box-Pack/) ){			
				printData = pdescriptionDivsArr[i].innerHTML;
				// container
				var tdContainer = document.getElementById("modtdPackageID");
				//wrapping text
				var divwrapping = document.createElement("div");
				divwrapping.style.textAlign = "left";
				divwrapping.style.fontWeight = "bold";
				divwrapping.innerHTML = "<strong>Pack order in gift box</strong>";
				//personal note text
				var divnote = document.createElement("div");
				divnote.style.textAlign = "left";
				divnote.style.marginTop = "5px";
				divnote.innerHTML = "<strong>Personal Note:</strong><br />" + printData;

				//remove packaging fields
				removeClassElements("packrowRem");
				removeChildren(tdContainer);
					
				//replace with newly created text
				tdContainer.appendChild(divwrapping);
				tdContainer.appendChild(divnote);
					
				//remake done and break loop
				return true;

			
			}
		
		}
	}
	//no giftbox found
	
	//update tax rates
     //  updateTax(document.getElementById('shippingCountry'));

	return false;
}







function triggerAddGiftbox(disablelink, wrapSelectObj, instructionTextarea){
	//disablelink - update button beside giftbox fields
	//wrapSelectObj - wrapping dropdown field object
	//instructionTextarea - personal note text area
	

//	var isSet;
	
	
	//check if objects are loaded
	if(!(disablelink && wrapSelectObj && instructionTextarea) ){
		alert("Page loading, please reload shopping cart if problem persists.triggerAddGiftbox!(disablelink && wrapSelectObj && instructionTextarea) ");
		return false;
	}
	
	
	// no wrapping option selected
	if(wrapSelectObj && wrapSelectObj.selectedIndex == 0){
		alert("Please select a packaging option.");	
	}
	// pack in gift box option selected
	else if(wrapSelectObj && wrapSelectObj.selectedIndex == 1){
		if(window.frames.giftboxpack_frame && window.frames.giftboxpack_frame.AddToCart){
			
			// set personal note in iframe
			if( setWrappingInstructions(
				  window.frames.giftboxpack_frame.document.getElementById('catProdInstructions_1040718'),replaceNewline(instructionTextarea.value, " <br />"))){
				// add gift box to cart
				//window.frames.giftboxpack_frame.AddToCart(42185,981261,'',4,false);
				window.frames.giftboxpack_frame.AddToCart(42185,1040718,'',4,false);
				//window.frames.giftboxpack_frame.document.getElementById("addcartContainer").childNode[0]
				
				disablelink.onclick = "return false;";
				//refresh cart
				getCart();
				setTimeout("remakePackaging()", 2000);
				updateTax(document.getElementById("shippingCountry"));
			}
			else{
				alert("Page loading, please reload shopping cart if problem persists.triggerAddGiftbox( setWrappingInstructions(window.frames.giftboxpack_frame.document.getElementById('catProdInstructions_1040718'), instructionTextarea.value) )");
				return false;
			}
		}
		else{
			alert("Page loading, please reload shopping cart if problem persists.triggerAddGiftbox(window.frames.giftboxpack_frame && window.frames.giftboxpack_frame.AddToCart)");
			return false;
		}
	}
	// sent flat with order selected
	else if(wrapSelectObj && wrapSelectObj.selectedIndex == 2){
		if(window.frames.giftbox_frame && window.frames.giftbox_frame.AddToCart){
			// add gift box to cart
			//window.frames.giftbox_frame.AddToCart(42185,981260,'',4,false);
			window.frames.giftbox_frame.AddToCart(42185,1040717,'',4,false);	
			disablelink.onclick = "return false;";
			//refresh cart
			getCart();
			setTimeout("remakePackaging()", 2000);
			updateTax(document.getElementById("shippingCountry"));
		}
		else{
			alert("Page loading, please reload shopping cart if problem persists.triggerAddGiftbox (wrapSelectObj && wrapSelectObj.selectedIndex == 2)");
			return false;
		}
	}
	
	return true;
	
	/*
	if (window.frames.giftbox_frame && window.frames.giftbox_frame.AddToCart) {
		//set wrapping on giftbox_frame
		isSet = setWrappingInstructions(document.getElementById("wrapSelectObjID").selectedIndex, document.getElementById("instructionSourceID").value);
		window.frames.giftbox_frame.AddToCart(42185,956676,'',4,false);
		
		//if giftbox added successfully
		if(isSet){
			disablelink.onclick = "return false;";
			//setTimeout("window.location.reload()", 1000);
			//setTimeout(" getCart(document.getElementById('catCartDetails') )", 1000);
			getCart(document.getElementById('catCartDetails') );
			setTimeout("remakePackaging()", 2000);
		}
		return false;
	}
	else{
		alert("Page loading, please reload shopping cart if problem persists.");
		return false;
	}
	*/
	
	
	
}





//******USING BC ajax FUNCTIONS********
//called on product remove or product quantity change, refresh function
function UpdateProductExtras(){
	remakePackaging();
}


function getCart(){
	//divContainer - div to place all cart contents
	
	RefreshCart();
	
	
	
	/*
    var c = readCookie("CartID");

    var sCart = CMS.OrderRetrievev2.ServerSideReDrawShoppingCart(c).value;
    //sCart hold the shopping cart output.
	
	//check if element exists
	if(divContainer)
		divContainer.innerHTML = sCart;
		
	*/

}


function updateTax(countryObj){


if(countryObj){
		if(countryObj.options[countryObj.selectedIndex].value == "AU"){
			//australia, use NSW tax code, Java_Shopping.js
			//ApplyTaxRate(8560,459760,1,1,0);
			
			//call state dropdown onchange: ApplyTaxRate()
			if(document.getElementById("shippingState") && document.getElementById("shippingState").onchange)
				document.getElementById("shippingState").onchange();
			
			
		}
		else{
			// null tax code
			//ApplyTaxRate(-1,459760,1,1,0);	
			
			//call destination country dropdown onchange
			if(countryObj.onchange)


				countryObj.onchange();
				
		}
	}



//alert(document.getElementById("shippingState").onchange);
}

/**** Gift box feature javascript END ****/

// if textarea value too long...trim it!

function limitTextarea(field, maxlimit) {
if (field.value.length > maxlimit) 
    field.value = field.value.substring(0, maxlimit);
return false;
}