var gl_el; //global element

//function compares two dates (string format) date format = YYYY-MM-DD
/* @return: -1 value1 < value2
			 1 value1 > value2
			 0  value1 = value2
*/			
// trim() function defined to remove spaces
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function dateCompare (value1, value2) {
   var date1, date2;
   var month1, month2;
   var year1, year2;

   year1  = value1.substring (0, value1.indexOf ("-"));
   month1 = value1.substring(value1.indexOf ("-")+1, value1.lastIndexOf ("-"));
   date1  = value1.substring (value1.lastIndexOf ("-")+1, value1.length);

   year2  = value2.substring (0, value2.indexOf ("-"));
   month2 = value2.substring(value2.indexOf ("-")+1, value2.lastIndexOf ("-"));
   date2  = value2.substring (value2.lastIndexOf ("-")+1, value2.length);

   year1  = parseFloat(year1);
   month1 = parseFloat(month1);
   date1  = parseFloat(date1);

   year2  = parseFloat(year2);
   month2 = parseFloat(month2);
   date2  = parseFloat(date2);

   if (year1 > year2){ return 1;}
   else { 
		if (year1 < year2){  return -1;}
		else { //means year1=year2
			if (month1 > month2){ return 1;}
			else{ 
				if (month1 < month2) { return -1;}
				else {//means month1=month2
					if (date1 > date2){ return 1;}
					else { 
						if (date1 < date2) {  return -1;}
						else{ //means date1=date2
							return 0;
						}
					}
				}
			}
		}
   }
}
function counterText(field, countfield, maxlimit) {
	/*
	* The input parameters are: the field name;
	* field that holds the number of characters remaining;
	* the max. numb. of characters.
	*/
	if (field.value.length > maxlimit) // if the current length is more than allowed
		field.value =field.value.substring(0, maxlimit); // don't allow further input
	else
		countfield.value = maxlimit - field.value.length;
} // set the display field to remaining number



/*
	validation function
	
*/
function trim(b){
	var i=0;
	while(b.charAt(i)==" "){
		i++;
	}
	
	b=b.substring(i,b.length);
	len=b.length-1;
	
	while(b.charAt(len)==" "){
		len--;
	}
	b=b.substring(0,len+1);
	return b;
}

function isCharsInBag (s, bag)
  {
    var i;
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) return false;
    }
    return true;
 }

//function to check valid zip code
function isZIP(s) 
  {
    return isAlphaNumeric(s);
 }

//function to check valid Telephone,. Fax no. etc
function isPhone(s)
  {
	return isCharsInBag (s, "0123456789-+(). ");//simple test
	
	var PNum = new String(s);
	
	//	555-555-5555
	//	(555)555-5555
	//	(555) 555-5555
	//	555-5555

    // NOTE: COMBINE THE FOLLOWING FOUR LINES ONTO ONE LINE.
	var regex = /^[0-9]{3,3}\-[0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\) [0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\)[0-9]{3,3}\-[0-9]{4,4}$|^[0-9]{3,3}\-[0-9]{4,4}$/;
//	var regex = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/; //(999) 999-9999 or (999)999-9999
	if( regex.test(PNum))
		return true;
	else
		return false;
	
	/*//code1
	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/; 
	if (s.match(phone2)) {
   		return true;
 	} else {
 		return false;
 	}

	
	*/
	
	/*//code2
	var stripped = s.replace(/[\(\)\.\-\ ]/g, '');
//strip out acceptable non-numeric characters
	if (isNaN(parseInt(stripped))) {
	   return false;
	}
	
	
	if (!(stripped.length == 10)) {
			return false;
	}
	*/
	
	/*//code3
	if (isCharsInBag (s, "- +().,/;0123456789") == false)
    {
        return false;
    }
    return true;
	*/
 }

function isAlphaNumeric(s){
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ");
}

function isEmpty(s)
{
		  s=trim(s);
		  return ((s == null) || (s.length == 0))
}

