//////////////////////////////////////////////////////////
// Checks whether a string contains a double byte character
// target = the string to be checked
//
// Return true if target contains a double byte char; false otherwise
//////////////////////////////////////////////////////////
function containsDoubleByte (target) 
{
     var str = new String(target);
     var oneByteMax = 0x007F;

     for (var i=0; i < str.length; i++)
     {
        chr = str.charCodeAt(i);
        if (chr > oneByteMax) {return true;}
     }
     return false;
}

//////////////////////////////////////////////////////////
// A simple function to validate an email address
// It does not allow double byte characters
// strEmail = the email address string to be validated
//
// Return true if the email address is valid; false otherwise
//////////////////////////////////////////////////////////
function isValidEmail(strEmail)
{
	// check if email contains dbcs chars
	if (containsDoubleByte(strEmail))
	{
		return false;
	}
	
	if(strEmail.length == 0) 
	{
		return true;
	} 
	else if (strEmail.length < 5) 
	{
         return false;
    }
    else if (strEmail.indexOf(" ") > 0)
   	{
      	return false;
   	}
   	else if (strEmail.indexOf("@") < 1) 
  	{
    	return false;
 	}
 	else if (strEmail.lastIndexOf(".") < (strEmail.indexOf("@") + 2))
   	{
     	return false;
    }
    else if (strEmail.lastIndexOf(".") >= strEmail.length-2)
    {
    	return false;
    }
  	return true;
}

//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string
// arg2 = the maximum number of bytes allowed in your input field
// Return false is this input string is larger then arg2
// Otherwise return true...
//////////////////////////////////////////////////////////
function isValidUTF8length(UTF16String, maxlength) 
{
    if (utf8StringByteLength(UTF16String) > maxlength) 
    	return false;
    else 
    	return true;
}

//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string you want a byte count of...
// Return the integer number of bytes represented in a UTF-8 string
//////////////////////////////////////////////////////////
function utf8StringByteLength(UTF16String) 
{
	if (UTF16String === null) 
  		return 0;
  	var str = String(UTF16String);
  	var oneByteMax = 0x007F;
  	var twoByteMax = 0x07FF;
  	var byteSize = str.length;

  	for (i = 0; i < str.length; i++) 
  	{
    	chr = str.charCodeAt(i);
    	if (chr > oneByteMax) 
    		byteSize = byteSize + 1;
    	if (chr > twoByteMax) 
    		byteSize = byteSize + 1;
  	}  
  	return byteSize;
}
var enabled = true;

//////////////////////////////////////////////////////////
//This function creates or modifies a cookie.
//
//////////////////////////////////////////////////////////
function updateCookie(name, value)
{
	if(enabled)
	{
		document.cookie = name + "=" + escape(value) + ";path=/;";
	}
}
//////////////////////////////////////////////////////////
//This function reads a cookie.
//
//////////////////////////////////////////////////////////
function readCookie(name) 
{
	if(enabled)
	{
		var cookie = document.cookie.split(';');
		var result = null;
		var res = new Array(null,null);
		for (i=0;i<cookie.length;i++)
		{  
			if(cookie[i].indexOf(name+"=")!=-1)
				res=cookie[i].split("=");
		}
		result=res[1];
		return result;
	}
}
	
//////////////////////////////////////////////////////////
// Sets the expiration date of a cookie (set to zero to delete cookie).
//
//////////////////////////////////////////////////////////
function expireCookie(name, minutes)
{
	if(enabled)
	{
		var dateObj=new Date();
		dateObj.setMinutes(dateObj.getMinutes()+minutes);
		document.cookie = name + "=" + readCookie(name) + ";path=/;expires=" + dateObj;
	}
}

function validateEmail(emailAdress)
{
	validEmail = isValidEmail(emailAdress);
	var emailErrElement = document.getElementById('emailError');
  	if(!validEmail && emailErrElement)
  	{
    	emailErrElement.style.display="";
  	}
  	else if(emailErrElement)
  	{
    	emailErrElement.style.display="none";
  	}
  	return validEmail;
}
//////////////////////////////////////////////////////////
// Convert char to ascii code
//
//////////////////////////////////////////////////////////
function toAscii (cmChar)  
{
	var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
	var loc;
	loc = symbols.indexOf(cmChar);
	if (loc >-1) 
	{ 
		return (32 + loc);
	}
	return(0);  // If not in range 32-126 return ZERO
}

