//=============================================================================
// Common JavaScript methods
//=============================================================================


//-----------------------------------------------------------------------------
// Frame related methods
//-----------------------------------------------------------------------------

// Force the current page to use the top frame - call this in the body onload
// to ensure that the page comes up in the top frame as opposed to a child frame.
function forceTopFrame() {	
	if (top != self)
		top.location.href = self.location.href;
}


//-----------------------------------------------------------------------------
// Control related methods
//-----------------------------------------------------------------------------

// Return true if control is null or has an empty value
function controlIsEmpty(ctrl)
{
	return ((ctrl == null) || ctrl.value.isempty());
}

// Hide/show the control with the specified ID
function showControl(id, show)
{
	var ctrl = document.getElementById(id);
	if (ctrl != null)
		ctrl.style.display = (show ? '' : 'none');
}

// This is used to enable & disable Validator controls.  It will only work with
// validator controls (such as RequiredFieldValidator, etc), AND it will only
// work if the Enabled property of the validator control is set to False by
// default!  Script can then use this method to enable (& disable) the validator.
function enableValidator(id, val)
{
	var ctrl = document.getElementById(id);
	if (ctrl != null)
		ctrl.enabled = val;
}

// This function enables the specified button when the specified Text Edit
// control has data. Otherwise, the button will be disabled.
function enableButtonBasedOnTextEdit(buttonId, textId)
{
	var text = document.getElementById(textId);
	if (text != null)
	{
		var enabled = !text.value.isempty();
		enableButton(buttonId, enabled);
	}
}

// This function enables the specified Anchor/Image when the specified Text Edit
// control has data. Otherwise, the Anchor/Image will be disabled.
function enableAnchorImageBasedOnTextEdit(anchorId, imageId, textId)
{
	var text = document.getElementById(textId);
	if (text != null)
	{
		var enabled = !text.value.isempty();
		enableAnchor(anchorId, enabled);
		enableImage(imageId, enabled);
	}
}

// Enable/disable the specified button control.
// If the button is an Image Button, the image will also be enabled/disabled.
function enableButton(buttonId, enabled)
{
	var button = document.getElementById(buttonId);
	if (button != null)
	{
		// Enable/disable the button control
		button.disabled = !enabled;
		enableImage(buttonId, enabled);
	}
}

// Enable/disable the specified anchor control.
// If the button is an Image Button, the image will also be enabled/disabled.
function enableAnchor(anchorId, enabled)
{
	var anchor = document.getElementById(anchorId);
	if (anchor != null)
	{
		anchor.disabled = !enabled;
		if (enabled)
		{
			if (anchor.href == null || anchor.href == "")
				anchor.setAttribute("href", anchor.ohref);
		}
		else
		{
			anchor.setAttribute("ohref", anchor.href);
			anchor.removeAttribute("href");
		}
	}
}

// Enable/disable the specified image control.
// This method determines a disabled image file name by appending "-d" to the base part
// of the existing image file name, and also changes the mouse pointer from a hand to a
// normal pointer if the image is disabled.
function enableImage(imageId, enabled)
{
	var image = document.getElementById(imageId);
	if (image != null)
	{
		// Change the source file name as appropriate
		var src = image.src;
		if (src != null && src.length > 0)
		{
			var extPos = src.lastIndexOf(".");
			if (extPos > 0)
			{
				var base = src.substring(0, extPos);
				var len  = base.length;					
				if (base.substring(len - 2) == "-d")
					base = base.substring(0, len - 2);
				var ext  = src.substring(extPos + 1);
				image.src = base + (enabled ? "" : "-d") + "." + ext;
				image.style.cursor = (enabled ? "hand" : "default");
			}
		}
	}
}


//-----------------------------------------------------------------------------
// String utilities
//-----------------------------------------------------------------------------

function strisempty() {
	return (this.trim().length == 0);
}
function strltrim() {
    return this.replace(/^\s+/,'');
}
function strrtrim() {
    return this.replace(/\s+$/,'');
}
function strtrim() {
    return this.ltrim().rtrim();
}
function strStripWhitespace() {
	return this.replace(/\s+/,'');
}

String.prototype.isempty = strisempty;
String.prototype.ltrim = strltrim;
String.prototype.rtrim = strrtrim;
String.prototype.trim = strtrim;
String.prototype.stripWhitespace = strStripWhitespace;


//-----------------------------------------------------------------------------
// Pop-up window methods
//-----------------------------------------------------------------------------