//function to check valid email id
function isEmail(s)
{
	
	/*//code 3.
	var regex = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
    return regex.test(s);
	*/
	
	var regex = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
	var regex =	/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return regex.test(s);
	

	/*//code 2.
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.test(s)
	*/

	/* //code 1.
	var emailFilter = /^.+@.+\..{2,3}$/;
	if (!(emailFilter.test(s))) { 
		return false;
	}

	//we want to check to make sure that no forbidden characters have slipped in. For email addresses, we’re forbidding the following: ( ) < > [ ] , ; : \ / "
	var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
	if (s.match(illegalChars)) {
	   return false;
	}	
	return true;
	*/
}

//format YYYY-MM-DD
function isValidDate(strdate) { 
 // alert(strdate)
  var datedelimiter = '-';
  var datesplit = strdate.split(datedelimiter)
  if (datesplit.length > 3) {return false;}
  var month = 0; 
  month = datesplit[1];
  if (month < 1 || month >12 ) {return false;}
  if (isNaN(datesplit[0])) {return false;}
  else if (isNaN(datesplit[1])) {return false;}
  else if (isNaN(datesplit[2])) {return false;}
  else {
    //var year = parseInt(datesplit[2],10);
    var yearLn = (datesplit[0].length);
    var year= datesplit[0];
    	
    if (yearLn==1){return false;}
    if (yearLn==3){return false;}
    if (year<1){return false;}
    if (yearLn==2){
         year = '20'+ year
    }

   //var year = year;
   // alert(year)
    // var year = (datesplit[2],10);

    var day = parseInt(datesplit[2],10);
     if(day<0){return false;}
	if (day>31){return false;}
    if ((day > 30) && ((month == 4) || (month == 6) || (month == 9) || (month == 11))) {return false;}
    if (month == 2) {  // This calculates the basic leap year no matter the format, i.e. 2000 or 00. 
		var leap = ((year/4) == parseInt(year/4))
		if (leap) {if (day > 29) {return false;}
		}else {if (day > 28) {return false;}
      }
    }
  } 
  return true;
}

function isbigdateTime(StDate, StTime, EdDate, EdTime)
 {
//alert('start' + StTime + 'end' + EdTime)
	//var DTDelimiter = ' ';
	var DateDelimiter='/';
	var TimeDelimiter=':';
	
	//Split start date and time.
	//var StDTSplit = StDateTime.split(DTDelimiter);
	//if (StDTSplit.length>2){return false;}
	//var StDate=StDTSplit[0];
	//var StTime=StDTSplit[1];
	var StDSplit = StDate.split(DateDelimiter);//Splite date into MM/DD/YYYY
	//alert(StDSplit.length)
	if (StDSplit.length>3){return false;}
	var StMM=parseInt(StDSplit[0]);
	var StDD=parseInt(StDSplit[1]);
	var StYY=parseInt(StDSplit[2]);
	var StTSplit = StTime.split(TimeDelimiter);//Splite time into H:M
	if (StTSplit.length>2){return false;}
	var StH=StTSplit[0];
	var StM=StTSplit[1];
	//alert('StMM' + StMM + '  StDD' + StDD + '  StYY' + StYY + '  StH' + StH + '  StM' 

//+ StM);
	
	//Split end date and time.
	//var EdDTSplit = EdDateTime.split(DTDelimiter);
	//if (EdDTSplit.length>2){return false;}
	//var EdDate=EdDTSplit[0];
	//var EdTime=EdDTSplit[1];
	var EdDSplit = EdDate.split(DateDelimiter);//Splite date into MM/DD/YYYY
	if (EdDSplit.length>3){return false;}
	
	var EdMM=parseInt(EdDSplit[0]);
	var EdDD=parseInt(EdDSplit[1]);
	var EdYY=parseInt(EdDSplit[2]);
	var EdTSplit = EdTime.split(TimeDelimiter);//Splite time into H:M
	//alert(EdTSplit.length)
	if (EdTSplit.length>2){return false;}
	var EdH=EdTSplit[0];
	var EdM=EdTSplit[1];
	//alert('time'+ EdH)
	//alert('EdMM' + EdMM + '  EdDD' + EdDD + '  EdYY' + EdYY + '  EdH' + EdH + '  EdM' 

//+ EdM);
	
	if(StYY>EdYY){
	    form1.txtDateEnd.focus()
		return false;
	}
	else if(StYY==EdYY && StMM>EdMM){return false;}	
	else if(StYY==EdYY && StMM==EdMM && StDD>EdDD){return false;}	
	else if(StYY==EdYY && StMM==EdMM && StDD==EdDD && StH>EdH){
		//alert("time HH")
		form1.selEndTime.focus(); 
		return false;
	}else if(StYY==EdYY && StMM==EdMM && StDD==EdDD && StH==EdH && StM>=EdM){
		//alert("time MM")
		form1.selEndTime.focus(); 
		//form.selEndTime.focus();
		return false;
	}	return true;	
}

