///////////////////////////////////////////////////////////////
// File Name: 	public.js
///////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////
// Shared javascript functions for public site
///////////////////////////////////////////////////////////////

// Get element by id.  Handle controls using master pages.
function getEl(id) {
    if (document.getElementById(id)) {
        return document.getElementById(id);
    } else if (document.getElementById("ctl00_main_" + id)) {
        return document.getElementById("ctl00_main_" + id);
    } else if (document.getElementById("ctl00_ctl00_main_main_" + id)) {
        return document.getElementById("ctl00_ctl00_main_main_" + id);
    } else if (document.getElementById("_ctl0_main_" + id)) {
        return document.getElementById("_ctl0_main_" + id);
    } else if (document.getElementById("_ctl0_ctl0_main_main_" + id)) {
        return document.getElementById("_ctl0_ctl0_main_main_" + id);
    } else if ($("*[id$=" + id + "]").length > 0) {
        return $("*[id$=" + id + "]")[0];
    }
}

//Get an element by control id
//Matches elements with an id that ends in the given id, to match controls within controls
function getControl(tagName,id,parent) {
    if (!parent) parent = document;
    var els = parent.getElementsByTagName(tagName);
    for (var i=0; i < els.length; i++) {
        if (els[i].id.search(id + "$") > -1) {
            return els[i];
        }
    }
    return null;
}
function findControl(id,tagName){
    return getControl(tagName,id);
}

/////////////////////////////////////
// popupWindows
/////////////////////////////////////
function popupWindow2(windowName,options) {
    try {
        eval("var " + windowName + " = window.open('','" + windowName + "','" + options + "')");
        eval(windowName + ".focus()");
    } catch (e) {  }  // this seems to be an issue with IE9}
	return eval(windowName);
}
function popupDialog(windowName,width,height,options) {
	if (options == null) options = "status=no,toolbar=no,menubar=no,location=no";
	var top = (screen.availHeight - height) / 2;
	var left = (screen.availWidth - width) / 2;
	options = "height=" + height + ",width=" + width + ",top=" + top + ",left=" + left + "," + options;
	return popupWindow2(windowName,options);
}

function xAddEvent(obj, name, handler) {
	if (obj.attachEvent) {
		obj.attachEvent("on" + name, handler);
	} else {
		obj.addEventListener(name, handler, false);
	}
}
function xGetEventSrcElement(e) {
	if (window.event) {
		return window.event.srcElement;
	} else if (e && e.currentTarget) {
		return e.currentTarget;
	}
}

function generate_address(username,hostname,name) {
	var atsign = "&#64;";
	var linktext = username + atsign + hostname;
	document.write("<a href=" + "mail" + "to:" + username + atsign + hostname + ">")
	if (name != null) {
		document.write(name)
	} else {
		document.write(username + atsign + hostname)
	}

	document.write("</a>")
}

function formatAsMoney(mnt) {
	mnt -= 0;
	mnt = (Math.round(mnt*100))/100;
	return (mnt == Math.floor(mnt)) ? mnt + '.00'
			  : ( (mnt*10 == Math.floor(mnt*10)) ?
					   mnt + '0' : mnt);
}

function selectValue(selectObj,value) {
	for (var i=0; i < selectObj.options.length; i++) {
		if (selectObj.options[i].value==value) {
			selectObj.selectedIndex = i;
			break;
		}
	}
}

// This is contained in the janus.js file as well but we don't want to have to include janus.js in the front end pages
// Validate extension for file name
// Checks to be sure that the file extension is in the given list.
// To use, set the following parameters in the CustomValidator:
// 	extensions - a comma separated list of valid extensions
function ValidateExtension(source, arguments) {
	success = true;

	var extensions = source.getAttribute("extensions").toLowerCase().split(",");
	var extension = "";

	if (arguments.Value != "") {
		if (arguments.Value.lastIndexOf(".") == -1) {
			success = false;
		} else {
			extension = arguments.Value.substring(arguments.Value.lastIndexOf("."),arguments.Value.length).toLowerCase();

			var foundExt = false;
			for (var i = 0; i < extensions.length; i ++) {
				if (extension == extensions[i]) {
					foundExt = true;
					break;
				}
			}
			if (!foundExt) {
				success = false;
			}
		}
	}

	arguments.IsValid = success;
}
// This is contained in the janus.js file as well but we don't want to have to include janus.js in the front end pages
// Validate prefix
// Checks to be sure that the value begins with particular characters.
// To use, set the following parameters in the CustomValidator:
// 	prefixes - a comma separated list of valid prefixes
function ValidatePrefix(source, arguments) {
    success = true;

    var prefixes = source.getAttribute("prefixes").toLowerCase().split(",");

    if (arguments.Value != "") {
        var foundPrefix = false;
        for (var i = 0; i < prefixes.length; i++) {
            if (arguments.Value.indexOf(prefixes[i]) == 0) {
                foundPrefix = true;
                break;
            }
        }
        if (!foundPrefix) {
            success = false;
        }
    }

    arguments.IsValid = success;
}

//Add nbsp to empty cells so that their borders show
function fillEmptyCells() {
    var tds = document.getElementsByTagName("TD");
    for (var i=0; i < tds.length; i++) {
        if (tds[i].innerHTML.search(/[^\s]/) == -1) {
            tds[i].innerHTML = "&nbsp;";
        }
    }
}

