/*
	Title:		Scripts.js
	Author:		Mike Sorrentino, Fig Leaf Software
	Date:		1/2/04

	Purpose:	This file contains all JavaScript functions and constants for the application.

*/

dayArray = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
monthArray = new Array('January','February','March','April','May','June','July','August','September','October','November','December')


var dtCh= "/";
var minYear=1900;
var maxYear=2100;

//This function will display the date on the page.
function presentDate(){
	today = new Date();
	document.write(dayArray[today.getDay()]);
	document.write(", ");
	document.write(monthArray[today.getMonth()]);
	document.write(" ");
	document.write(today.getDate());
	document.write(", ");
	document.write(today.getYear());
	}
	
function whatSearched(){
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for (i=0; i < pairs.length; i++){
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
		}
	return args;
	}

//This function adds a bookmark to the favorites of the IE browser
function addBookmark(bookmarkurl,bookmarktitle){
	if (document.all) window.external.AddFavorite(bookmarkurl,bookmarktitle);
}

//This function will call the calendar pop up
function callCalendar(path,formField)
{
		calendarFormField = formField;
		window.open(path + 'calendar.aspx','ca','width=228,height=175');
	}
		
//This function will move a selected item to the destination list
function moveSelectOption(from, to,type) {
	
	//validate that the from is highlighted
	if (from.selectedIndex == -1) {
		alert("Please select " + type);
		return false;
	}
	
	//Increase the length of the to box
	to.length++;
	
	//set the value of the new index to the selected value in the from
	to[to.length-1].value = from[from.selectedIndex].value;
	to[to.length-1].text = from[from.selectedIndex].text;
	
	//now, kill the array index that held the value in the from box
	from[from.selectedIndex] = null;
}

//Send the user to the delete notice page.
function DeleteNotice(noticeID) {
	if(confirm("Click OK to delete this notice. This action cannot be undone")) {
		document.location.href = "deletenotice.aspx?noticeID=" + noticeID;
	}
}


//This function will check for a required function
function requiredCheck(formobj,fields,labels){
	// Enter name of mandatory fields
	var fieldRequired = fields.split(',');
	
	// Enter field description to appear in the dialog box
	var fieldDescription = labels.split(',');
	
	// dialog message
	var alertMsg = "Please enter ";
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			bError = false;
			
			switch(obj.type){
				case "select-one":
					if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == "" || obj.options[obj.selectedIndex].value == "0"){
						bError = true;
					}
					break;
				case "select-multiple":
					if (obj.selectedIndex == -1){
						bError = true;
					}
					break;
				case "text":
				case "password":
				case "textarea":
					if (obj.value == "" || obj.value == null){
						bError = true;
					}
					break;
				default:
					break;
				
				
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					bError = true;
				}
			}
			
			//if the error flag was set, then tell the user and bail out
			if(bError){
				alertMsg += fieldDescription[i] + ".";
				alert(alertMsg);
				obj.focus();
				if(obj.type != "select-one") obj.select();
				return false;
			}	
		}
	}

	return true;
}

//Obvious
function checkEmailAddress(field) {

	var goodEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);

	if (!goodEmail){
		alert('Please enter a valid e-mail address.');
		field.focus();
		field.select();
		return false;
	}
	
	return true;
}

//This function will check for a required function
function checkNumber(formobj,fields,labels){
	// Enter name of mandatory fields
	var fieldRequired = fields.split(',');
	
	// Enter field description to appear in the dialog box
	var fieldDescription = labels.split(',');
	
	// dialog message
	var alertMsg = "";
		
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			bError = false;
			if (!isNaN(parseInt(obj.value))){
				bError = true;
			}
		}
			
		//if the error flag was set, then tell the user and bail out
		if(bError){
			alertMsg += fieldDescription[i] + " must be numeric.";
			alert(alertMsg);
			obj.focus()
			obj.select()
			return false;
		}	
	}

	return true;
}

//This function will check for a date
function checkDate(formobj,fields,labels){
	// Enter name of mandatory fields
	var fieldRequired = fields.split(',');
	
	// Enter field description to appear in the dialog box
	var fieldDescription = labels.split(',');
	
	// dialog message
	var alertMsg = "";
		
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			bError = false;
			if(obj.value.length > 0){
				if (!isDate(obj.value)){
					bError = true;
				}
			}
		}
			
		//if the error flag was set, then tell the user and bail out
		if(bError){
			obj.focus()
			obj.select()
			return false;
		}	
	}

	return true;
}

