//////////////////////////////////////////////////////////
// MVC framework
//////////////////////////////////////////////////////////

var mvc_Validators = new Object();
var mvc_EnterScript = null;
document.onkeypress = mvc_onEnterKey;
var NS4 = (document.layers) ? true : false;
if(NS4) document.captureEvents(Event.KEYPRESS);

function mvc_addValidator(validateFunc, validateEvent)
{
	if (typeof validateEvent == 'undefined') {
		validateEvent = 'all';
	}

	if (typeof mvc_Validators[validateEvent] == 'undefined') {
		mvc_Validators[validateEvent] = new Array();
	}

	var validators = mvc_Validators[validateEvent];

	validators[validators.length] = validateFunc;
}

function mvc_setEnterScript(script)
{
	mvc_EnterScript = script;
}

function doValidation(validators)
{
	if (typeof validators == 'undefined') {
		return true;
	}

	for(var i = 0; i < validators.length; ++i)
	{
		var valFunc = validators[i];
		var validated = valFunc();
		if(!validated)
		{
			return false;
		}
	}
	return true;
}

function doEvent(eventName, args, skipValidation, skipGeneralValidation)
{
	var doSubmit = true;
	if (!skipValidation) {
		//call all validators for the 'all' event
		if (!skipGeneralValidation) {
		   doSubmit = doValidation(mvc_Validators['all']);
		}

		if (doSubmit) {
			var removeMVC = /mvc_Controller./;
			var newEventName = eventName.replace(removeMVC, '');

		   //call all validators for the named event
		   doSubmit = doValidation(mvc_Validators[newEventName]);
		}
	}
	if(doSubmit)
	{
		document.form.mvc_Event.value = eventName;
		document.form.mvc_Event_Args.value = args;
		document.form.submit();
	}

    return doSubmit;
}

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){
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false;
	}
	return true;
}


function isEmail(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		
		if (str.indexOf(at)==-1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

 		 return true;				
	}


function mvc_validateValue(value, facetList, message, control)
{
	var result = true;
	var splitRE = /\s*,\s*/;
	facets = facetList.split (splitRE);
	for(var i = 0; i < facets.length; ++i)
	{
		if(facets[i].charAt(0) == '=') result = eval(facets[i].substring(1));
		else if(facets[i] == "validemail") result = isEmail(value);
		else if(facets[i] == "validdate") result = isDate(value);
		else if(facets[i] == "notblank") result = !isBlank(value);
		else if(facets[i] == "numeric") result = isNumeric(value);
		else if(facets[i] == "email") result = isEmail(value);
        else if(facets[i] == "radiochecked") result = isRadioChecked(value);
        else if(facets[i] == "wholecurrency") result = isWholeCurrency(control, value);
		if(!result)
		{
			alert(message);
			if(typeof(control) != "undefined")
			{
                if (typeof(control.focus) == "function")
				   control.focus();
                else if (typeof(control[0]) != "undefined" && typeof(control[0].focus) == "function")
                     control[0].focus();
			}
			break;
		}
	}
	return result;
}

function mvc_transferOptions(from, to)
{
	for (var i = 0; i < from.length; ++i)
	{
		if (from.options[i].selected == true)
		{
			var toLen = to.length;
			to.options[toLen] = new Option(from.options[i].text);
			to.options[toLen].value = from.options[i].value;
			from.options[i] = null;
			--i;
		}
	}
}

function mvc_moveOptions(control, step)
{
	var dir = (step > 0) ? 1 : -1;
	var len = control.length;
	var start = (dir > 0) ? len - 2 : 1;
	var end = (dir > 0) ? -1 : len;

	step = Math.abs(step);
	while((step--) > 0)
	{
		for (var i = start; i != end; i -= dir)
		{
			if (control.options[i].selected == true && control.options[i + dir].selected == false)
			{
				var temp = control.options[i].text;
				control.options[i].text = control.options[i + dir].text;
				control.options[i + dir].text = temp;

				temp = control.options[i].value;
				control.options[i].value = control.options[i + dir].value;
				control.options[i + dir].value = temp;

				temp = control.options[i].selected;
				control.options[i].selected = control.options[i + dir].selected;
				control.options[i + dir].selected = temp;

			}
		}
	}
}

function mvc_optionValueArray(control)
{
	var result = "ORA:";
	for(var i = 0; i < control.length; ++i)
	{
		result += control.options[i].value;
		if(i < control.length - 1) result += "|+|";
	}
	return result;
}

//////////////////////////////////////////////////////////
// Validation functions
//////////////////////////////////////////////////////////

function isBlank(value)
{
	var result = false;
	var blankRE = /^[ \t]*$/;
	if(blankRE.test(value) || value=="OID:0") result = true;
	return result;
}

function isEmail(value)
{
	var result = false;
	var re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(re.test(value)) result = true;
	return result;
}

function isNumeric(value)
{
	return !isNaN(Number(value));
}

function isRadioChecked(control)
{
    for (var i = 0; i < control.length; ++i)
    {
        if (control[i].checked)
           return true;
    }
    return false;
}

function isWholeCurrency(control, value)
{
    var commaRE = /,/g;
    var decimalRE = /\\.[0-9]*$/;

    value = value.replace(commaRE, "");
    value = value.replace(decimalRE, "");

    if (isNumeric(value))
    {
        control.value = value;
        return true;
    }
    else
    {
        return false;
    }
}

//////////////////////////////////////////////////////////
// Control helper functions
//////////////////////////////////////////////////////////

function mvc_SelectorValue(control)
{
	return control.options[control.selectedIndex].value;
}

function mvc_onEnterKey(mvcEvent)
{
	if(typeof(event) != "undefined") mvcEvent = event;

	if(mvc_EnterScript == null) return true;

	var code = 0;

	if (NS4)
		code = mvcEvent.which;
	else
		code = mvcEvent.keyCode;

	if(code == 13)
	{
		var result = eval(mvc_EnterScript);
		if(typeof(result) == "undefined") result = false;
		return result;
	}
	else return true;
}

function mvc_getNamedWindow(name, url, width, height)
{
	return window.open(url, name, "resizable=yes" + (height != null ? (",height=" + height + ",") : "") + (width != null ? (",width=" + width) : "") + ",location=no,menubar=no,status=no,toolbar=no,scrollbars=yes");
}

function mvc_openSubWindow(url, height, width)
{
	if(height == null) height = 250;
	if(width == null) width = 350;
	var w = mvc_getNamedWindow("SubWindow", url, width, height);
	w.focus();
}
