function test(element){
alert($(element).name);

}

function init(val) {
  if(val==1) {
   	 // expand('bhdOrder');  
	//alert($('itemReq').value);
	showReq($('itemReq').value);	
   	//show('total');
   	validate_js(); 	 
	}
	else if (val==2) { }
	
	CB();
}  


 
function CB() {
 
 		var mem_fee = 0 ;
	    var subtotal = 0;
		var qtyStr = "qty-";
		var chkStr = "chk-";
		var subtotalStr = "sub-";
		
		for (i=0; i<= lastItem; i++){
			// if the id value exists (there are blank spots in the arrays)  
			
				if( $( 'chk-' + i)   ) {
				
					subtotal += calcSubTotal(qtyStr.concat(i),  
										chkStr.concat(i), 
										subtotalStr.concat(i), i)	;
										
										
										
				}// else the the item doesn't exist so no extra needs to be added on
		}//end for loop
		    //DISPLAY SUBTOTAL at bottom of form
   	   $("lblSUBTotal").innerHTML = Format$(subtotal);
   	    // orderTotal = subtotal; //save the order total
    	
    
    
    	//update mebership fee only on Member's ordering
    	if ($('order_type').value == 'M'){	mem_fee = parseFloat(updateMembershipSelection());
    		subtotal += mem_fee;
		    $('lblMembership').innerHTML = Format$(mem_fee); 
       }

   	    //DISPLAY SUBTOTAL
   	    //
   	    //
   	    
 
	if(itemCount >0) {
			subtotal = pF(subtotal);
			
		//set postage amount based on total 
			if(subtotal	> 50){	
 			var postage	= pF(POSTAGE_REGISTERED);	
			}else{ var postage =pF(POSTAGE_HANDLING_FEE); }
		
		//display the postage on the page
			$("lblPH").innerHTML = Format$(postage); 

		//add postage onto subtotal	for final total					
			subtotal += postage;		
		}
		else {
		      $("lblPH").innerHTML = Format$(pF("00.00"));

		}
   	    
   	    //calc post gst                     
		var gst = pF(subtotal) * GST_PERCENTAGE;  
 
		$("lblGST").innerHTML = CurrencyFormatted(gst);
	
		
		
		if(CALCULATE_GST==true) { 
		   $("lblTotal").innerHTML = Format$(pF(subtotal));  
		}
		else {  
		   $("lblTotal").innerHTML = Format$(pF(subtotal) + pF(gst)); 
		}
        
        if(itemCount >0) {
        	$("ph").checked= true;
        }
        else {
            $("ph").checked= false;
        }
        
              
       //reset global variables
		 itemCount = 0;
		//alert(braceletordered);
		braceletordered=false;
		
		applyDiscount(); //will only be applied if relevant 
		
}// end CB 


// find the quantity of items ordered and the price per item needs to be added multiply together and return a subtotal for that imem
function calcSubTotal(qtyField,chkBox,subLabel, item) { 
    var _q = parseFloat($(qtyField).value);; //turn the quantity into a number
    var unitVal = ($(chkBox).checked)?pF($(chkBox).value):0;; // is it checked
    var result = _q * unitVal;  
    if(isNaN(result)) { 
        alert('NaN, Error'); return 0 ; 
    }else { //place the result on the page right in the appropriate label position
        $(subLabel).innerHTML = Format$(result); 
        if(pF(_q) > 0) { 
            itemCount = ($(chkBox).checked)? pF(itemCount)+pF(_q):itemCount; 
			
			
			
			
	/*-------- used for the $20 necklace special finding out if a bracelet is ordered */
			if( item >= 90 && item <= 101){	braceletordered = true;	}
			
			/* if it is a necklace - nwb special*/
			if( (item == 115 || item == 116 || item == 123 || item == 124 || item == 119 || item == 120)&& braceletordered == true){
				
				result = _q* 20;
				 $(subLabel).innerHTML = result; 
			
			
			}
     /*--------------- end nwb special */
			
        } 
        return result;
     }//end else
}//end function



function User_Data_Validator(theForm) {
	
/* test that for any inputs that have options, that they are filled in */	

	for (i = 0; i < grouplist.length; i++) {
	//alert("i" +i +" val: "+  grouplist[i][4]);		
		if(grouplist[i][5]){ // 5 is position of options
			for (j = grouplist[i][2]; j <= grouplist[i][3]; j++) {
				
				for (k = 1; k <= 3; k++) {
					//alert('opt'+k+'-'+j);
					if ($('opt' + k + '-' + j) != undefined) { // option exists
						opt = $('opt' + k + '-' + j);
					
/*					
						if ($('qty-'+j).value > 0) {
					
			//opt.tagName == 'INPUT' &&				
	//	alert(opt.type);		
	 if ((opt.tagName == 'INPUT') && (opt.type == 'text' || opt.type == 'hidden') && (opt.value.length == 0)) {
								alert('Please choose chain options.');
								document.location = '#'+'anchor' + j;
								opt.focus();
								return false;
							}
						}//end if qty > 0
		*/
					}//end if option exists
				}// end loop k
			}//end loop j
		}//end if options
	}//end loop i
	
	
	 
	return true;
}




/* show requested - 
 - takes the input from the url as the requested item (now a hidden form input,
 - expands the relebant section it exists in
- ticks the item */

function showReq(itm){
	//grouplist is set in settings.js.php
var item = parseInt(itm);	
	//alert(item);
	
		
		if($("chk-" + item)){ $("chk-" + item).checked = true;			
							updateQ("qty-"+item, $("chk-"+item));
			}
				//alert(grouplist[i][5] ); 
			
		//show options if exist	
		if(opt = $('options-' + item)) opt.style.display = 'block';			
			
					
}// end show Req



