﻿// ## UTILS

Utils = { };

Utils.isMSIE = (navigator.userAgent.indexOf("MSIE") > -1) ? true : false;
Utils.isMSIE6 = (navigator.userAgent.indexOf("MSIE 6") > -1) ? true : false;
Utils.WebsiteURL = "";
Utils.SetDefaultText = function(itemID) {
	var item = $(itemID);

	if (item.type == "text" && item.title != null && item.title != '') {
		item.addEvent("focus", Utils.DefaultTextFocus);
		item.addEvent("blur", Utils.DefaultTextBlur);

		item.value = item.title;
	}
}

Utils.DefaultTextFocus = function() {
    if (this.title == this.value) { this.value = ''; }
}

Utils.DefaultTextBlur = function() {
    if (this.value == '') { this.value = this.title; }
}

// Since IE fails at applying a background to a table row.
Utils.AdjustTableCellBackground = function(tableID) {
	if (Utils.isMSIE) {
		var rows = $(tableID).getElements("TR.adjustCellBG");
		
		rows.each(function(row) {
			var width = 0;
			var cells = row.getElements("TD");
			
			cells.each(function(cell) {
				$(cell).setStyle("background-position", "-" + width + "px 0px");
				
				width += cell.getWidth();
			});
		});
	}
}

Utils.OnLoad = function(func) {
	var previous = window.onload;
	
	window.onload = function(e) {
		if (previous != null) { previous(e); }
		func(e);
	}
}

Utils.OnScroll = function(func) {
	var previous = window.onscroll;
	
	window.onscroll = function(e) {
		if (previous != null) { previous(e); }
		func(e);
	}
}

// Joins two collections.
Utils.Concat = function(a, b) {
	for (var i = 0, node; node = b[i]; i++) {
		a.push(node);
	}
	
	return a;
}

// Due to NET using a single panel for all panels, this makes certain the correct panel is submitted
// by determining the panel object that has focus and submitting the panel by clicking the first button
// found after the user presses the enter key.
Utils.SubmitByCorrectButton =  function(e) {
	try {
		var caller = Utils.GetEventCaller(e);
	    
		if (Utils.GetEventKeyCode(e) == 13 && caller.type.toLowerCase() != "textarea") {
			var elements    = $('aspnetForm').getElementsBySelector('SELECT', 'INPUT');
			var callerFound = false;
	        
			for (var i = 0; i < elements.length; i++) {
				var element = elements[i];
				var type    = element.readAttribute("type");
	        
				if (element.id == caller.id) { callerFound = true; }
				if (type)                    { type        = type.toLowerCase(); }
	            
				if (callerFound && (type == "image" || type == "submit")) {
					buttonNotClicked = false;
					element.click();
					break;
				}
			}
	        
			return false;
		}
	} catch (ex) { }
    
    return true;
}

Utils.GetEventKeyCode = function(e) {
    if (window.event) {
        return e.keyCode;
    } else if (e.which) {
        return e.which;
    }
}

Utils.GetEventCaller = function(e) {
    if (window.event) {
        return e.srcElement;
    } else if (e.which) {
        return e.target;
    }
}

Utils.Clone = function(original) {
	var copy = { };
		
	if ($type(original) == "array") {
		copy = new Array();
	}
	
	if ($type(original) == "object") {
		for (var item in original) {
			copy[item] = Utils.Clone(original[item]);
		}
		
	} else if ( $type(original) == "array") {
		for (var i = 0; i < original.length; i++) {
			copy[i] = Utils.Clone(original[i]);
		}
		
	} else if ($type(original) == "element") {
		copy = original.clone();
	
	} else {
		copy = original;
	}
    
    return copy;
}

Utils.Copy = function(from, to) {
	$extend(to, from);	
    return to;
}

Utils.ParseNETDate = function(string) {
	var year = string.substring(0, 4);
	var month = string.substring(5, 7);
	var day = string.substring(8, 10);
	var hour = string.substring(11, 13);
	var minute = string.substring(14, 16);
	var second = string.substring(17, 19);
	
	if (month.indexOf("0") == 0) {
		month = month.substring(1, 2);
	}
	
	month = parseInt(month) - 1;
	
	return new Date(year, month, day, hour, minute, second);
}

Utils.StripCurrency = function(str) {
    str = str + "";
    
    str = str.replace(/\$/g, "");
    str = str.replace(/ /g, "");
    str = str.replace(/,/g, "");
    
    return str;
}

Utils.FormatNumberCommas = function(nStr) {
	nStr += '';
	
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	
	return x1 + x2;
}

// Rounds number to x decimal places, defaults to 2.
Utils.Round = function(number, x) {
    x = (!x ? 2 : x);
    return Math.round(number * Math.pow(10, x)) / Math.pow(10, x);
}

try {
	if (console == null) { }
} catch(ex) {
	console = { };
	console.log = function(str) {
		if (str == null) { str = ""; }
		$("console").innerHTML += ("<p>" + str + "</p>");
	}
}


// ## OVERLAY

Overlay = { };

Overlay.BACKDROP_ID = "OverlayBackdrop";
Overlay.OPEN_OVERLAY = null;