function newWindow(url, name, width, height, resize, scrollbar, menubar) {
	var xTop = screen.width/2 - (width/2);
	var yTop = screen.height/2 - (height/2);
	if (scrollbar==null || scrollbar.length==0)
		scrollbar = '1';
	if (menubar=='undefined' || menubar==null)
		menubar='0';
					
	var childWindow = window.open(url, name.stripWhitespace() + 'Popup', 'height=' + height
		+ ',width=' + width + ',scrollbars=' + scrollbar + ',resizable=' + resize
		+ ',menubar=' + menubar
		+ ',toolbar=0,status=0,location=0,directories=0,left='
		+ xTop + ',top=' + yTop);
	childWindow.window.focus();
}

function showExcelWindow(url, name) {
	showProcessing(false);
	var myUrl; var w;	var h;	var t; var l; var option;
	w = 600; h = 600;	t = (screen.availHeight - h) / 2;	l = (screen.availWidth - w ) / 2;
	option = "width=" + w + ",height=" + h + ",top=" + t + ",left=" + l;
	option = option + ',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes';					
	window.open(url,name.stripWhitespace()+'Popup',option);     	      	
}

function showDiv(object) {
	//(document.all) - ie only -  NS will crap - by design
	var ctrl = document.all[object];
	if (ctrl != null)
	{    
		ctrl.style.visibility = 'visible';
		ctrl.style.zIndex = 100;
    }
}

function hideDiv(object) {
	var ctrl = document.all[object];
	if (ctrl != null)
		ctrl.style.visibility = 'hidden';			
}

function showHideDiv(object, show) {
	if (show)
		showDiv(object);
	else
		hideDiv(object);
}


function hideErrorDiv() {		
	var ctrl;
	for (var i=0; i<256; i++) {
		ctrl = document.all['ErrorDiv' + i];
		if (ctrl != null)
			ctrl.style.visibility = 'hidden';
		else
			break;		
	}
}

//-----------------------------------------------------------------------------
// Page submission methods
//-----------------------------------------------------------------------------

function hideSubmitImages(imgID) {
	var ctrl = document.getElementById(imgID);
	if ( ctrl!= null) {
		ctrl.disabled = true;
		ctrl.style.visibility = "hidden";
	}
}

function submitClick() {
	var bSubmit = true;

	hideErrorDiv();	//hide any ErrorDivxxx where xxx=0-255

	// If the page has validation controls, execute them
	if (typeof(Page_ClientValidate) == 'function')
		bSubmit = Page_ClientValidate();

	// If we didn't fail validation, continue
	if (bSubmit) {

		// Disable the INPUT control to prevent the user from clicking it again while
		// waiting.  This MUST be done before the manual submit below, or we'll get a
		// double submit courtesy of some freaking code in IE.
		// TODO: This requires an ugly hack on the server to detect a post-back without
		//       any control name (it doesn't get sent since the control is disabled
		//       before the submit is done).  Try to fix this script to post-back the
		//       proper form variables to the server (has to be X,Y coordinates for
		//       image buttons.  ALSO, probably should pass the control ID below into
		//       this method as a parameter.
		
		//var ctrl = document.getElementById('SubmitImage');
		//ctrl.disabled = true;
		//ctrl.style.visibility = "hidden";
		
		hideSubmitImages('SubmitImage');
		hideSubmitImages('SubmitQuoteImage');		

		// Put a message on the browser's status line, otherwise it will say "Done"
		// even though we're still waiting for the server.
		//window.status = 'Processing...';

		// Display optional processing animation to the user
		showProcessing(true);

		// Force a submit manually
		var form = document.forms[0];
		form.submit();

		// Finally, disable all of the controls on the page, so the user can't mess around
		// with them while waiting for the server. This must be done AFTER the submit,
		// otherwise no form variables will be sent to the server.
		var elements = form.elements;
		for (var i = 0; i < elements.length; ++i)
			elements[i].disabled = true;
	}
	return bSubmit;
}

function showProcessing(show) {
	var img = document.getElementById('imgProcessing');
	if (img != null) {
		img.src = show ? "../css/Images/stampa.gif" : "../css/Images/blank.gif";
		window.status = 'Processing...';
	}
	else {
		window.status = 'Processing.....';
	}
}

function validateLength(ctrl, length) {
	if (ctrl.value.length <length)
		return true;
	return false;
}

//=============================================================================
function isNumber(key) {
	return (key>=48 && key<=57);
}

//--- SSN functions -----

function lsiOnKeyPressSSN(editControl) {
	
	key = window.event.keyCode;	    
    if (  isNumber(key) ) {	//Numbers from 0-9 only
        var len = editControl.value.length;
        if (len==3 || len==6)
        	editControl.value += '-';        
        	//alert('true - key=' + key);
        return true;
    }       
    //alert('false - key=' + key);
    return false;
}

function lsiOnblurSSN(editControl) {
	var data = editControl.value;
	if (data.length == 9)
		editControl.value = data.substr(0,3) + "-" + data.substr(3,2) + "-" + data.substr(5,4); 
	
}