//System function. Do not call directly.
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;
}

//System function. Do not call directly.
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;
}

//System function. Do not call directly.
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 );
}

//System function. Do not call directly.
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
}

//This function will determine the if the input is a valid date but do NOT call this directly.  CALL CHECKDATE above
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){
		return false
	}
return true
}

//This function  will verify that the input date is two days from today. If not, an error will display and the function will return false.
function checkDayNumber(e){

	var t = new Date();	
		
	var myday = parseInt(t.getDate()) + 2;
	var mymonth = parseInt(t.getMonth()) + 1;
	var myyear = parseInt(t.getYear());

	var theDate = e.value;
	aDate = theDate.split('/');
	
	var checkMonth = parseInt(aDate[0]);
	var checkDay = parseInt(aDate[1]);
	var checkYear = parseInt(aDate[2]);
	
	var IsValid = true;
	
	//Check the year first
	if (checkYear >= myyear){
		//Check the month
		if(checkMonth > mymonth){
			IsValid = true;
		} else if(checkMonth == mymonth) {
			//check the day
			if(checkDay >= myday){
				IsValid = true;
			} else {
				IsValid = false;
			}
		} else {
			IsValid = false;
		}
	} else {
		IsValid = false;
	}
	
	if(!IsValid) {
		alert("The posting date must be at least two days from today.");
		return false;
	}
	
	return true;
}
	
//This function will set the geo and state and county vars in .net
function test(stateID,countyID){
	document.login.hiddenCountyID.value = countyID;
	document.login.hiddenStateID.value = stateID;
	document.login.submit();
}

//This function will ensure that the first input date is smaller than the second
function compareDates(lower,higher){
	if(lower.length > 0){
		var higherDate = higher.value;
		var aHigherDate = higherDate.split('/');
		
		var highMonth = parseInt(aHigherDate[0]);
		var highDay = parseInt(aHigherDate[1]);
		var highYear = parseInt(aHigherDate[2]);

		var lowerDate = lower.value;
		var aLowerDate = lowerDate.split('/');
		
		var lowMonth = parseInt(aLowerDate[0]);
		var lowDay = parseInt(aLowerDate[1]);
		var lowYear = parseInt(aLowerDate[2]);
		
		var IsValid = true;
		
		//Check the year first
		if (highYear > lowYear){
			IsValid = true;
		} else if(highYear = lowYear){
			
			//Check the month
			if(highMonth > lowMonth){
				IsValid = true;
			} else if(highMonth == lowMonth) {
				//check the day
				if(highDay >= lowDay){
					IsValid = true;
				} else {
					IsValid = false;
				}
			} else {
				IsValid = false;
			}
		} else {
			IsValid = false;
		}
		
		if(!IsValid) {
			alert("The posting date cannot be later than the expiration date.");
			return false;
		}
	}
	return true;
	
}

//This function handles the select all for checkboxes.
function swapCheckboxes(inputVal,boxType)
{
	thisForm = document.login;
	
	//Loop through all fiels to look for the checkboxes
	for(var i=0; i < thisForm.length; i++)
	{
		var testVal = "";
		
		//if we have a checkbox, take the string and separate the name at the :.  In .net this will get us to the name of the Web Control
		if(thisForm[i].type == "checkbox")
		{
			testVal = thisForm[i].name.split(':');
			
			//if the web control name is = to the type asked for (bold, featured) the set that form control to checked.
			if(testVal[2] == boxType)
			{
				
				//Check the value of the input checkbox control
				if(inputVal)
				{
					thisForm[i].checked = true;
				}
				else 
				{
					thisForm[i].checked = false;
				}
			}
		}
	}
}

//THis function will check a single textbox control value. We use this for the textboxes inside user controls because of the weird .net syntax with the colon in the name
function checkUCRequiredVal(obj,msg)
{
	if(obj.value == "" || obj.value == null)
	{
		alert("Please enter " + msg + ".");
		obj.focus();
		obj.select();
		return false;
	}
	return true;
}

function checkUCNumber(obj,msg)
{
	if(isNaN(parseInt(obj.value)))
	{
		alert("Please enter " + msg + ".");
		obj.focus();
		obj.select();
		return false;
	}
	
	return true;
}
