// Global JavaScript Document

// Declare variables
var browserName = navigator.appName; 
var browserVer = parseInt(navigator.appVersion);
var win = null;

// Define string prototypes
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.toInteger = function() { return (isNaN(this)) ? 0 : parseInt(this); };
String.prototype.toCurrency = function() { 
	num = this;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) return "0.00";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	return num + "." + cents;
};
String.prototype.padLeft = function(len) {
	var char = "0";
	var str = this;
	if (arguments > 1) char = arguments[1];
	for (var x = 0; x < len; x ++) str = char + str + '';
	return str;
};
String.prototype.padRight = function(len) {
	var char = "0";
	var str = this;
	if (arguments > 1) char = arguments[1];
	for (var x = 0; x < len; x ++) str += char + '';
	return str;
};
String.prototype.toDate = function() {
	var val = this.replace(/[-.]/g, "/");
	var tmp = Date.parse(val);
	if (isNaN(tmp)) return this;
	else {
		var yearDigits = (val.match(/\/[0-9]{2}$/) != null) ? 2 : 4;
		d = new Date(tmp);
		if (d.getFullYear() < '1950' && yearDigits == 2) d.setFullYear(d.getFullYear() + 100);
		return parseInt(d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
	}
};

// Set up object for AJAX requests
var request = setupNewAjaxRequest();

function setupNewAjaxRequest() {
	var request = null;
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = null;
			}
		}
	}
	return request;
}

function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

// Selects or deselects all checkboxes in a given conainer
function selectAll(cont, bool) {
	var obj = document.getElementById(cont);
	if (obj) {
		var elem = obj.getElementsByTagName("input");
		for(var x = 0; x < elem.length; x++) {
			if (elem[x].type == 'checkbox') elem[x].checked = bool;
		}
	}
}

// Enables or disables all checkboxes in a given conainer
function disableAll(cont, bool) {
	var obj = document.getElementById(cont);
	if (obj) {
		var elem = obj.getElementsByTagName("input");
		for(var x = 0; x < elem.length; x++) {
			if (elem[x].type == 'checkbox') elem[x].disabled = bool;
		}
	}
}

// Sets the CSS class property of a document element
function setElementCssClass(elem_name, class_name) {
	var obj = document.getElementById(elem_name);
	if (obj) obj.className = class_name;
}

// Displays and hides the loader progress wheel
function showLoader(val) {
	var id = (arguments.length > 1) ? arguments[1] : "progresswheel";
	var progress = document.getElementById(id);
	if (progress) progress.style.visibility = (val) ? 'visible' : 'hidden';
}

// Function for click confirmation
function clickConfirm(theMessage) {
	if (confirm(theMessage)) return true;
	else return false;
}

// Determine the difference between two dates
function DateDiff(start, end, interval, rounding ) {
    var iOut = 0;
    
    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Please enter a valid date.";
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'y': case 'Y': 
            iOut = parseInt(number / 31536000000) ;
            if(rounding) iOut += parseInt((number % 31536000000)/43200001) ;
            break ;
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    return iOut ;
}

// Gets the text from an element
function getText(el) {
	var text = "";
	if (el != null) {
		if (el.childNodes) {
			for (var i=0; i < el.childNodes.length; i++) if (el.childNodes[i].nodeValue != null) text = text + el.childNodes[i].nodeValue;
		}
	}
	return text;
}

// Returns the value of an XML node
function getXMLValue(node) {
	return (node && node.firstChild) ? node.firstChild.nodeValue : ""
}

