//***USAGE***//
//useremail=isEmail(email.value);
//if (useremail==false) {
//	alert("Please enter a valid email address.");
//	email.focus();
//	return false;
//}
function isEmail(argvalue) {

  	if (argvalue.indexOf(" ") != -1)
    	return false;
  	else if (argvalue.indexOf("@") == -1)
    	return false;
  	else if (argvalue.indexOf("@") == 0)
    	return false;
  	else if (argvalue.indexOf("@") == (argvalue.length-1))
    	return false;

	var strArray = argvalue.split("@");

	if (strArray[1].indexOf(".") == 0) 
		return false;		
	else if (strArray[1].indexOf(".") == -1) 
		return false;
	else if (strArray[1].indexOf(".") == (strArray[1].length-1)) 
		return false;

	var laniArray = strArray[1].split(".");

	if (laniArray[(laniArray.length)-1]=="")
		return false;

  return true;

}

//***USAGE***//
//var address = theform.Address;
//if (isPOBox(address, address)==true){
//	alert("We do not accept P.O. Box addresses.");
//	address.focus();
//	return false;
//}
function isPOBox(argvalue, thectrl){
	argvalue = argvalue.value.replace(/\./g,""); //to remove periods
	argvalue = argvalue.replace(/ /g,"");  //to remove spaces
	argvalue = argvalue.toLowerCase();

	if (typeof(thectrl) == "object" && argvalue.match("pobox") == "pobox")
		return true;
	
	return false;
}

// Radio Button Validation
//***USAGE***//
//var optship = valButton(theform.optShippingOptionID);
//if (optship==null){
//	alert("Please select your preferred shipping method.");
//	return false;
//}
function valButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}

function doCollapseByRadiobtn(elementId, action){
	var element = document.getElementById(elementId);
	element.style.display = action;
}

function doCollapse(elementId) {
	var element = document.getElementById(elementId);
	if(element.style.display != "block"){
		element.style.display = "block";
	}
	else{
		element.style.display = "none";
	}
}

function doUpdateInnerHTML(element, defaulttitle, showtitle, hidetitle) {
	if(element.innerHTML.indexOf(defaulttitle) != -1) {
		element.innerHTML = hidetitle;
	}
	else {
		element.innerHTML = showtitle;
	}
}

//************ISNUMERIC VALIDATION************//
//***USAGE***//
//if (!IsNumeric(ctrlqty.value)){
//		alert("You can only enter a numeric value.");
//		ctrlqty.value = 1;
//	}
function IsNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++){ 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1){
         IsNumber = false;
      }
   }
   return IsNumber;
}

//Sets new color in rows,buttons in Mouse Over/Mouse Out event//
function ChangeBtnColor(tID, mBGColor, mFColor){
    tID.style.background = mBGColor;
    tID.style.color = mFColor;
}

function RestoreBtnColor(tID, mBGColor, mFColor){
    tID.style.background = mBGColor;
    tID.style.color = mFColor;
}

function ChangeElemColor(tID, mBGColor, mFColor){
    document.getElementById(tID).style.background = mBGColor;
    document.getElementById(tID).style.color = mFColor;
}

function RestoreElemColor(tID, mBGColor, mFColor){
    document.getElementById(tID).style.background = mBGColor;
    document.getElementById(tID).style.color = mFColor;
}
//End of set new color in rows,buttons in Mouse Over/Mouse Out event//

//Navigate to other url from onchange event of dropdown box//
//Navigate and check if selectedIndex is greater than zero//
function drpdown_Navigate(drop_down_list){
    var number = drop_down_list.selectedIndex;

    if (number > 0){
	    location.href = drop_down_list.options[number].value;
	}
}

//Navigate without checking the selectedIndex//
function redirect(theurl){
	location.href = theurl;
}

//***Declaring valid date character, minimum year and maximum year***//
var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1 = dtStr.indexOf(dtCh)
	var pos2 = dtStr.indexOf(dtCh,pos1+1)
	var strMonth = dtStr.substring(0,pos1)
	var strDay = dtStr.substring(pos1+1,pos2)
	var strYear = dtStr.substring(pos2+1)

	strYr = strYear

	if (strDay.charAt(0) == "0" && strDay.length > 1) strDay=strDay.substring(1)
	if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth=strMonth.substring(1)

	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0) == "0" && strYr.length > 1) strYr=strYr.substring(1)
	}

	month = parseInt(strMonth)
	day = parseInt(strDay)
	year = parseInt(strYr)

	if (pos1 == -1 || pos2 == -1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length < 1 || month < 1 || month > 12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false){
		alert("Please enter a valid date")
		return false
	}
	return true
}

//***Usage***//
//function ValidateForm(){
//	var dt = document.frmSample.txtDate
//	if (isDate(dt.value) == false){
//		dt.focus()
//		return false
//	}
//    return true
//}
//***Usage***//


//************COOKIES************//
//***Usage***//
//function setcookie(){
//set_cookie("isLoggedIn", form1.txt.value);
//}

//get_cookie('isLoggedIn');

//delete_cookie('isLoggedIn');

function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure){
	var cookie_string = name + "=" + escape ( value );
	
	if (exp_y){
		var expires = new Date (exp_y, exp_m, exp_d);
		cookie_string += "; expires=" + expires.toGMTString();
	}

	if (path)
	    cookie_string += "; path=" + escape (path);

	if (domain)
	    cookie_string += "; domain=" + escape (domain);

	if (secure)
	    cookie_string += "; secure";

	document.cookie = cookie_string;
}

