
/**
 * This method is just used to verify that the
 * JavaScript is properly included on pages that
 * that it needs to be.
 */
function testJS ()
{
	alert("global.js included");
}

//---------------------------------------------------------------------//


/**
 * Used to validate generic forms client side
 */
function validateForm() {
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.returnValue = (errors == '');
} }


//---------------------------------------------------------------------//


/**
 * Used to open Pop-up windows
 */ 
function openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}

//---------------------------------------------------------------------//

/** 
 *	updateShippingPrice() 
 *  
 *  DESCRIPTION - Takes the value of the selected shipping type updates the cart prices based on the selection.
 *  
 *  PARAMETERS 
 *       fltShippingTotal - selected shipping total
 *
 */
function updateShippingPrice (fltShippingTotal) {


	var ShippingElement = document.getElementById('shippingTotal');
 
	if(fltShippingTotal) {
		ShippingElement.innerHTML = parseFloat(fltShippingTotal).toFixed(2);
	}
	if(document.getElementById('shipping_cost')) {
		document.getElementById('shipping_cost').value = fltShippingTotal;
	}

	updateCurrentTotal();
 }

//---------------------------------------------------------------------//

/** 
 *	calculateShipping() 
 *  
 *  DESCRIPTION - Gets the zipcode element, makes a request, and retreives shipping options.
 *  
 *  PARAMETERS - NONE
 *       
 *  NOTES - 
 *      1) The element id 'zip_code' is required for holding and retrieving the zipcode
 *      2) The element id 'shippingOptions' is required to display the returned shipping options 
 */

function calculateShipping (strZipCode, strCountryCode, tmp) {

	var objShippingTypes = document.getElementById('shippingOptions');
	objShippingTypes.innerHTML = 'Loading...';

	// Verify input
	if (strZipCode.length < 4) {
                if (strCountryCode == "US"){
                    objShippingTypes.innerHTML = '<span class="cartZipError">Please enter a valid US zip code!</span>';
                }else{
                    objShippingTypes.innerHTML = '<span class="cartZipError">Please enter a valid CA zip code!</span>';
                }
		return;
	}

	// Clear Options 	
	var conn = new Ext.data.Connection();

	conn.request({
		url: '/index.php/GetShippingOptions',
		method: 'POST',
		params: {
			"zipcode"      : strZipCode,
			"country_code" : strCountryCode 
		},

		success: function(responseObject) {
			document.getElementById('shippingOptions').innerHTML = responseObject.responseText;
		},
		failure: function() {
			document.getElementById('shippingOptions').innerHTML = 'Failed to retreive shipping options!';
		}
	});

	return;
}

function updateCurrentTotal() {

	var fltSubtotal = parseFloat(document.getElementById('subTotal').innerHTML);
	var fltShipping = parseFloat(document.getElementById('shippingTotal').innerHTML);
	var fltTaxes = parseFloat(document.getElementById('taxes').innerHTML);
	var CurrentGrandTotalElement = document.getElementById('currentGrandTotal');
	var fltGiftCardAmount = 0.00;
	if(document.getElementById('giftCardRedeemAmount') != null) {
		fltGiftCardAmount = parseFloat(document.getElementById('giftCardRedeemAmount').innerHTML);
	}

	fltRunningGrandTotal = fltSubtotal + fltShipping + fltTaxes;
//alert('GiftCard Amount :' + fltGiftCardAmount); 
	if(fltGiftCardAmount < fltRunningGrandTotal) {
		fltRunningGrandTotal -= fltGiftCardAmount;	
//alert('Card less than total :' + fltRunningGrandTotal); 
	}
	else {
		var GiftCardAmountUsedElement = document.getElementById('giftCardAmountUsed');
		GiftCardAmountUsedElement.innerHTML = fltRunningGrandTotal.toFixed(2);
//alert('Card more than total :' + fltRunningGrandTotal); 
		fltRunningGrandTotal = 0;	
	}
	CurrentGrandTotalElement.innerHTML = fltRunningGrandTotal.toFixed(2);
}


// showCombinedWhatsThis() - displays information about Combined SHipping
function showCombinedWhatsThis() {

	var objContainer = document.getElementById('contentContainer');
	objContainer.setAttribute('opacity').value = '90%';
	
}