function expand(section){
	
	show(section.concat('-'));
	show(section.concat('Order'));
	hide(section.concat('+'));

}

function collapse(section){
// !!! check that no items iare in this section !!! think...	
	show(section.concat('+'));
	hide(section.concat('Order'));
	hide(section.concat('-'));

}

function showselected(num, i, choice){
	//alert('selected-' + i);
	
	$('selected'+num+'-'+i).innerHTML = choice;
	show('selected'+ num+ '-'+i);
	$('opt'+num+'-'+i).value = choice;		
	show('opt'+ num+'-'+i +'-choose');	
	
}

function showHideOptions(i){
	var checkbox = $('chk-'+i);
	if(checkbox.checked){
		if(opt = $('options-' + i)) opt.style.display = 'block';	
	}else{
		if(opt = $('options-' + i)) opt.style.display = 'none';	
	}// end else
		
}// end show hide options
	
	
	// checks that the input is all characters and that it is the length of constraint c
function checkText(i, min, max){
	
 var len = parseInt($(i).value.length);
 var maxlen = parseInt(max);
 var minlen = parseInt(min);	
	
 	
 	if(len > maxlen || len < minlen ){
 		if(maxlen == minlen ){
 			alert("Please Enter exactly "+ maxlen + " letter(s).");
 		}else{
			alert("Please enter between "+ minlen + " and " + maxlen + " letters."); 		
 		}	
 		
 	}//end if len
}//end check text


function updateQ(qtyField, itemCheckbox){

	var _q = parseFloat($(qtyField).value);; //turn the quantity into a number
	if(itemCheckbox.checked){

 	if(_q == 0){
 		$(qtyField).value = 1;
 	}//end if item checked
 	}else{ //the item is not checked
 			$(qtyField).value = 0;

	}//else

}//updateQ

function fixQty(item){
	var qfield = $('qty-'+ item);
	var input = $('opt1-'+ item);	
	var str =	input.value;
	var ok = "1234567890-=!@#$%^&*()_+qwertyuiopasdfghjklzxcvbnm?QWERTYUIOPASDFGHJKLZXCVBNM";	
	var q = 0;
	for( i = 0; i< str.length; i++){
		for( j = 0; j< ok.length; j++){
			if(str.charAt(i) == str.charAt(j) ){
			 	q ++; break;
			 }
		}//end for j
	}// end for i
	
	qfield.value = q;

}// end qtyfix 

/*
checks the valididty of the quantity text inpt
then will untick or tick the checkbox associated depending if the qty entered is 0 or not.
*/
function checkTick  (qtyField, itemCheckbox)
{
 
	var _q = parseFloat($(qtyField).value); //turn the quantity into a number
		
	//data validation on quantity _q 
	if((_q=='undefined') || (_q==undefined) || (_q < 0)) 
	 { 
        alert('Not a valid input.\n Please try again.'); 
		$(qtyField).value = '0'; //set the real value to 0
		
	 };
    if(isNaN(_q)) 
    { 
        alert('The Quantity You enetered is not Numeric.\r\nPlease Try again');  
        $(qtyField).value = '0';
       
	};
		
	
		if($(qtyField).value == 0){	$(itemCheckbox).checked = false;}		// untich the checkbox
		else { 		$(itemCheckbox).checked = true;} //make sure checkbox is ticked
}//end function check tick


// applies a discount to the order total display if the discount code is correct
/*

*discountCodeStart  
*discountCodeEnd 
 *discountValue  
  *discountMinPurchase  
  
referenced from                inc/settings.js.php

*/

function validateVoucher(ordertotal, discountCode){

	 if( (discountCode >= discountCodeStart  && discountCode <= discountCodeEnd) ||  discountCode  == discountCodeUnique  ){
	 //within range
				if(ordertotal >= discountMinPurchase){
				//total greater than min purchase amount -  ok for disount
				return 'success';
				}else{
					return 'Order value must be $' + discountMinPurchase + ' or more to receive discount.';
				}
				
	}else{ return 'Invalid discount code :('; }

}// end validateVoucher

function applyDiscount(){

	var discountCode = $('txtVoucher').value;
	
	var subtotal = pF( document.getElementById('lblSUBTotal').innerHTML );
	var membership = pF( document.getElementById('lblMembership').innerHTML );
	var postage = pF( document.getElementById('lblPH').innerHTML );
	var orderTotal = subtotal + membership + postage;
	
	
	if( !discountCode){
		
		$('lblVoucher').innerHTML =  Format$(0);  
		$("lblTotal").innerHTML	= Format$(pF(orderTotal)); 
		
		$("lblVoucherFeedback").innerHTML = "";

		return; //do nothing if no discount code is entered
	}
	
	
	
	
	
	var voucherFeedback = validateVoucher( orderTotal, discountCode);

		 //validate that the code is within range
	if( voucherFeedback == 'success' ){	

		//set the display of discount amount
		$('lblVoucher').innerHTML =  Format$(discountValue);  
		
		//apply the discount to the order total
		orderTotal -= discountValue;
		//display the new order total
			$("lblTotal").innerHTML	= Format$(pF(orderTotal)); 
		
		$("lblVoucherFeedback").innerHTML = ""; 
		
	}else{
			//failed discount code
		$("lblVoucherFeedback").innerHTML = voucherFeedback 	;
		
		//set the display of discount amount
		$('lblVoucher').innerHTML =  Format$(0);  ;
		
		$("lblTotal").innerHTML	= Format$(pF(orderTotal)); 
		
		}
		
		

 
 //discountMinPurchase  

	



}
             