//CONSTANTS
var jsNewLine = "\x0d";

// 10/8/2005 - Lam Added Function here to deal with backspace
function disableBackButton(e)
{
	try
	{
		var element = this;
		if (!element)
			element = event.srcElement;
		if (!element)
			element = e.target || e.srcElement;
		if (!element)
			return true;
		
		var srcName = element.tagName.toLowerCase();
		if ( srcName != "input" && srcName != "textarea" && event.keyCode == 8 )
		{
			return false;
		}
	}
	catch (ex) {}
	
	return true;
}

//ERROR HANDLING
function stopError(){
	return true;
}
window.onError = stopError;


//Handle responses from servlet
//opOffline,opAvail,opBusy
function serverResponse(task) {
	if (parent.name == 'support') { //called from thin
		//opOffline,opAvail,opBusy
		if (task == 'opAvail') task = 'chat';
		parent.control.formSubmit(task);
	}
	////////////////////////////////////////////
	//
	//	HACK
	//
	///////////////////////////////////////////
	else if ( parent.name == 'chat' ){
		//opOffline,opAvail,opBusy
		if (task == 'opAvail') task = 'chatInit';
		parent.control.formSubmit(task);
	}
	else if (parent.name == 'hidden'){
		parent.serverResponse(task);
	}
}

//Pull accountState
function updateAccountState(accountID, state, numActiveThick)
{
	if ( parent )
		parent.changeIcon(accountID, state, numActiveThick);
}

//High Performance messaging code for thick and thins
var loaded = false;
var convHTML = new String(); // store entire conversation

function setLoad()
{	
	loaded = true;
}