function showHide(elm, itr) {
    if(document.getElementById(elm + '_'  + itr).style.display == 'block'){
        document.getElementById(elm + '_' + itr).style.display = 'none';
        document.getElementById(elm + '_img_' + itr).src = "/Scripts/Ext/resources/images/default/tree/elbow-plus.gif";
    }
    else {
        document.getElementById(elm + '_' + itr).style.display = 'block';
        document.getElementById(elm + '_img_' + itr).src = "/Scripts/Ext/resources/images/default/tree/elbow-minus.gif";
    }
}


/***********************************
*
* Email Vision Sign Up Form Validation Functions
*
***********************************/
function isEmail(emailAddress){
emailAddressValue=emailAddress.value.toLowerCase();
var countryTLDs=/^(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$/;
var gTLDs=/^(aero|biz|cat|com|coop|edu|gov|info|int|mil|museum|name|net|org|jobs)$/;
var basicAddress=/^(.+)@(.+)$/;
var specialChars='\\(\\)><@,;:\\\\\\\"\\.\\[\\]';
var validChars='\[^\\s'+specialChars+'\]';
var validCharset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\'-_.';
var quotedUser='(\"[^\"]*\")';
var atom=validChars+'+';
var word='('+atom+'|'+quotedUser+')';
var validUser=new RegExp('^'+word+'(\.'+word+')*$');
var symDomain=new RegExp('^'+atom+'(\.'+atom+')*$');
var matchArray=emailAddressValue.match(basicAddress);
if(emailAddress.value==''||emailAddress==null){
return true;
}
if(matchArray==null){
alert('The Email address doesn\'t seem to be correct,\nplease check syntax.');
emailAddress.focus();
return false;
}else{
var user=matchArray[1];
var domain=matchArray[2];
for(i=0;i<user.length;i++){
if(validCharset.indexOf(user.charAt(i))==-1){
alert('The Email address contains invalid characters,\nplease check the username.');
emailAddress.focus();
return false;
}
}
for(i=0;i<domain.length;i++){
if(validCharset.indexOf(domain.charAt(i))==-1){
alert('The Email address contains invalid characters,\nplease check the domain.');
emailAddress.focus();
return false;
}
}
if(user.match(validUser)==null){
alert('The Email address doesn\'t seem to be correct,\nplease check the username.');
emailAddress.focus();
return false;
}
var atomPat=new RegExp('^'+atom+'$');
var domArr=domain.split('.');
var len=domArr.length;
for(i=0;i<len;i++){
if(domArr[i].search(atomPat)==-1){
alert('The Email address doesn\'t seem to be correct,\nplease check the domain name.');
emailAddress.focus();
return false;
}
}
if((domArr[domArr.length-1].length==2)&&(domArr[domArr.length-1].search(countryTLDs)==-1)){
alert('The Email address doesn\'t seem to be correct,\nplease check domain suffix.');
emailAddress.focus();
return false;
}
if((domArr[domArr.length-1].length>2)&&(domArr[domArr.length-1].search(gTLDs)==-1)){
alert('The Email address doesn\'t seem to be correct,\nplease check domain suffix.');
emailAddress.focus();
return false;
}
if((domArr[domArr.length-1].length<2)||(domArr[domArr.length-1].length>6)){
alert('The Email address doesn\'t seem to be correct,\nplease check domain suffix.');
emailAddress.focus();
return false;
}
if(len<2){
alert('The Email address doesn\'t seem to be correct,\nplease check missing hostname.');
emailAddress.focus();
return false;
}
}
return true;
}
String.prototype.trim = function() { return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");	}
function mandatoryText(input,fieldName){
if(input.value.trim()==''||input==null){
alert('Please enter your '+fieldName+'.');
input.focus();
return false;
} else {
return true;
}
}
function validForm(){
if(!mandatoryText(document.getElementById('EMAIL_FIELD'), 'Email')) return;
if(!isEmail(document.getElementById('EMAIL_FIELD'))) return;
if(!mandatoryText(document.getElementById('FIRSTNAME_FIELD'), 'First Name')) return;
if(!mandatoryText(document.getElementById('LASTNAME_FIELD'), 'Last Name')) return;
document.getElementById('emvForm').submit();
}