//////////////////////////////////////////////////////////
// Convert decimal to Hex
//
//////////////////////////////////////////////////////////
function Dec2Hex(Decimal) 
{
	var hexChars = "0123456789ABCDEF";
	var a = Decimal % 16;
	var b = (Decimal - a)/16;
	hex = "" + hexChars.charAt(b) + hexChars.charAt(a);
	L = hexChars.charAt(a);
	H = hexChars.charAt(b);
	return hex;
}

//////////////////////////////////////////////////////////
//Right trims spaces from a string
//////////////////////////////////////////////////////////
function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0)
	{
		return"";
	}
	var iTemp = v_length -1;
	
	while(iTemp > -1)
	{
		if(VALUE.charAt(iTemp) == w_space)
		{
		}
		else
		{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	} //End While
	return strTemp;
} //End Function

function trim(stringToTrim) 
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

//////////////////////////////////////////////////////////
// This function is meant to remove html tags from a string
// There is a possibility that the HTML tags are in Mark Up 
//  form, so change string from markup before replacing
// 
// Returns input string with no html.
//////////////////////////////////////////////////////////
function clearHTMLTags(strHTML)
{		
  	var strOut;
    var cMarkUp = /&lt;([^&]*)&gt;/g; //Markup regexp
    var strMarkedUp = strHTML.replace(cMarkUp,"<$1>");
  	
	//replace on reg expression
    strOut = strMarkedUp.replace(/<[^>]*>/g, "");   
    return strOut;
} // //End Function

//////////////////////////////////////////////////////////
// This function parses price to remove '$'
// 
// Returns number
//////////////////////////////////////////////////////////
function parsePrice(strPrice)
{		
  	var priceOnly;
  	
  	if(strPrice && strPrice.indexOf('$') != -1)
	{
		priceOnly = trim(strPrice).substring(1, strPrice.length);		
	}
	else
	{
		priceOnly = trim(strPrice);
	}
	
	if (priceOnly)
	{
		priceOnly = priceOnly.toLowerCase();
	}
	
	if(priceOnly && priceOnly.indexOf('<br') != -1)
	{
		priceOnly = trim(priceOnly.substring(0, priceOnly.indexOf('<br')));
	}
	
	return Number(priceOnly);
} //End Function

//////////////////////////////////////////////////////////
// This function outputs a price format with '$'
// 
// Returns string
//////////////////////////////////////////////////////////
function formatCurrency(val, bIncludeSign) 
{
	if (val.toFixed) 
	{ 	//if browser supports toFixed
		val = val.toFixed(2);
	} 
	else 
	{
		val = val + ''; // make a string - to preserve the zeros at the end
	    var decimalPos = val.indexOf('.');
	    if (decimalPos == -1) 
	    {
	        val += '.';
	        for (i=0; i<2; i++)
	        {
	            val += '0';
	        }
	    } 
	    else 
	    {
	        var actualDecimals = (val.length - 1) - decimalPos;
	        var difference = 2 - actualDecimals;
	        for (i=0; i<difference; i++)
	        {
	            val += '0';
	        }
	    }
	}
	if (bIncludeSign) 
		val = '$' + val;
	return val;
}

function checkEnterPressed(e)
{
	 var characterCode;
	 if(e && e.which)
	 {
		 e = e;
		 characterCode = e.which;
	 }
	 else
	 {
		 e = event;
		 characterCode = e.keyCode;
	 }
	 if(characterCode == 13)
	 {
	 	return true;
	 }

	 return false;
 }
//////////////////////////////////////////////////////////
// This function opens a popup "modal" window.
// since the showModalDialog is only supported by IE >= 5.5
// we have to use a different technique for Mozilla.
//	NOTE: the mozilla technique is not completely modal since
//		you can still do stuff on the previous window, 
//		but this new one will stay on top. 
//////////////////////////////////////////////////////////
function modalPopup(popupURL, popupTitle, popupWidth, popupHeight) 
{
	var result;
	if(window.showModalDialog) 
	{	//showModal is supported
		result = window.showModalDialog(popupURL, popupTitle,
			"dialogWidth:" + popupWidth + ";dialogHeight:" + popupHeight);
	} 
	else 
	{	//showModal not supported.
		result = window.open(popupURL, popupTitle,
			"height=" + popupHeight + ",width=" + popupWidth 
			+ ",toolbar=no,directories=no,status=no,menubar=no,"
			+ "scrollbars=no,resizable=no,modal=yes");
	}
	return result;
}