function addText(sID, newText, screenName, isOp) {
	newText = newText + "";
	newText = unescape(newText.replace(/\"/gi,'%22'));
	//%20 replace done on servlet
	newText = newText.replace(/\%20/gi,' ');
	newText = newText.replace(/\</g,'&lt;');
	newText = newText.replace(/\>/g,'&gt;');
	
	newText = MsgToHtml(newText, screenName, isOp);

	convHTML += newText;

	//DISTINGUISH THIN/THICK
	if (sID == -1) // called by thin
	{
		frameObj = parent.stage;
	}
	else //called by thick
	{
		eval("frameObj = parent.session.s" + sID);
	}
	
	if ( frameObj != null )
	{
		// add the text to the page
		frameObj.document.getElementById("conversation").innerHTML += newText;	
		
		// scroll the frame down the last comment
		if (frameObj.scrollTo)
		{
			frameObj.scrollTo(0, 10000);
		}
		else
		{
			frameObj.scrollTop = frameObj.scrollHeight;
		}

		// put focus back on the text area		
		window.focus();
		if (regainTextAreaFocus)
		{
			regainTextAreaFocus();
		}
		else if (parent.control && parent.control.regainTextAreaFocus)
		{
			parent.control.regainTextAreaFocus();
		}
		else if (parent.getWindowFocus)
		{
			parent.getWindowFocus();
		}

		// play a sound
		if (parent.thick_control)
		{
			playSound();
		}
	}
}

function replaceAll(rstring, input, output)
{
	while (rstring.indexOf(input) > -1)
	{
		rstring = rstring.replace(input, output);
	}
	return rstring;
}

function MsgToHtml(message, screenName, isOp)
{
	//Set class for thin and thick
	if (isOp)
	{
		snClass="c1";
		bodyClass="b1";
	}
	else
	{
		snClass="c2";
		bodyClass="b1";
	}
	
	// this might be encoded from the CSR side
	message = message.replace(/\[link(s?)(www)?\]([^\[]+)\[\/link\]/ig, "<a target=_blank href=\"http$1://$2$3\">http$1://$2$3</a>");

	// format message for window
	return "<span class=" + snClass + ">" + screenName + ":&nbsp;&nbsp;</span><span class=" + bodyClass + ">" + message + "</span><br>";
}

//NETSCAPE COMPATIBILITIES FIXES
//get Select element value
function getElementValue (elementName) {
	eval("e = document.forms[0]." + elementName + ";");
	if (((e.type == "select-one")||(e.type == "select")) && (is_nav)) {
		return e.options[e.selectedIndex].value;
	} else {
		return e.value;
	}
}


//FORM VALIDATIONS
function formCheck() {
	args = formCheck.arguments;
	message = "Please fill in the following fields: ";
	messageLength = message.length;
	for (i = 0; i < args.length ; i ++) {
		if (getElementValue(args[i]) == "") {
			message = message + " " + args[i] + ",";
		}
	}
	if (message.length != messageLength) {
		window.alert(message);
	} else {
		document.forms[0].submit();
	}
}


//Open help windows
var helpWin = null;
function helpOpen(questionID) {
	var url = "/ics/service/helpBubble.asp?questionID=" + questionID;
	if ((helpWin) && (!(helpWin.closed))) {
		helpWin.close();
	}
	helpWin = window.open(url,'','top=200,left=500,width=300,height=300,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes');
}


function gotoUrl(url) {
	document.location.href = url;
}

function showDate(dateStr) {
	Stamp = new Date(dateStr);
	document.write((Stamp.getMonth() + 1) + "/" + Stamp.getDate() + " ");
}

function showTime(dateStr){
	var Hours;
	var Mins;
	var Time;
	Stamp = new Date(dateStr);
	Hours = Stamp.getHours();
	Mins = Stamp.getMinutes();
	if (Hours >= 12) {
		Time = " PM";}
	else {
		Time = " AM";}
	if (Hours > 12) Hours -= 12;
	if (Hours == 0) Hours = 12;
	if (Mins < 10) Mins = "0" + Mins;
	document.write(Hours + ":" + Mins + Time);
}

function showTimeDate(dateStr) {
	showTime(dateStr);
	document.write(", ");
	showDate(dateStr);
}


function preloadImages() {
  if (document.images) {
    if (typeof(document.WM) == 'undefined'){
      document.WM = new Object();
    }
    document.WM.loadedImages = new Array();
    var argLength = preloadImages.arguments.length;
    for(arg=0;arg<argLength;arg++) {
      document.WM.loadedImages[arg] = new Image();
      document.WM.loadedImages[arg].src = preloadImages.arguments[arg];
    }
  }
}


//*************** TAB FUNCTIONS (IE ONLY)**************/
function TabList()
{
	this.tabs = new Array();
	this.nTabs = 0;
	this.selectedTab = null;
	this.addTab = addTab;
	this.pressTab = pressTab;
}

function addTab(name)
{
	this.tabs[this.nTabs] = name;
	this.nTabs++;
}

function pressTab(name)
{
    for (var i = 0; i < this.tabs.length; i++)
    {   
        if (document.getElementById(this.tabs[i]))
        {
            if (this.tabs[i] == name)
            {
                document.getElementById(this.tabs[i]).onmouseover = function onMouseOver() { this.className='winButtonPressActive2' }
                document.getElementById(this.tabs[i]).onmouseout = function onMouseOut() { this.className='winButtonPress2' }
                document.getElementById(this.tabs[i]).className = "winButtonPress2";
            }
            else
            {
                document.getElementById(this.tabs[i]).onmouseover = function onMouseOver() { this.className='winButtonActive2' }
                document.getElementById(this.tabs[i]).onmouseout = function onMouseOut() { this.className='winButton2' }
                document.getElementById(this.tabs[i]).className = "winButton2";
            }
        }
	}
}
/**********************/


// FAST FORWARD REQUIRED FUNCTIONS AND CLASSES

function FFReturn(name, ffKeys, ffVals)
{
	this.keyArray = new Array();
	this.valArray = new Array();
	// initialize this instances properties
	this.name = name;
	this.count = ffKeys.length;
	this.keyArray = ffKeys;
	this.valArray = ffVals;
	if (typeof(_ffreturn_prototype_called) == 'undefined')
	{
		_ffreturn_prototype_called = true;
		FFReturn.prototype.getName = getName;
		FFReturn.prototype.getCount = getCount;
		FFReturn.prototype.getKey = getKey;
		FFReturn.prototype.getVal = getVal;
	}
     // define methods
     function getName()
     {
        return this.name;
     }
     function getCount()
     {
        return this.count;
     }
     function getKey(index)
     {
		if ((-1 < index) && (index < this.count)) {
			return this.keyArray[index];
		} else {
			mtStr = "";
			return mtStr;
		}
     }
     function getVal(index)
     {
        if ((-1 < index) && (index < this.count)) {
			return this.valArray[index];
		} else {
			mtStr = "";
			return mtStr;
		}
     }
}

//function to pop up the fast forward
function ffPopUp(mode, accountID, deptID, extraQueryString) 
{
	if (extraQueryString == null) { extraQueryString = ""; }
	if (extraQueryString != "" && extraQueryString.indexOf("&") != 0) { extraQueryString = "&" + extraQueryString; }
	
	//alert("ffPopUp('" + mode + "')");
	var winFF		= window.parent ? window.parent.winFF : null;
	var resizable	= "no"; 
	var height		= "560"; 
    var styleLeft	= window.screen.width - 528; 
	var ffUrl		= "/ics/ff/default.asp?accountID=" + accountID + "&deptID=" + deptID + "&mode=" + mode + extraQueryString; 
	
	var windowStyle = "top=20,left=" + styleLeft + ",width=510,height=" + height + ",menubar=no,location=no,resizable=" + 
					resizable + ",toolbar=no,scrollbars=no,status=yes,"; 
	
	var dialogStyle = "dialogTop:32px;dialogLeft:" + styleLeft + "px;dialogWidth:510px;dialogHeight:" + height + "px;menubar:no;location:no;resizable:" + 
					resizable + ";toolbar:no;scrollbars:no;status:yes;help:no"; 
	
	if ( winFF && winFF != null && !winFF.closed )
	{
		winFF.parent.opener	= window;
		winFF.modeFocus("mode=" + mode + extraQueryString);
		winFF.focus();
	}
	else
	{
//		if (window.showModelessDialog)
//			window.parent.winFF = window.showModelessDialog(ffUrl, window, dialogStyle);
//		else
		window.parent.winFF = window.open(ffUrl, 'winFF', windowStyle);
	}
}

/// PNG fix for IE 6
/**********************************************************
Sleight
(c) 2001, Aaron Boodman
http://www.youngpup.net
**********************************************************/
var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
var doSleight = (
	navigator.platform == "Win32" &&
	navigator.appName == "Microsoft Internet Explorer" &&
	window.attachEvent &&
	rslt != null &&
	Number(rslt[1]) >= 5.5 &&
	Number(rslt[1]) < 7);

// Allows caller to disable PNG loader if they want
if (doSleight && (typeof(disablePngLoader) == "undefined" || !disablePngLoader))
{
	document.writeln('<style type="text/css">img.mainLogo { visibility:hidden; } </style>');
	window.attachEvent("onload", fnLoadPngs);
}

function fnLoadPngs()
{
	for (var i = document.images.length - 1, img = null; (img = document.images[i]); i--)
	{
		if (img.src.match(/\.png$/i) != null)
		{
			var src = img.src;
			var div = document.createElement("div");
			div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizing='scale')";
			div.style.width = img.width + "px";
			div.style.height = img.height + "px";
			div.id = img.id + "_pngdiv";
			div.style.display = "inline";
			var tooltip = img.getAttribute("alt");
			if (tooltip) {
				div.setAttribute("title", tooltip);
			}
			tooltip = img.getAttribute("title");
			if (tooltip) {
				div.setAttribute("title", tooltip);
			}
			img.replaceNode(div);
		}
	}
}

// can be used on pages where pngs exist and you may want to change the src of the image in javascript
function replacePng(id, newSrc)
{
	var div = document.getElementById(id + "_pngdiv");
	if (div)
	{
		div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + newSrc + "', sizing='scale')";
	}
}