// Sets up image rollovers
function setupRollovers() {
	var baseURL = getBaseURL();
	// Get all of the images on this page and iterate through them to determine if any are rollovers
	var pageImages = document.getElementsByTagName("img");
	for (var x = 0; x < pageImages.length; x++) {
		// Get the base name of the current image
		var tmparr1 = pageImages[x].src.split('/');
		var tmparr2 = tmparr1[tmparr1.length - 1].split('.');
		var imgname = tmparr2[0];
		// Check the current image name against the list of rollovers and see if there is a match
		for (var i = 0; i < rolloverImages.length; i++) {
			if (imgname == rolloverImages[i]) {
				// Preload rollover image
				var normalURL = baseURL + 'images/buttons/' + imgname + '.gif';
				var rolloverURL = baseURL + 'images/buttons/' + imgname + '_on.gif';
				(new Image()).src = rolloverURL;
				// Setup rollover events
				addRollover(pageImages[x], normalURL, rolloverURL);
				// Exit the loop
				break;
			}
		}
	}
	// Get all of the image buttons on this page and iterate through them to determine if any are rollovers
	var inputElements = document.getElementsByTagName("input");
	for (var x = 0; x < inputElements.length; x++) {
		if (inputElements[x].getAttribute("type") == "image") {
			// Get the base name of the current image
			var tmparr1 = inputElements[x].src.split('/');
			var tmparr2 = tmparr1[tmparr1.length - 1].split('.');
			var imgname = tmparr2[0];
			// Check the current image name against the list of rollovers and see if there is a match
			for (var i = 0; i < rolloverImages.length; i++) {
				if (imgname == rolloverImages[i]) {
					// Preload rollover image
					var normalURL = baseURL + 'images/buttons/' + imgname + '.gif';
					var rolloverURL = baseURL + 'images/buttons/' + imgname + '_on.gif';
					(new Image()).src = rolloverURL;
					// Setup rollover events
					addRollover(inputElements[x], normalURL, rolloverURL);
					// Exit the loop
					break;
				}
			}
		}
	}
}

// Image button rollover handler
function addRollover(img, normalURL, rolloverURL) {
	img.onmouseover = function() { img.src = rolloverURL; }
	img.onmouseout = function() { img.src = normalURL; }
}

// Creates rollover highlights for data table rows
function setupTableRollovers() {
	var tables = document.getElementsByTagName("table");
	for (var x=0; x < tables.length; x++) {
		if (tables[x].className == "tablelist") {
			var rows = document.getElementsByTagName("tr");
			for (var i=0; i < rows.length; i++) {
				if (rows[i].className == "item" && rows[i].getAttribute("url")) {
					rows[i].onmouseover = function() { this.className = "item-selected"; }
					rows[i].onmouseout = function() { this.className = "item"; }
				} else if (rows[i].className == "item-alt" && rows[i].getAttribute("url")) {
					rows[i].onmouseover = function() { this.className = "item-selected"; }
					rows[i].onmouseout = function() { this.className = "item-alt"; }
				}
			}
		}
	}
}

// Focuses the cursor on the first form element
function cursorFocus() {
	var focused = false;
	if (document.login) {
		// Determine cursor focus for the login form
		if (document.login.User.value.length==0) document.login.User.focus();
		else document.login.Pass.focus();
	} else if (document.forms.length > 0) {
		// Iterate through each form
		for (var x = 0; x < document.forms.length; x++) {
			if (focused) break;
			var form = document.forms[x];
			// Iterate through each document element to find a text or drop-down field
			for (var n = 0; n < form.elements.length; n++) {
				var element = form.elements[n];
				if (element.disabled || element.readOnly) continue;
				if (element.type == 'text' || element.type == 'textarea' || element.type == 'password') {
					element.select();
					focused = true;
					break;
				} else if (element.type == 'file' || element.type == 'select-one' || element.type == 'select-multiple') {
					element.focus();
					focused = true;
					break;
				}
			}
		}
	}
}

// Runs globally during onload handler
function globalLoad() {
	preloadImages('/images/interface/nav_services_f2.jpg',
				  '/images/interface/nav_hosting_f2.jpg',
				  '/images/interface/nav_support_f2.jpg',
				  '/images/interface/nav_about_f2.jpg',
				  '/images/interface/nav_portfolio_f2.jpg',
				  '/images/interface/nav_resources_f2.jpg');
}

if (window.addEventListener) window.addEventListener("load", globalLoad, false);
else if (window.attachEvent) window.attachEvent("onload", globalLoad);