Overlay.OpenWindow = function(id, showBackdrop) {
	if (showBackdrop == null) { showBackdrop = true; }
	if (showBackdrop) { Overlay.ShowBackdrop(); }
	Overlay.SetupOverlay(id);	
	Overlay.OPEN_OVERLAY = id;
}

Overlay.OpenWindowVariable = function(id) {
	var container = $(id);
	Overlay.OpenWindow(id);

	if (!container.SetupComplete) {
		var content = container.getElement(".popupBody");
		
		var bodyHeight = $(document.body).getHeight().toInt();
		var contentHeight = content.getHeight().toInt();

		if (contentHeight > bodyHeight - 200) {
			content.setStyle("height", (bodyHeight - 200) + "px");
			content.setStyle("overflow", "auto");
		}

		container.SetupComplete = true;
	}

	// Adjust the position and so forth as heights don't get calculated properly until all of the objects are visible.
	Overlay.AdjustPosition(id);
}

Overlay.CloseWindow = function() {
	Overlay.HideBackdrop();
	
	if (Overlay.OPEN_OVERLAY) {
		$(Overlay.OPEN_OVERLAY).setStyle("display", "none");
	}
}

Overlay.SetupOverlay = function(id) {
	var container = $(Overlay.BACKDROP_ID);
	var overlay = $(id);
	
	if (container == null) {
		container = $(document.body);
	}

	if (!overlay.Setup) {
		overlay.inject(container);
		overlay.addClass("Overlay");
		
		overlay.Setup = true;
	}
	
	overlay.setStyle("display", "block");
	Overlay.AdjustPosition(id);
}

Overlay.AdjustPosition = function(id) {
	var container = $(Overlay.BACKDROP_ID);
	var overlay = $(id);
	
	if (container == null) {
		container = $(document.body);
	}

	// Position in the middle of the container.
	var containerHeight = container.getHeight().toInt();
	var overlayHeight = overlay.getHeight().toInt();
	var positionTop = Math.ceil(containerHeight / 2) - Math.ceil(overlayHeight / 2);
	
	overlay.setStyle("margin-top", positionTop + "px");
}

Overlay.ShowBackdrop = function() {
	var backdropContainer = Overlay.SetupBackdrop();
	backdropContainer.setStyle("display", "block");
}

Overlay.HideBackdrop = function() {
	var backdropContainer = $(Overlay.BACKDROP_ID + "Container");
	
	if (backdropContainer) {
		backdropContainer.setStyle("display", "none");
	}
}

Overlay.SetupBackdrop = function() {
	var body = $(document.body);
	
	var backdrop = $(Overlay.BACKDROP_ID);
	var backdropContainer = $(Overlay.BACKDROP_ID + "Container");
	if (backdrop == null)			{ backdrop				= new Element('div', { id: Overlay.BACKDROP_ID }); }
	if (backdropContainer == null)	{ backdropContainer		= new Element('div', { id: Overlay.BACKDROP_ID + 'Container', style: 'display: none;' }); }
	
	backdrop.inject(backdropContainer);
	backdropContainer.inject(body);
	
	// If this is MSIE6, then we will have to adjust the position of the backdrop using JavaScript.
	if (Utils.isMSIE6) {
		backdropContainer.interval = setInterval("Overlay.AdjustBackdropPosition();", 10);
	}
	
	return backdropContainer;
}

Overlay.AdjustBackdropPosition = function() {
	var backdropContainer = $(Overlay.BACKDROP_ID + "Container");
	
	backdropContainer.setStyle("top", (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px");
	backdropContainer.setStyle("left", (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px");
}

// ## LOGIN

Login = { };
	
Login.ShowControl = function(message) {
	if (message != null && message != "") {
		$('LoginControlMessage').addClass("error");
		$('LoginControlMessage').innerHTML = message;
	}
	
	Overlay.OpenWindow('LoginControl');
}

Login.ShowControlRedirect = function(message, path, limitedAccess) {
	$('redirectPath').value = path;
	$('limitedAccess').value = limitedAccess;
	Login.ShowControl(message);
}


Login.NoAccess = function(message) {
	if (message != null && message != "") {
		$('NoAccessControlMessage').innerHTML = message;
	}
	
	Overlay.OpenWindow('NoAccessControl');
}
// ## HELP

Help = { };

Help.ShowControl = function(id) {
	var control = $(id);
	var container = $('HelpPopupContent');

	if (container.Current) {
		container.Current.setStyle("display", "none");
		container.Current.inject($('outerContainer'));
		
		container.Current = null;
	}
	
	container.Current = control;
	control.inject(container);	
	
	control.setStyle("display", "block");
	Overlay.OpenWindow('HelpPopup');

	if (!container.SetupComplete) {
		var bodyHeight = $(document.body).getHeight().toInt();
		var containerHeight = container.getHeight().toInt();
		
		if (containerHeight > bodyHeight - 200) {
			container.setStyle("height", (bodyHeight - 200) + "px");
			container.setStyle("overflow", "auto");
		}

		container.SetupComplete = true;
	}
	
	// Adjust the position and so forth as heights don't get calculated properly until all of the objects are visible.
	Overlay.AdjustPosition('HelpPopup');
}