// Validation Code for Job Entry

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

function validateSendTo  (valfield, infofield, required)
{
	var tfld = valfield.value;  // value of field with whitespace trimmed off
	
	if ( IsBlank(tfld) ) 
	{
		msg (infofield, "required", "This field can not be blank");
		return false;
	}
	
	// This field can contain the e-mail address seperated by commas so split that up and check each one
	
	var addresses = tfld.split(",")
	
	for ( var x=0; x< addresses.length; x++ )
	{
		if ( ! emailCheck(trim(addresses[x])) )
		{
			msg (infofield, "required", "Send To is in an improper e-mail format");
			return false;
		}
	}
	
	
	msg (infofield, "", "");
	return true;
}

function validateFrom  (valfield, infofield, required) 
{
	var tfld = trim(valfield.value);  // value of field with whitespace trimmed off

	if ( IsBlank(tfld) ) 
	{
		msg (infofield, "required", "This field can not be blank");
		return false;
	}

	if ( ! emailCheck(valfield.value) )
	{
		msg (infofield, "required", "From is in an improper e-mail format");
		return false;
	}
	
	msg (infofield, "", "");
	
	return true;
}

function validateSendForm(theForm)
{
    var errs=0;
    
    var elem = document.getElementById(theForm);
	
    if (!validateSendTo	(document.getElementById('SendTo'),  'msgSendTo',  true))	  errs += 1; 
    if (!validateFrom		(document.getElementById('From'),     'msgFrom',     true))  errs += 1; 
    
    if ( errs > 1 )		alert('There are fields which need correction before sending');
    if ( errs == 1)		alert('There is a field which needs correction before sending');
	
    return (errs==0);
  };

function emailCheck(emailString)
{
   valid = true;
   
   // This Regex Expression is the main one and should match most valid e-mail addresses
   var regexFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;

   // Same as above except it will match ips with brackets around them
   var regexFilter2 = /^([a-zA-Z0-9_\.\-])+\@\[(([0-9])+\.)+([0-9]{2,4})+\]$/i;
   
   // This Regex Expression is to match the not so widely used "Whatever you want"@domain.com format
   var regexFilter3 = /^\".+\"\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;

   // Same as above except it will match ips with brackets around them
   var regexFilter4 = /^\".+\"\@\[(([0-9])+\.)+([0-9]{2,4})+\]$/i;
  
   if ( emailString == "" )
   {
      valid = false;
   }
   else
   {
      // FIrst try to match it against the common e-mail address formats..
      if ( ! regexFilter.test(emailString) )
      {
         // Now check to see if it's in a non-so-common format
         if ( ! regexFilter2.test(emailString) )
         {
            if ( ! regexFilter3.test(emailString) )
            {
               if ( ! regexFilter4.test(emailString) )
               {
                  valid = false;
               }
            }
         }
      }
   }      
   
   return valid;
}

function validateRateVideoForm(theForm)
{
    var radio_choice = false;
 
    var rateform = document.getElementById(theForm);
    
    //var progtitle = document.getElementById('progTitle');
    
    //alert ('ProgTitle = '+ progtitle);
    
    for (counter=0; counter < rateform.ratebtn.length; counter++) //ratebtn is id field of each button
    {
     // If a radio button has been selected it will return true
	 // (If not it will return false)
	 //alert ('choice = ' + rateform.ratebtn[counter].value);

		if (rateform.ratebtn[counter].checked)
		{
		radio_choice = true; 
		break;   //exit once you find one that is true
		}
	}
		
	if (!radio_choice)
	{
	// If there were no selections made display an alert box 
		alert("Please select a rating.")
	}
	else
	{
		//alert ('Now Playing = ' + rateform.nowPlaying.value + ' Choice = ' + rateform.ratebtn[counter].value);
		UpdateVideoRating(rateform.nowPlaying.value, rateform.ratebtn[counter].value);
	}	
	return (radio_choice);
	
	                  
  };



//-------------------------------------- General Utility Functions---------------------------------------------  


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld, msgtype, message) 
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
 
	var dispmessage;

	if (emptyString.test(message)) 
		dispmessage = String.fromCharCode(nbsp);    
	else  
		dispmessage = message;
	
	var elem = document.getElementById(fld);
	
	elem.firstChild.nodeValue = dispmessage;  
  
	//elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

function IsBlank ( valfield )
{
	var fld = trim(valfield);
	
	if ( fld == "" )
		return true;

	return false;
}

function trim ( valfield )
{
	var tmpstr = ltrim(valfield);
	return rtrim(tmpstr);
}

function ltrim(argvalue)
{
	while (1)
	{
		if (argvalue.substring(0, 1) != " ")
			break;
		argvalue = argvalue.substring(1, argvalue.length);
	}

	return argvalue;
}

function rtrim(argvalue)
{
	while (1)
	{
		if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
			break;
		argvalue = argvalue.substring(0, argvalue.length - 1);
	}
	return argvalue;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year

var dtCh= "/";
var minYear=1900;
var maxYear=3000;

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
}

// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}