// Displays, hides or toggles layers
function toggleBox(obj, iState) // 1 visible, 0 hidden, 2 toogle
{
	try
	{
		if (obj)
		{
			var $obj = $(('#' + obj));
			
			if (iState == 2)
			{
				$obj.toggle();
			}
			else if(iState == 1) 
			{	
				$obj.show();
			}
			else
			{
				$obj.hide();
			}
		}
	}
	catch(e){}
}

//Popup
function nonModalPopup(file, p_width, p_height, sbars, loc, menus, toolb)
{
	var w = p_width;
	var h = p_height;
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	
	if (!sbars) sbars = "0";
	if (!loc) loc = "0";
	if (!menus) menus = "0";
	if (!toolb) toolb = "0";
	
	windowprops = "height="+h+",width="+w+",top="+ wint +",left="+ winl +",location="+loc+", scrollbars="+sbars+",menubar="+menus+",toolbar="+toolb+",resizable=0,status=1";
	var win = window.open(file, "Popup", windowprops);
	win.focus();
}

/**
*  Validate phone number 
*/
function isPhoneValid(phoneValue)
{
	var rtn = true;
	
	if (phoneValue != "")
	{
		// This Regular Expression requires a US phone number with area code.
		// It accepts whatever delimiters you want or no delimiters at all.
        // (111-222-3333, or 111.222.3333, or (111) 222-3333, or 1112223333)	
		var phone1Check = new RegExp(/(^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$)/);
		if (!phone1Check.test(phoneValue)) 
		{
        	rtn = false;
        }
    }
	 
	return rtn;
}  

/** 
 *	convert an array of one to scalar values
 */
function _convertArray(ar) 
{
	if(null == ar) 
	{
		return null;
	}
	if(ar.length) 
	{
		// is either array or string 
		if(ar.substr) 
		{
			// is a string -- return it.
			return ar;
		} 
		else 
		{
			try 
			{ 
				return ar[0]; 
			}
			catch(e) 
			{ 
				return null; 
			}
		}
	} 
	else 
	{
		return ar;
	}
}

// Stuff from CSD
/**
 * Attach a roll-over image for the given target
 */
function attachRollover(target, image){
    var $target = $(target);
    var $image = $target.find('img');
    var $original = $image.attr('src');
    $target.hover(
      function(){ $image.attr('src', image); },
      function(){ $image.attr('src', $original); }
    );
  }
  
// Expand/Contract Menu items logic
function expand(id, suff)
{
	var linkEl = document.getElementById(id);
	var contentEl = document.getElementById(id + suff);	
	
	contentEl.style.display = "block";
	linkEl.href = "javascript:contract('"+id+"','"+suff+"')";
}

function contract(id, suff)
{
	var linkEl = document.getElementById(id);
	var contentEl = document.getElementById(id + suff);	
	
	contentEl.style.display = "none";
	linkEl.href = "javascript:expand('"+id+"','"+suff+"')";
}

/** 
	Confirm that only numeric characters have been entered into input field.	
	Implement using the "onKeyPress" event/attribute.
**/
function checkNumericInput(evt)
{
	var modKey = null;
	
	if (!evt) 
		var evt = window.event;
   	
   	//Determine modifier
   	if(evt.ctrlKey)
   		modKey = "c"; // Ctrl key pressed
   	
	// Get ASCII value of key that user pressed	
	var key = document.all ? evt.keyCode : evt.which;
	
	// Was key that was pressed a numeric character (0-9)?
	// 8 = Backspace
	// 0 = Tab
	// 13 = Enter
	
	if (modKey || (key == 8 || key == 0 || key == 13) || 
		(key > 47 && key < 58))
		return true; // if so, do nothing
	else
		return false; // otherwise, discard character
}

function hideHint(inputElement)
{
    inputElement.value='';
    inputElement.onfocus=null;
    inputElement.style.color="#000000";
}

/**
 * clear the select input type
 * @param selectId
 * @return
 */
function clearSelect(selectId)
{
	var selectBox = dojo.byId(selectId);
	try
	{
		selectBox.options.length = 0;
	}
	catch(e)
	{	// ie 6 hack
		if (selectBox && selectBox.options)
		{
			var i;
			for(i=selectBox.options.length-1;i>=0;i--)
			{
				selectBox.remove(i);
			}
		}
	}
}