/*Even out the bottom borders of boxes in the same row*/
function evenBoxes(){
    var s,bottom,height,max = 0;
    $.each(arguments, function() {
        s = "" + this;
        if (s != null && s != "undefined" && $(s).offset() != null) {
            bottom = $(s).offset().top + $(s).outerHeight();
            if (bottom > max) {
                max = bottom;
            } 
        }
    })
    $.each(arguments, function() {
        s = "" + this;
        if (s != null && s != "undefined" && $(s).offset() != null) {
            bottom = $(s).offset().top + $(s).outerHeight();
            if (bottom < max) {
                if ($(s).get(0) && $(s).get(0).tagName == "IMG") {
                    $(s).css({ "margin-top": (max - bottom) + "px" })
                } else {
                    $(s).height($(s).height() + max - bottom);
                }
            }
        }
    })
}

// Count down the number of remaining characters and write it to a span tag specified
// we expect the span tag just to be the id as a string
function countdownTextbox(txt,span,maxlength) {
	var spanTag;

	spanTag = getEl(span);

	if (txt==null) return;
	if (spanTag==null) return;
	if (maxlength==0) return;

	var remain;
	remain = (maxlength - txt.value.length);
	if (remain==1)
		spanTag.innerHTML = remain + ' character remaining<br>';
	else
		spanTag.innerHTML = remain + ' characters remaining<br>';
}

function limitTextLength(field, maxLength) {
    if (field.value.length > maxLength) {
        field.value = field.value.substring(0, maxLength);
    }
}



function clearSpanTag(span) {
    var spanTag;

    spanTag = getEl(span);
    if (spanTag == null) return;
    spanTag.innerHTML = '';
}


// Validate number of items checked for checkboxgroup
// To use, set the following parameters in the CustomValidator:
// 	CheckBoxList - the name of the checkboxlist which will prefix each checkbox id
//	minChecked - the minimum number of options to be checked
//	maxChecked - the maximum number of options to be checked
function ValidateNumChecked(source, arguments) {
	success = true;

	// get attributes

	checkBoxList = source.getAttribute("CheckBoxList")
	minChecked = source.getAttribute("MinChecked")
	maxChecked = source.getAttribute("MaxChecked")

    // get the checkbox table that holds the list
    checkTable = getEl(checkBoxList);

    if (checkTable != null)
    {
	    // get all input elements
	    allInputElements = document.getElementsByTagName("INPUT")
	    numChecked = 0;

	    // loop through all input elements and count checked

	    for (i = 0; i < allInputElements.length; i++) {
		    if (allInputElements[i].id.indexOf(checkTable.id) == 0) {
			    if (allInputElements[i].checked) {
				    numChecked ++;
			    }
		    }
	    }

	    // Make sure the number checked is valid
	    if (numChecked < minChecked || numChecked > maxChecked) {

		    success = false;
	    }
	}
	arguments.IsValid = success;
}

// This function replaces extended unicode characters that sometimes do not print correctly when exporting to Excel
// These include the em-dash, en-dash, left quote, right quote, etc
function replacedExtendedChars(s) {

    var retString;
    var re;

    retString = s;

    // em-dash and en-dash replaced with a hyphen
    re = new RegExp("[\u2013]|[\u2014]", "g");
    retString = retString.replace(re, "-");

    // left and right quote replaced with '
    re = new RegExp("[\u2018]|[\u2019]", "g");
    retString = retString.replace(re, "'");

    // left and right double quote with "
    re = new RegExp("[\u201C]|[\u201D]", "g");
    retString = retString.replace(re, "\"");

    return retString;
}

// Date
// To use, set the following parameters in the CustomValidator:
// 	ControlToValidate
function ValidateDate(source, arguments) {
    //checks to see if the date is valid
    success = true;

    if (!isDate(arguments.Value)) {
        success = false;
        getEl(source.getAttribute("controltovalidate") || eval(source.id).controltovalidate).select();
    }

    arguments.IsValid = success;
}

///////////////////////////////////////////////////////////////
// Utility functions
///////////////////////////////////////////////////////////////

function isDate(dtStr) {
    //checks to see if the string passed in is a valid date
    var dtCh = "/";
    var minYear = 1900;
    var maxYear = 2100;

    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 (month < 1 || month > 12) {
        return false
    }
    if (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 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 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 formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt * 100)) / 100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00'
			  : ((mnt * 10 == Math.floor(mnt * 10)) ?
					   mnt + '0' : mnt);
}

function round(n, d) {
    return Math.round(n * Math.pow(10, d)) / Math.pow(10, d);
}

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 fireButton(target) {
    var defaultButton;
    if (__nonMSDOMBrowser) {
        defaultButton = document.getElementById(target);
    }
    else {
        defaultButton = document.all[target];
    }
    if (defaultButton && typeof (defaultButton.click) != "undefined") {
        defaultButton.click();
        event.cancelBubble = true;
        if (event.stopPropagation) event.stopPropagation();
        return false;
    }
    return true;
}

function scrollToElement(theElement) {
    var selectedPosX = 0;
    var selectedPosY = 0;
    while (theElement != null) {
        selectedPosX += theElement.offsetLeft;
        selectedPosY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }

    window.scrollTo(selectedPosX, selectedPosY);
}
