/***********************
 * framework.js
 *
 * Contains functions common across the entire framework 
 * and onReady tasks needed across the framework that
 * do not require variables.
 * 
 *
 * @author Tom Fernandez
 * $Id$
 ***********************/

var change = false;
var jQ = $;

$(document).ready(function () {
	// IE6 specific fixes here
	if($.browser.msie && $.browser.version=="6.0") 
	{
		$("input").focus(
			function () {$(this).addClass("focus");},
			function () {$(this).removeClass("focus");}	
		);
	}
	
	
	$("#menu").menu({
		content: $("#menuOps").html(),
		showSpeed : 300,
		crumbDefaultText: " ",
		flyOut: true
	});
	
	installChangeListener($(".changable"));

	$(".clrErrOnKey").live("keypress",function () {
		$(this).removeClass("ui-state-error");
	});
	$(".clrErrOnChg").live("change",function () {
		$(this).removeClass("ui-state-error");
	});	
	$(".digitOnly").live("keypress",function (e) {
		return digitOnly(e);
	});
	$(".digitOnly").live("change",function (e) {
		checkDigitOnly($(this));
	});

	$("#backToTop").click(function (e) {
		window.scrollTo(0,0);
	});

	$("ul.subMenu li[class!=activeMenuItem]").each(function () {
		$(this).hover(
		function () {
			$(this).addClass("ui-state-hover");	
		},
		function () {
			$(this).removeClass("ui-state-hover");	
		});
	});

	$("#helpDialog").dialog({
		bgiframe: true,
		show: 'fold',
		width: 800,
		height: parseInt($(window).height() * 0.9),
		autoOpen: false,
		position: ['center',40]
	});
	$(".helpLink").click(function () { 
		var theDialog = $("#helpDialog");
		var url;

		theDialog.html("<div style=\"width: 100%; text-align: center;\">"+
				"<img src=\""+FR_BASE_DIR+"/images/spinner.gif\" />"+ 
				"</div>");
		theDialog.dialog("open");
		if (FR_ACTION_NAME.length > 0)
			url = FR_BASE_DIR+"/"+FR_MODULE_NAME+"/"+FR_ACTION_NAME+"?task=help";
		else
			url = FR_BASE_DIR+"/"+FR_MODULE_NAME+"?task=help";
		theDialog.load(url,{});
	});
	
	// Check for change before leaving the screen on all anchors 
	// and other elements with checkChgB4Exit class
	$("a").live("click",function(){
		return checkChangeBeforeExit($(this).attr("href"));
	});
	$(".checkChgB4Exit").live("click",function(){
		return checkChangeBeforeExit($(this).attr("href"));
	});
	
	$("#logoutLink").click(function () {
		$("#logoutForm").submit();
	});
	$("#searchLink").click(function () {
		$("#loginInfoBox").hide();
		$("#gSearchBox").show();
		$("#gSearchField").focus();
	});
	
	$("button").button();
	
});


/**
 * Install change listeners on objects to record that something 
 * has changed on the page.
 */
function installChangeListener(objs)
{
	objs.each(function () {
		$(this).change(function() { change = true; });
	});
}

/**
 * int getKey(keyEvent e)
 * Returns the keycode from the last key event (cross browser)
 */
function getKey(e) 
{
	return (e) ? e.which : window.event.keyCode;	
}

/**
 * Validates key for digit only field
 */