function OpenWin(width,height,URL,title)
{
	window.open(URL,'',"height=" + height + ",width=" + width + ",toolbar=no,location=no,directories=no,status=no,menubar=no,,scrollbars=yes,resizable=yes");
}


function SelectOption(pObj,pSelOption)
{
	for(var i=0;i<pObj.options.length;i++)
	{
		if(pObj.options[i].value==pSelOption)
		{
			pObj.options[i].selected=true;
		}
	}
}

function trim(b)
{
	var i=0;
	while(b.charAt(i)==" ")
	{
	i++;
	}
	b=b.substring(i,b.length);
	len=b.length-1;
	while(b.charAt(len)==" "){
	len--;
	}
	b=b.substring(0,len+1);
	return b;
}


//Validation for numeric fields
function isInteger(var1){
	str = var1;
	return isCharsInBag (str, "0123456789");
}

//Validation for radio buttons
function validateRadio(var1, var2){
	var sCheck = "N";
	for (i = 0; i < var1.length; i++){
		if (var1[i].checked == true){
		  sCheck = "Y";
		}
	}
	if (sCheck != "Y"){
		return false;
	}
	return true;
}

//Validation for percentage
function validatePercentage(var1, var2){
	var fld = "";
	fld = var1.value;
	if (fld > 100 && fld != ""){
		return false;
	}
	return true;
}

function isValidateUrl(strUrl) {
    var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) { 
        return false;
    }
	return true;
} 

function isPublisher(s){
	s=trim(s);
	var bag = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var flag = false; 
	
	for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1){
			flag = true;
		}
    }
    return flag;
}


function isName(s){
	s=trim(s);
	return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ");
}
function isNumeric(s){
	s=trim(s);
	return isCharsInBag (s, "0123456789");
}

  // This function accepts a string variable and verifies if it is a
  // proper date or not. It validates format matching either
  // mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
  // has the proper number of days, based on which month it is.	 
  // The function returns true if a valid date, false if not.
  // ******************************************************************	 
  function isDate(dateStr) 
  {

	   var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{2})$/;
	   var matchArray = dateStr.match(datePat); // is the format ok?
	   months= new Array(12);
	   months[0]="Jan";
	   months[1]="Feb";
	   months[2]="Mar";
	   months[3]="Apr";
	   months[4]="May";
	   months[5]="Jun";
	   months[6]="Jul";
	   months[7]="Aug";
	   months[8]="Sep";
	   months[9]="Oct";
	   months[10]="Nov";
	   months[11]="Dec"; 
	  if (matchArray == null) 
	  {
		  alert("Please enter date as either mm/dd/yy or mm-dd-yy.");
		  return false;
	  }
 
	  month = matchArray[1]; // parse date into variables
	  day = matchArray[3];
	  year = matchArray[5];

	  if (month < 1 || month > 12) // check month range
	  { 
		  alert("Month must be between 1 and 12.");
		  return false;
	  }
 
	  if (day < 1 || day > 31) 
	  {
		  alert("Day must be between 1 and 31.");
		  return false;
	  }
 
	  if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	  {
		  alert("Month "+ months[month-1]+" doesn't have 31 days!")
		  return false;
	  }
 
	  if (month == 2)  // check for february 29th
	  {
		  var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		  if (day > 29 || (day==29 && !isleap)) 
		  {
			  alert("February " + year + " doesn't have " + day + " days!");
			  return false;
		  }
	  }
	  return true; // date is valid
  }


  function selval(sellist, selvalue){
  	for(iVar=0;iVar<sellist.options.length;iVar++){
		if (selvalue == ""){
			sellist.selectedIndex = 0;
			return;
		} else if (sellist.options[iVar].value == selvalue){
			sellist.selectedIndex = iVar;
			return;
		}
	}
	return;
  }


  //set focus on el or global variable gl_el;
  function setFocus(el){
	if(el != "undefined"){
		document.getElementById(el).focus();
		setAlertStyle(el);
	//	addEvent(document.getElementById(el),'onblur',function(){ alert('hello!'); })
	}else if(typeof gl_el != "undefined"){
		gl_el.focus();	
	}
	return true;
	
  }
  
  function setAlertStyle(el){
	document.getElementById(el).style.border = '2px solid';
	document.getElementById(el).style.borderColor = 'RED';
  }
  
  function unsetAlertStyle(el){
	//document.anchors[elm].removeProperty("color");  
	//document.getElementById(el).style.removeProperty("border");  
	//document.getElementById(el).style.removeProperty("borderColor");  
	document.getElementById(el).style.border = '1px solid';
	document.getElementById(el).style.borderColor = '';
  }

  function addEvent( obj, type, fn ) {
   if ( obj.attachEvent ) {
     obj['e'+type+fn] = fn;
     obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
     obj.attachEvent( 'on'+type, obj[type+fn] );
   } else
     obj.addEventListener( type, fn, false );
 }
 
 
 
