/*
commonscript.js 
This file has common javascript functions that can be used elsewhere.
When needed, this file should be referenced in a <head> section, as
    <script language="JavaScript" src="/js/commonscript.js"></script>
*/
        
		 
/*
add a text node to the specified element.  use instead of
 ...innerHTML = <value>
*/
function setInnerHTML ( container, newText )
    {
    while ( container.hasChildNodes() )
        {
        container.removeChild ( container.lastChild );
        }
    container.appendChild ( document.createTextNode(newText) );
    }

/*
change cursor to hourglass (wait).
*/         
function doHourglass()
    {
	window.document.body.style.cursor = 'wait';
    }

/*
change cursor to the default.
*/         
function doDefaultCursor()
    {
    window.document.body.style.cursor = 'default';
    }
    
/*
disable all input fields on the page.
*/    
function disableForm()
    {
    if ( document.all )
	    {
    	var i;
        for ( i = 0; i < document.all.length; i++ )
     	    {
         	if ( document.all[i].tagName == 'INPUT' )
                {
            	document.all[i].disabled = true;
	            }
	        }
	    }
    doHourglass();
    }
    
/*
disable all input fields on the page.
*/    
function enableForm()
    {
    if ( document.all )
        {
        var i;
        for ( i = 0; i < document.all.length; i++ )
            {
            if ( document.all[i].tagName == 'INPUT' )
                {
                document.all[i].disabled = false;
                }
            }
        }
    doDefaultCursor();
    }   
    
        