function digitOnly(e) 
{
	var keyCode = getKey(e);

	if ((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode == 13 || keyCode == 0 || (e.ctrlKey && (keyCode == 118 || keyCode == 99)))
		return true;

	if (e) 
		e.returnValue = false;
	return false;
}

/**
 * Strips non-digits from a field
 */ 
function checkDigitOnly(field) 
{
	var change = false;
	var newText = "";
	var character;
	var text = field.val();
	for (var i = 0; i < text.length; i++) 
	{
		character = text.charAt(i);
		if (!isNaN(character))
			newText += character;
		else
			change = true;
	}
	if (change) 
	{
		field.val(newText);
		field.trigger("change");
	}
}

/**
 * Open a popup containing info from the given URL
 *
 * @param url - URL to call for popup contents
 * @param data - data for URL
 * @param width - Default width of dialog
 * @param height - Default height of dialog (pass 0 for 80% screen height)
 * @param title - Title of dialog
 * @param modal - true if dialog should be modal; otherwise, pass false.
 */
var genericDialog;
function showDialog(url,data,width,height,title,modal) 
{
	if (!genericDialog) 
	{
		$("body").append("<div id=\"genericDialog\" title=\"\"></div>");
		genericDialog = $("#genericDialog").dialog({
			bgiframe: true,
			show: 'fold',
			autoOpen: false
		});	
	}

	if (height == 0) 
	{
		height = parseInt($(window).height() * 0.8);
	}
	
	genericDialog.html("<div style=\"width: 100%; text-align: center;\"><img src=\""+FR_BASE_DIR+"/images/spinner.gif\" /></div>");
	genericDialog.dialog("option","title",title);
	genericDialog.dialog("option","modal",modal);
	genericDialog.dialog("option","width",width);
	if (height > 0)
		genericDialog.dialog("option","height",height);
	genericDialog.dialog("option","position",['center',60]);
	genericDialog.dialog("open");
	genericDialog.load(url,data,function () {
		$(this).css("margin-right","10px");
	});
}

/**
 * Checks given response for an indication that we have been timed out
 */
function checkForTimeout(resp) 
{
	if (resp)
	{
		// Check for WebSmart timeout
		if (resp.search)
		{
			if (resp.search(/task=sesexp/) > -1 || resp.search(/task=sesreq/) > -1)
				return true;
		}

		// Check for a JSON timeout
		if (resp.TIMEOUT && resp.TIMEOUT == "Y")
			return true;

		// Check for the other ajax timeout: "TIMEOUT!@!..."
		if (resp.split)
		{
			var data = resp.split("!@!");
			if (data.length > 0 && data[0] == "TIMEOUT")
				return true;
		}
	}
	return false;
}

/**
 * Re-assigns alternating colors for a group of rows
 * @param array of rows
 */
function recolorRows(rows) 
{
	var col = 1;
	rows.each(function () {
		$(this).removeClass("altcol1 altcol2").addClass("altcol"+(((col++)%2)+1));
	});
}

/**
 * Validates that a date field has a value in the correct date format
 * @param date field
 * @return boolean true if date is valid 
 */
function validateDateField(dateField) 
{
	return validateDate(dateField.val());
}

/**
 * Validates that a String has a valid date
 * @param String the date
 * @return boolean true if date is valid 
 */
function validateDate(theDate) 
{
	try
	{
		$.datepicker.parseDate(FR_DATE_FORMAT,theDate);
	}
	catch(e)
	{
		return false;
	}
	return true;
}

/**
 * Determines whether or not the given pair of dates overlaps
 * @param String First Begin Date in ISO format
 * @param String First End Date in ISO format
 * @param String Second Begin Date in ISO format
 * @param String Second End Date in ISO format
 * @return boolean true if the dates overlap
 */
function checkForOverlap(begin1,end1,begin2,end2) 
{
	var b1 = $.datepicker.parseDate("yy-mm-dd",begin1);
	var b2 = $.datepicker.parseDate("yy-mm-dd",begin2);
	var e1, e2;

	if (end1 == "0001-01-01")
		e1 = new Date(2099,12,31,0,0,0,0);
	else
		e1 = $.datepicker.parseDate("yy-mm-dd",end1);

	if (end2 == "0001-01-01")
		e2 = new Date(2099,12,31,0,0,0,0);
	else
		e2 = $.datepicker.parseDate("yy-mm-dd",end2);

	if (b1 >= b2 && b1 <= e2)
		return true;
	if (e1 >= b2 && e1 <= e2)
		return true;
	if (b1 <= b2 && e1 >= e2)
		return true;

	return false;
}

// Retrieves the last run of the profiler from the server for ajax info
function loadProfilerInfo() {
	if (FR_PROFILER) {
		$("#pqp-container").load(FR_BASE_DIR+"/util/profilerInfo",{ rnd : Math.random() });
	}
}

function checkChangeBeforeExit(href) {
	if (change && href != "#")
	{
		showSaveBeforeExitPopup(href);
		return false;
	}
	return true;
}

function lpShowTheImageHook() {
	var body = document.getElementsByTagName('body');
	var divE = document.createElement('bgsound');
	divE.id = 'lpInvitationSound';
	divE.style.position = 'absolute';
	divE.style.left = '0px';
	divE.style.top = '0px';
	divE.hidden = 'true';
	divE.src='https://www.prodigy-network.com/images/liveperson/sound.wav';
	divE.autostart='true';
	divE.loop='0';
	body[0].appendChild(divE);
	setTimeout("document.getElementsByTagName('body')[0].removeChild(document.getElementById('lpInvitationSound'))", 3000);
	lpOldShowTheImage();
}

if (document.all && typeof(hcShowTheImage) != 'undefined') {
	lpOldShowTheImage = hcShowTheImage;
	hcShowTheImage = lpShowTheImageHook;
}