/*
 * msg = message to print
 * callback = function to be called when ok is clicked
 * el is the element to be passed when cllback is called
 */
function winAlert(msg,el,callback){
	if(!callback)
		callback = 'setFocus';
	
	/*
	alert(el);
	eval(callback+'("'+el+'");');*/
	
	Dialog.alert(
		'<span class="arial14">'+msg+'</span>', 
		{
			windowParameters: 
			{
				className: "alphacube",
				width:300
			},
			
			okLabel: "Ok",
			ok: function(win) { eval(callback+'("'+el+'");'); return true;}
		}
	);
	
}


/*
 * msg = message to print
 * callback = function to be called when ok is clicked
 * el is the element to be passed when cllback is called
 */
function winConfirm(msg,okcallback,cancelcallback){
	Dialog.confirm(
		msg,
		{
			windowParameters: 
			{
				className: "alphacube",
				width:300
			}, 
			
			okLable: "Ok",
			cancelLable: "Cancel",
			ok: function(win) { eval(okcallback); return true;},
			cancel:function(win) {
				if(cancelcallback){
					eval(cancelcallback);
				}
				return true;
			} 
		 }
	);	
}

function winOpen(url,width,height,name){
	if(!name)
		name = '';
	if(!width)
		width  = 800;
	if(!height)
		height = 500;
	leftVal = (screen.width - width) / 2;
	topVal = (screen.height - height) / 2;
	popUp = window.open(url,name,'scrollbars=1,resizable=1,width='+width+',height='+height+',left='+leftVal+',top='+topVal);
	return popUp;
}



function winClose(){
	window.close();
}

function intergerValue(value) {
	return parseInt(value);
}

function addOption(selectId, val, txt) {
	var objOption = new Option(txt, val);
	document.getElementById(selectId).options.add(objOption);
}



function checkAtLeastOneBox(name) {
	count = 0;
	elements = document.getElementsByName(name);
	len = elements.length;

	for (var i = 0; i < len; i++) {
		var e = elements[i];
		if (e.checked) {
			count=count+1;
		}
	}

	if (count == 0){
		return false;
	}
	else {
		return true;
	}
}

	function redirectURL(rediectUrl) {
		location.href= rediectUrl;
	}

	function removeHTMLTags(html){
		if(!isEmpty(html)){
			var strInputCode = html;
			/* 
				This line is optional, it replaces escaped brackets with real ones, 
				i.e. &lt; is replaced with < and &gt; is replaced with >
			*/	
			strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
				return (p1 == "lt")? "<" : ">";
			});
			strTagStrippedText = strInputCode.replace(/(&nbsp;)/ig, "");
			return strTagStrippedText = strTagStrippedText.replace(/<\/?[^>]+(>|$)/g, "");
		}	
	}