function lsiOnKeyUpSSN(editControl) {
	
   var key = window.event.keyCode;	
	var len = editControl.value.length;
	
	//var msg = 'lsiOnKeyUpSSN:' + key + '       len:' + len + ' - ';
	//window.status = msg;

    if (  (key>=48 && key<=57) || (key>=96 && key<=105)) {	//Numbers from 0-9 only        
        switch (len) {
        	case 3:        		
        		editControl.value += "-";
        		break;        		
        	case 6:
        		editControl.value += "-";
        		break;        		
        	default:
        		break;
        	}           
    }
}
//-----------------------------------------------------------------------------------------

function lsiOnKeyPressPhone (ctrl, noExtension) { 
	    var key = window.event.keyCode;    	    
	    var len = ctrl.value.length;
	    var msg = 'keyPressPhone:' + key + 'len:' + len + ' - ';	    
	    //window.status = msg;              
	    
	    //Len Pos: 01234567890123
	    //Format:  123 456-7890
	    //keyCode  =40  =41  -=45   0=48  1=49  2=50  ... 9=57  space=32  <bspc> N/A  <SHIFT> N/A
	    	    
        //After all the basic numbers are entered:  (888) 789-0123
        //  - If the next character is a space, let it through
        //  - If the next character is an X, add a space in front of it
        //  - If the next character is a digit, add space + 'X' in front of it
        //The trick is how to determine the end of the sequence.  Try detect "-dddd"	    
	    if ( len>10 && ctrl.value.charAt(len-5)=='-') {
			if (noExtension) {
				return false;
			}
			else {				
				if (key==88 || key==120) {	//"x" 120, "X" 88
					ctrl.value += " ";
				}
				else if ( isNumber(key) ) {
					ctrl.value += " x";
				}						
			}
        }
	    
	    //Don't allow 'x' nor 'X' until sequence	    
	    if (key==88 || key==120) {
			if ( len<=13 || (ctrl.value.indexOf('x')>0) || (ctrl.value.indexOf('X')>0) )
				return false;
		}
		
	    
	    if ( (len==0 && key==40) || (len==4 && key==41)  || (len==5 && key==32) || (len==9 && key==45) ) {
	    	return true;
	    }
	    	    
	    if ( (key>=48 && key<=57) && len<=20) {
	    	switch (len) {
	        	case 0:
	        		ctrl.value = "(";
	        		break;        		
	        	default:
	        		break;
	        	}             	
	    		return true;
	    }
	    
   
	    
	    if (key==88 || key==120 || key==32)
			return true;
	    
	    return false;
}

function lsiOnKeyUpPhone(ctrl, noExt) {
	
   key = window.event.keyCode;	
	var len = ctrl.value.length;
	//msg += 'keyUpPhone:' + key + 'len:' + len + ' - ';
	//window.status = msg;

	if (len==5 && key==48)
		ctrl.value += " ";

    if (  (key>=48 && key<=57) || (key>=96 && key<=105) ) {	//Numbers from 0-9 only  also allow "x" 120, "X" 88, and space 32
        //alert(len);
        switch (len) {
        	case 1:
        		if (key>=48 && key<=57)
        			ctrl.value = "(" + ctrl.value;
        		break;
        	case 4:
        		//alert("len=4");
        		ctrl.value += ") ";
        		break;        		
        	case 9:
        		ctrl.value += "-";
        		break;
        	//case 15:
        		//if (key==48)
        		//	ctrl.value += "x";
        		break;         		
        	default:        		
        		break;
        	}                	        	
    }
    else {
    	//if (len > 0)
    	//	editControl.value = editControl.value.substring(0, len-1);
    }    
}

//-----------------------------------------------------------------------------------------

function isCurrency(key) {
	//Numbers from 0-9 only,  36=$  46=.  44=,
	return (  (key>=48 && key<=57) || (key==36) || (key==46) );  //don't allow comma (key==44) 
}

function lsiOnKeyPressCurrency(editControl) {
	//alert('Hi');
    key = window.event.keyCode;    
    //alert(key);
    if (  isCurrency(key) ) {	
		var len = editControl.value.length;
    	if (len == 0) {
    		if ( key==36 ) //$
    			return true;
    		else if ( isNumber(key) ) {
    			editControl.value = '$';
    		}
    		else
    			return false;     		
    	}
    	else if ( len>11 ) {
    		return false;
    	}
    	else {  //Not the first character
    		if ( key==36 ) //$
    			return false;
    	}
    	  		
		//if there is already a period, only allow two more characters after that, and no additional period allowed
		var periodPos = editControl.value.indexOf('.');
		if ( periodPos>0 && ( (len-periodPos)>2 || key==46 ) )			
    			return false;
    	  		
        return true;
    }           
    return false;
}