function trim(strText)  {  	// this will get rid of leading spaces  
    while (strText.substring(0,1) == ' ')
  		strText = strText.substring(1, strText.length);     
	while (strText.substring(strText.length-1,strText.length) == ' ') //this will get rid of trailing spaces
		strText = strText.substring(0, strText.length-1);     
 	return strText;
}
			 
			 
function removePunctuation( field ){
	var str = field.value;
	var trimstr = trim(str);
	var str2 = trimstr.replace(/\s*,|;|:|-|_|\\|\/|\*|\(|\)|\||\[|\{|}|]\s*/g, ' ');
	var str3 = str2.replace(/'|`|"|!|%|\^|\$|~|\?/g, '');
	field.value = str3.replace(/\s+/g, ' ');
}


function checkControlChars( field ){
    var trimstr = trim(field.value);
    field.value = trimstr;
    if(trimstr.match(/[\x80-\xfe]+/g)) {
        alert("Please remove special characters from field value: " + trimstr);
        field.focus();
        return false;
    }
    return true;
}			

function standardizeAttention( field ){
    toUpper(field);
    checkControlChars( field );
} 

function standardizeCity( field ){
    toUpper(field);
    checkControlChars( field );
}    
			
function standardizePOBOX(str){
	//change to PO BOX
	if(str.match(/\s*POST OFFICE BOX\s*/g)){
	//" POST OFFICE BOX "
	//not doing a search on POST OFFICE 
	//because can be a road name as there is one in DB
	str = str.replace(/\s*POST OFFICE BOX\s*/g, ' PO BOX ');
	}
	else if(str.match(/P\s*\.*\s*O\s*\.*\s*BOX\s*/g)){
		//"P. O. BOX"
		str = str.replace(/P\s*\.*\s*O\s*\.*\s*BOX/g, ' PO BOX ');
	}
	else if (str.match(/\s*P\s*\.*\s*O\s*\.*\s*B\.*\s*BOX\s*/g)){
		//"P. O. B. BOX"
		str = str.replace(/P\s*\.*\s*O\s*\.*\s*B\.*\s*BOX/g, ' PO BOX ');	
	}
	else if (str.match(/\s+P\s*\.*\s*O\s*\.*\s*B\.*\s+/g)){
		//" P. O. B. "
		str = str.replace(/P\s*\.*\s*O\s*\.*\s*B\.*/g, ' PO BOX ');
	}
	else if (str.match(/^P\s*\.*\s*O\s*\.*\s*B\.*\s+/g)){
		//"starts with P. O. B."
		str = str.replace(/P\s*\.*\s*O\s*\.*\s*B\.*/g, 'PO BOX ');
	}
	else if (str.match(/\s+BOX\.*\s+/g)){
		//" BOX. "
		str = str.replace(/BOX\.*/g, ' PO BOX ');
	}
    else if (str.match(/^BOX\.*\s+/g)){
        //" starts with BOX. "
        str = str.replace(/BOX\.*/g, ' PO BOX ');
    }
	else if (str.match(/\s*P\s*\.*\s*O\s*\.*\s*#/g)){
		//"PO#"
		str = str.replace(/\s*P\s*\.*\s*O\s*\.*\s*#/g, ' PO BOX ');
	}
	return str;
}
			
function standardizeAPO(str){
			
	if(str.match(/\s+A\s*\.*\s*P\s*\.*\s*O\s*\.*\s+/g)){
		//" A. P. O. to APO"
		str = str.replace(/\s+A\s*\.*\s*P\s*\.*\s*O\s*\.*\s+/g, ' APO ');
	}
	else if (str.match(/^A\s*P\s*O\s+/g)){
		//"A P O to APO"
		str = str.replace(/A\s*P\s*O\s+/g, 'APO ');
	}
	return str;
}

function standardizeDate(field){
            
    var str = field.value;
    var trimstr = trim(str);
    var date = trimstr.replace(/[^0-9]/g,'');
    if(date.length != 8) {
        alert(field.value + " Please enter date in format: MM/DD/YYYY");
        return(false);
    }
    
    var Month = date.substring(0,2);
    var Day = date.substring(2,4);
    var Year = date.substring(4,8);

    field.value = Month + "/" + Day + "/"+ Year;
}
			
		
function standardizeAddress(field){
    toUpper(field);
	removePunctuation( field );
    checkControlChars( field );
	var str = field.value;
	var trimstr = trim(str);
				
	field.value = standardizePOBOX(trimstr);
	field.value = standardizeAPO(field.value);
	//APO
	trimstr = field.value;

	//change @ to AT
	if(trimstr.match(/\s*@\s*/g)){
		//replace @ with AT
		field.value = trimstr.replace(/\s*@\s*/g, ' AT ');
	}
	var result = field.value;
	field.value = result.replace(/\s+/g, ' ');
	field.value = trim(field.value);
}
			
			
function standardizeCompanyName( field ){
    toUpper(field);
	removePunctuation( field );
    checkControlChars( field );
	var str = field.value;
	var trimstr = trim(str);

	//remove THE
	if (trimstr.substring(0,4) == 'THE '){
		field.value = trimstr.substring(4, trimstr.length); 
	}
	trimstr = field.value;
	if(trimstr.match(/\s+THE\s+/g)){
		//THE in middle of address or company name
		field.value = trimstr.replace(/\s+THE\s+/g, ' ');
	}
				
	trimstr = field.value;
	//change @ to AT
	if(trimstr.match(/\s*@\s*/g)){
		//replace @ with AT
		field.value = trimstr.replace(/\s*@\s*/g, ' AT ');
	}
    
    trimstr = field.value;
    field.value = trimstr.replace(/\.(?!COM\b)|\?/g, '');
	var result = field.value;
	field.value = result.replace(/\s+/g, ' ');
	field.value = trim(field.value);
}

function standardizeUSPhone( field ){
    var str = field.value;
    var trimstr = trim(str);
    var phone = trimstr.replace(/[^0-9]/g,'');
    if(phone.length < 10) {
	    alert(field.value + " is not a valid US phone number");
	    return(false);
    }
    if(phone.length > 10) {
        alert("Please enter 10 digit US phone number.");
        return(false);
    }
    var area = phone.substring(0,3);
    var prefix = phone.substring(3,6);
    var number = phone.substring(6,10);

    field.value = area + "-" + prefix + "-"+ number;
    
}


/**
 *  Convert string to all upper case
 */
function toUpper(object)
    {
    object.value = object.value.toUpperCase();
    }

function validateDate(fld, updatefield) {
        if (!checkDate(fld, updatefield)) {
            // focus if validation fails
            fld.focus();
            fld.select();
            return false;
        }
        return true;
       }
   
function  checkDate(fld, updatefield) {
    var mo, day, yr;
    var entry = fld.value;
    var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
    var valid = (reLong.test(entry)) || (reShort.test(entry));
    if (valid) {
        var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
        var delim1 = entry.indexOf(delimChar);
        var delim2 = entry.lastIndexOf(delimChar);
        mo = parseInt(entry.substring(0, delim1), 10);
        day = parseInt(entry.substring(delim1+1, delim2), 10);
        yr = parseInt(entry.substring(delim2+1), 10);
        // handle two-digit year
        if (yr < 100) {
            var today = new Date();
            // get current century floor (e.g., 2000)
            var currCent = parseInt(today.getFullYear() / 100) * 100;
            // two digits up to this year + 15 expands to current century
            var threshold = (today.getFullYear() + 15) - currCent;
            if (yr > threshold) {
                yr += currCent - 100;
            } else {
                yr += currCent;
            }
        }
        var testDate = new Date(yr, mo-1, day);
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    // fill field with database-friendly format
                   // fld.value = mo + "/" + day + "/" + yr;
                    return true;
                } else {
                    //$('go_button').disabled = true; 
                    $(updatefield).innerHTML = '<Font color="red">' + "There is a problem with the year entry." + '</FONT>';
                    $(updatefield).setStyle ( { display:'block' } );
                }
            } else {
                //$('go_button').disabled = true; 
                $(updatefield).innerHTML = '<Font color="red">' + "There is a problem with the month entry." + '</FONT>';
                $(updatefield).setStyle ( { display:'block' } );
            }
        } else {
                //$('go_button').disabled = true; 
                $(updatefield).innerHTML = '<Font color="red">' + "There is a problem with the date entry." + '</FONT>';
                $(updatefield).setStyle ( { display:'block' } );
        }
    } else {
       // $('go_button').disabled = true; 
        $(updatefield).innerHTML = '<Font color="red">' + "Incorrect date format. Enter as mm/dd/yyyy." + '</FONT>';
        $(updatefield).setStyle ( { display:'block' } );
        return false;
      }
    }
    
// thresholds for cart values    
var cart_item_minValue  = 0;
var cart_item_maxValue  = 9999;
var cart_item_warnValue = 100;
    
// Is the character a digit ('0'..'9').
function _isDigit(d)
    {
    return ((d >= '0') && (d <= '9'));
    }

// Check to see if quantity is a valid numeric value.
function _isNum ( quantity )
    {
    if ( quantity.length == 0 )
        {
        return false;
        }
    for ( var i = 0; i < quantity.length; i++ )
        {
        var c = quantity.charAt(i);
        if ( !_isDigit(c) )
            {
            return false;
            }
        }
    return true;
    }

// Routine to validate a shopping cart quantity.
function isValidCartQuantity ( quantity )
    {
    var isValid = _isNum(quantity) &&
                  quantity >= cart_item_minValue &&
                  quantity <= cart_item_maxValue;
    return isValid;
    }