function get_cookie(cookie_name){
	var results = document.cookie.match ('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

	if (results)
		return (unescape(results[2]));
	else
		return null;
}

function delete_cookie(cookie_name){
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime (cookie_date.getTime() - 1);
	document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}


//************PHONE FORMAT************//
//***USAGE***//
//var phone = theform.Phone;
//phone.value=Format_USPhone(phone.value, 'nnn-nnn-nnnn', phone, theform);
//if (IsInvalid=="true") {
//	phone.focus();
//	return false;
//}

function Format_USPhone(phonevalue, phoneformat, phonename, theform){
	IsInvalid="false";
	phonevalue=phonevalue.replace(/\D/g,'');
	var phonelength=phoneformat.length-phoneformat.replace(/n/g,'').length;
	if (phonelength!=phonevalue.length){
		alert("Invalid format. US phone format must be numeric and contain 10 digits.\n\neg. 8183664529");
		IsInvalid="true";
	}
	var y=0,z='';
	for (var x=0;x<phoneformat.length;x++){
		z+=(phoneformat.charAt(x)=='n')?phonevalue.charAt(y++):phoneformat.charAt(x);
	}
	return z;
}

//************NUMBER FORMAT************//
//***USAGE***//
//alert(FormatNumber(document.getElementById('x').value, 2, true, true, true));
function FormatNumber(num, decimalNum, bolLeadingZero, bolParens, bolCommas){
	/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
	**********************************************************************/

    if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

//Universal confirmation msg box//
function doMsgAlert(msg, loc){
	var Selection = confirm(msg);
	if (Selection)
		if (loc != ""){
			window.location.href = loc;
			return true;
		}
		else{
			return true;
		}
	else
		return false;
}

//Modal window dialog box//
function modalWin(theurl, thename, thewidth, theheight){
	if (window.showModalDialog){
		if (navigator.userAgent.indexOf('Firefox') !=-1){
			window.showModalDialog(theurl, thename, "dialogWidth:"+thewidth+";dialogHeight:"+theheight);
		}
		else{
			window.showModalDialog(theurl, thename, "'dialogWidth:"+thewidth+";dialogHeight:"+theheight+"'");
		}
	}
	else{
		window.open(theurl, thename, "height="+theheight+",width="+thewidth+",menubar=no,status=yes,location=no,toolbar=no,scrollbars=yes,directories=no,resizable=no,copyhistory=no,modal=yes");
	}
}

var TotalOn = 0;
//==========================================
// Check All boxes (Master checkboxes)
//==========================================
function CheckAll(fmobj) {
  for (var i=0;i<fmobj.elements.length;i++) {
    var e = fmobj.elements[i];
    if ( (e.name != 'allbox') && (e.type=='checkbox') && (!e.disabled) ) {
      e.checked = fmobj.allbox.checked;
      if (e.checked){
      	TotalOn++;
      }
      else{
      	TotalOn = 0;
      }
    }
  }
}

//==========================================
// Check all or uncheck all? (Child checkboxes)
//==========================================
function CheckCheckAll(fmobj) {
  var TotalBoxes = 0;
  //var TotalOn = 0;
  TotalOn = 0;

  for (var i=0;i<fmobj.elements.length;i++) {
    var e = fmobj.elements[i];
    if ((e.name != 'allbox') && (e.type=='checkbox')) {
      TotalBoxes++;
      if (e.checked) {
      	TotalOn++;
      }
    }
  }
  if (TotalBoxes==TotalOn) {
    fmobj.allbox.checked=true;
  }
  else {
   fmobj.allbox.checked=false;
  }
}

//***USAGE***//
//selectChange(this, frmUserInfo.SpecialtyID, arrItems1, arrItemsGrp1);
function selectChange(control, controlToPopulate, ItemArray, GroupArray){
	var myEle;
	var x;
	// Empty the second drop down box of any choices
	for (var q=controlToPopulate.options.length;q>=0;q--) controlToPopulate.options[q]=null;
		// ADD Default Choice - in case there are no values
		myEle=document.createElement("option");
		theText=document.createTextNode("[SELECT]");
		myEle.appendChild(theText);
		myEle.setAttribute("value","0");
		controlToPopulate.appendChild(myEle);
		// Now loop through the array of individual items
		// Any containing the same child id are added to
		// the second dropdown box
		for ( x = 0 ; x < ItemArray.length  ; x++ ) {
			if ( GroupArray[x] == control.value ) {
				myEle = document.createElement("option") ;
				//myEle.value = x ;
				myEle.setAttribute("value",x);
				// myEle.text = ItemArray[x] ;
				var txt = document.createTextNode(ItemArray[x]);
				myEle.appendChild(txt)
				// controlToPopulate.add(myEle) ;
				controlToPopulate.appendChild(myEle)
			}
		}

		if (control.selectedIndex==0){
			controlToPopulate.style.background="#EEEEEE";
			controlToPopulate.disabled=true;
		}
		else{
			controlToPopulate.style.background="#FFFFFF";
			controlToPopulate.disabled=false;
		}
}

function refreshParent(msg, closechild){
	window.opener.document.location.href = window.opener.document.location.href;

	if (window.opener.document.progressWindow){
		if(closechild=="true"){
			window.opener.document.progressWindow.close()
		}
	}

	if(msg!=""){
		alert(msg);
	}

	if(closechild=="true"){
		window.close();
	}
}

function swap_img(thectrl, theimg){
	document.getElementById(thectrl).src=theimg;
}
