// JavaScript Document

jQuery.noConflict(); 
jQuery(document).ready(function(){	
			jQuery('#sidemenu1').corner("5px");
			jQuery('#sidemenu2').corner("5px");
			jQuery('#sidemenu3').corner("5px");
			jQuery('#sidemenu4').corner("5px");
});


function clear_form_elements(ele) {

    jQuery(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                jQuery(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}


function SubmitForm(formid){
var myForm = document.getElementById(formid);
var SS = Spry.Widget.Form.validate(myForm);
if(SS==true){
	myForm.submit();
}
}

function loadpage(url, target) {
	target.location.href = url;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function ClearBadTxt(id,txt) {
     document.getElementById(id).value=filterNum(document.getElementById(id).value)

     function filterNum(str) {
         
		 if(txt == 1){
		  re = /\$|@|#|~|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\"|\<|\>|\?|\||\\|\!|\$|\./g;
		}else if(txt == 2){
		  re = /@|#|~|\*|\^|\&|\(|\)|\+|\=|\[|\_|\]|\[|\}|\{|\"|\<|\>|\||\\/g;
	     }else if (txt == 3){
		  re = /~|\^|\&|\+|\=|\[|\]|\[|\"|\<|\>|\||\\/g;
		}
          // remove special characters like "$" and "," etc...
          return str.replace(re, "");
     }
}


// **********************************
// BEGIN - DATE FUNCTIONS ***********
// **********************************


/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * http://blog.stevenlevithan.com/archives/date-time-format
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};




// DATEADD Function ***********************
// http://www.vbknowledgebase.com/?Id=80&Desc=Javascript-Date-functions-for-VB-DateDiff-DateAdd
function DateAdd(ItemType, DateToWorkOn, ValueToBeAdded)
{
    switch (ItemType)
    {
        //date portion        
        case 'd': //add days
            DateToWorkOn.setDate(DateToWorkOn.getDate() + ValueToBeAdded)
            break;
        case 'm': //add months
            DateToWorkOn.setMonth(DateToWorkOn.getMonth() + ValueToBeAdded)
            break;
        case 'y': //add years
            DateToWorkOn.setYear(DateToWorkOn.getFullYear() + ValueToBeAdded)
            break;
        //time portion        
        case 'h': //add hours
            DateToWorkOn.setHours(DateToWorkOn.getHours() + ValueToBeAdded)
            break;
        case 'n': //add minutes
            DateToWorkOn.setMinutes(DateToWorkOn.getMinutes() + ValueToBeAdded)
            break;
        case 's': //add seconds
            DateToWorkOn.setSeconds(DateToWorkOn.getSeconds() + ValueToBeAdded)
            break;
    }
    return DateToWorkOn;
}




// DATEDIFF Function ***********************
// http://www.vbknowledgebase.com/?Id=80&Desc=Javascript-Date-functions-for-VB-DateDiff-DateAdd
function DateDiff(IntervalType, StartDate, EndDate)
{
    var Interval = 0;
    var DevideBy = 1;
    if (EndDate < StartDate)
    {
        self.alert("StartDate can not be smaller than EndDate ");
        return Interval;
    }
    switch (IntervalType)
    {
        //date portion 
        case 'd': //add days
            DevideBy = 1000 * 60 * 60 * 24;
            Interval = EndDate - StartDate;
            Interval = Math.floor(Interval / DevideBy);
           

            break;
        case 'm': //add months
            var MonthsInFullYear = EndDate.getFullYear() - StartDate.getFullYear();
            if (MonthsInFullYear > 0)
            {
                MonthsInFullYear = (MonthsInFullYear - 1) * 12;
                Interval = EndDate.getMonth() + (12 - StartDate.getMonth());
                Interval = Interval + MonthsInFullYear
            }
            else
            {
                Interval = EndDate.getMonth() - StartDate.getMonth();
            }

            break;
        case 'y': //years
            Interval = EndDate.getFullYear() - StartDate.getFullYear();
            break;

        //time portion       
        case 'h': //days
            DevideBy = 1000 * 60 * 60;
            Interval = EndDate - StartDate;
            Interval = Math.floor(Interval / DevideBy);
            break;
        case 'n': // minutes
            DevideBy = 1000 * 60;
            Interval = EndDate - StartDate;
            Interval = Math.floor(Interval / DevideBy);
            break;
        case 's': //seconds
            DevideBy = 1000
            Interval = EndDate - StartDate;
            Interval = Math.floor(Interval / DevideBy);
            break;
    }

    return Interval;
} 

// BEGIN - DATE FUNCTIONS ***********
// **********************************


// *********************
// BEGIN - Format Phone Number
/*
FormatTelNo method takes in the current element of the form and formats the phone number 
in "(123 456-7890" format. This method should be fired on every key entry 
(using onKeyUp method) in the current element of the form. If any key other than 0 to 9 
is entered, it erases that entry rightaway. Maxlength and size of the current
element of the form should be 13.
Eg. <netui:textBox size="13" maxlength="13" onKeyUp="javascript:formatTelNo (this);" onBlur="javascript:checkTelNo (this);" onKeyDown="javascript:formatTelNo (this);"/>    
*/
function formatTelNo (telNo)
{
    // If it's blank, save yourself some trouble by doing nothing.
    if (telNo.value == "") return;

    

    var phone = new String (telNo.value);
    
    phone = phone.substring(0,14);

    /*
    "." means any character. If you try to use "(" and ")", the regular expression becomes 
    complicated sice both are reserve characters and escaping them sometimes fails. So just 
    use "." for any character and replace it later.
    */
    if (phone.match (".[0-9]{3}.[0-9]{3}-[0-9]{4}") == null)
    {
        /*
        Following "if" is for user making any changes to the formatted tel. no. If you don't put this 
        "if" condition, the user can not correct a digit by first deleting it and then entering a 
        correct one, since this will fire two "onkeyup" events : first one on deleting a 
        character and second one on entering the correct one. The first "onkeyup" event will fire this 
        function which will reformatt the tel no before the user gets a chace to correct the digit. This 
        will surely confuse the user. The "if" condition below eliminates that.
        */
        if (phone.match (".[0-9]{2}.[0-9]{3}-[0-9]{4}|" + ".[0-9].[0-9]{3}-[0-9]{4}|" +
            ".[0-9]{3}.[0-9]{2}-[0-9]{4}|" + ".[0-9]{3}.[0-9]-[0-9]{4}") == null)
        {
            /*
            You will reach here only if the user is still typing the number or if he/she has 
            messed up already formatted number. 
            */
            var phoneNumeric = phoneChar = "", i;
            // Loop thru what user has entered.
            for (i=0;i<phone.length;i++)
            {
                // Go thru what user has entered one character at a time.
                phoneChar = phone.substr (i,1);
    
                // If that character is not a number or is a White space, ignore it. Only if it is a digit, 
                // concatinate it with a number string.
                if (!isNaN (phoneChar) && (phoneChar != " ")) phoneNumeric = phoneNumeric + phoneChar;
            }
    
            phone = "";
            // At this point, you have picked up only digits from what user has entered. Loop thru it.
            for (i=0;i<phoneNumeric.length;i++)
            {
                // If it's the first digit, throw in "(" before that.
                if (i == 0) phone = phone + "(";
                // If you are on the 4th digit, put ") " before that.
                if (i == 3) phone = phone + ") ";
                // If you are on the 7th digit, insert "-" before that.
                if (i == 6) phone = phone + "-";
                // Add the digit to the phone charatcer string you are building.
                phone = phone + phoneNumeric.substr (i,1)
            }
        }
    }
    else
    { 
        // This means the tel no is in proper format. Make sure by replacing the 0th, 4th and 8th character.
        phone = "(" + phone.substring (1,4) + ") " + phone.substring (5,8) + "-" + phone.substring(9,13); 
    }
    // So far you are working internally. Refresh the screen with the re-formatted value.
    if (phone != telNo.value) telNo.value = phone;
}
// END - Format Phone Number
// *********************




// *********************
// BEGIN - Set and read Cookies
// manual set and read cookies
function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

// AUTO set and read cookies for form fields 
// Global variables.
domain		= 'hometrustusa.org';
path		= '/';
secure		= 0;

// Function to save a field.
function save_field(obj) {
	var cookie_value = '';
	var objType = new String(obj.type);
	switch(objType.toLowerCase()) {
		case "checkbox" :
			if (obj.checked) cookie_value = obj.name + '=[1]'
			else cookie_value = obj.name + '=[0]'
			break;
		case "undefined" :
			// a.k.a. radio field.
			for (var i = 0; i < obj.length; i++) {
				if (obj[i].checked) cookie_value = obj[i].name + '=[' + i + ']'
			}
			break;
		case "select-one" :
			cookie_value = obj.name + '=[' + obj.selectedIndex + ']';
			break;
		case "select-multiple" :
			cookie_value = obj.name + '=[';
			for (var i = 0; i < obj.options.length; i++) {
				if (obj.options[i].selected) cookie_value += '+' + i
			}
			cookie_value += ']';
			break;
		default :
			// We assume all other fields will have
			// a valid obj.name and obj.value
			cookie_value = obj.name + '=[' + obj.value + ']';
	}
	if (cookie_value) {
		var expires = new Date();
		expires.setYear(expires.getYear() + 1);
		document.cookie = cookie_value +
		((domain.length > 0) ? ';domain=' + domain : '') +
		((path) ? ';path=' + path : '') +
		((secure) ? ';secure' : '') +
		';expires=' + expires.toGMTString();
	}
	return 1;
}

// Function to retrieve a field.
function retrieve_field(obj) {
	var cookie = '', real_value = '';
	cookie = document.cookie;
	var objType = new String(obj.type);
	if (obj.name)
		var objName = new String(obj.name);
	else
		var objName = new String(obj[0].name);
	var offset_start = cookie.indexOf(objName + '=[');
	if (offset_start == -1) return 1;
	var offset_start_length = objName.length + 2;
	offset_start = offset_start + offset_start_length;
	var offset_end = cookie.indexOf(']', offset_start);
	real_value = cookie.substring(offset_start, offset_end);
	switch(objType.toLowerCase()) {
		case "checkbox" :
			if (real_value == '1') obj.checked = 1
			else obj.checked = 0
			break;
		case "undefined" :
			obj[real_value].checked = 1;
			break;
		case "select-one" :
			obj.selectedIndex = real_value;
			break;
		case "select-multiple" :
			for (var i = 0; i < obj.options.length; i++) {
				if ((real_value.indexOf('+' + i)) > -1)
					obj.options[i].selected = 1;
				else
					obj.options[i].selected = 0;
			}
			break;
		default :
			obj.value = real_value;
			break;
	}
	return 1;
}

// END - Set and read Cookies
// ************************