var aSubWindows = new Array();
var lTimer;
var oTimer;
var sTitle = document.title;

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function LoadProgressWindow(lProgressID,bHasFile) {
		if (document.MM_returnValue && bHasFile) {
			winstyle="height=300,width=400,status=no,toolbar=no,menubar=no,location=no";
			window.open("progress.asp?progressid="+lProgressID,"progress",winstyle);
		}
}

function CheckFileName(sName) {
//	for (i=0; i<sName.length; i++) {
//		alert(sName.charCodeAt(i))
//	}

//	return ''

	var re = /[#,?\u2019\u2018\u201C\u201D]|\.\./	//special codes for single and double smart quotes
	if (re.test(sName)) {
		return 'Please make sure the file name \'' + sName + '\' does not contain\nany of the following: # , ? .. \u2018 \u2019 \u201C \u201D .'
	} else {
		return ''
	}
//	return 'test'
}

function NewJob(lCustomerID) {
	winstyle="height=650,width=420,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes";
	window.open("newJob.asp?Customer="+lCustomerID,"",winstyle);
}

function AddNote(lJobID,sFile,sType) {
	winstyle="height=640,width=400,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes";
	aSubWindows[aSubWindows.length] = window.open("addNote.asp?Job=" + lJobID + "&Type=" + sType + "&File=" + sFile,"",winstyle);
}

function AddRelatedNote(lJobID,lNoteID,sFile,sType,sPrivate,sAdministrative) {
	winstyle="height=640,width=400,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes";
	aSubWindows[aSubWindows.length] = window.open("addNote.asp?Job=" + lJobID + "&NoteID=" + lNoteID + "&Type=" + sType + "&Private=" + sPrivate + "&Administrative=" + sAdministrative + "&File=" + sFile,"",winstyle);
}

function EditNote(lNoteID) {
	winstyle="height=600,width=400,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes";
	window.open("EditNote.asp?Note="+lNoteID,"EditNote",winstyle);
}

function EditJob(lJobID) {
	winstyle="height=550,width=470,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes";
	window.open("EditJob.asp?Job="+lJobID,"EditJob",winstyle);
}

function modifyjob(Change,JobID,OldValue,Status) {
	window.open ('ModifyJob.asp?Job=' + JobID + '&Change=' + Change + '&OldValue='+ OldValue + '&Status=' + Status,'modifyjob','width=150,height=300')
}

function jobpriority(JobID,UserID,Dir) {
	window.open ('ModifyJob.asp?Job=' + JobID + '&User=' + UserID + '&Change=Priority&Direction=' + Dir,'modifyjob','width=100,height=250')
}

function NoteTools(sAction) {
	window.open ('NoteTools.asp?action=' + sAction,'NoteTool','width=100,height=100,resizable=1,scrollbars=1')
}

function JobAdminUsers(lJobID) {
	window.open ('JobAdminUsers.asp?Job=' + lJobID,'modifyjob','width=150,height=600,resizable=1,scrollbars=1')
}

function SendNoteEmail(lJobID, lNoteID) {
	aSubWindows[aSubWindows.length] = window.open ('addNote.asp?Job=' + lJobID + '&CopyNoteID=' + lNoteID,'SendNoteEmail','height=640,width=430,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes')
}

//var getUrlLink = 'title="get url"><img src="images/document_attachment.png" border="0" align="absmiddle"></a>';
var getUrlLink = 'title="get url">Link to Note</a>';

function showURL(iJobID, iNoteID) {
	var oUrlDiv = document.getElementById('url_' + iNoteID);
	var s = '<a href="javascript:hideUrl(' + iJobID + ',' + iNoteID + ')"' + getUrlLink;
	s += '<div class="showurl" style="margin-left:50px;">'
	s += '<a href="javascript:copyUrl(' + iJobID + ',' + iNoteID + ')" style="display:block; float:left; width:50%; text-align:left; margin:0px 0px 5px 0px;">copy URL</a>';
	s += '<a href="javascript:hideUrl(' + iJobID + ',' + iNoteID + ')" style="display:block; float:right; width:50%; text-align:right; margin:0px 0px 5px 0px;">close</a>';
	s += 'http://www.spotlightdesign.com/MyJobs/job.asp?Job=' + iJobID + '#n' + iNoteID;
	s += '</div>';
	oUrlDiv.innerHTML = s;
	//alert(oRow);
}

function hideUrl(iJobID, iNoteID) {
	var oUrlDiv = document.getElementById('url_' + iNoteID);
	var s = '<a href="javascript:showURL(' + iJobID + ',' + iNoteID + ')"' + getUrlLink;
	oUrlDiv.innerHTML = s;
}

function copyUrl (iJobID, iNoteID) {
	hideUrl(iJobID, iNoteID);
	var s = 'http://www.spotlightdesign.com/MyJobs/job.asp?Job=' + iJobID + '#n' + iNoteID;
	var browser=navigator.appName;
	//var b_version=navigator.appVersion;
	//var version=parseFloat(b_version);

	if (browser == "Netscape") {
		// firefox requires workaround . . . .
		//const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].   
		//getService(Components.interfaces.nsIClipboardHelper);   
		//gClipboardHelper.copyString(s);  
	} else {
		window.clipboardData.setData('text', s);
	}
}

function SizeToFit() {
	if (document.body.scrollWidth && document.body.offsetWidth) {
		var maxHeight = Math.min(screen.availHeight - 75,document.body.scrollHeight);
		var maxWidth = Math.min(screen.availWidth - 20,document.body.scrollWidth);
		var addWidth = maxWidth - (document.body.offsetWidth)
		var addHeight = (maxHeight - document.body.offsetHeight)
		//alert(addWidth + ':' + addHeight)
		if (addWidth < -15 || addWidth > 15 || addHeight < -15 || addHeight > 15) {
		window.resizeBy(addWidth + 25 ,addHeight + 10)
		}
	}	
}

function doSpell(varname) {
//	var url = '/spellchecker/window.asp?jsvar='+ varname
//    window.open(url, null, 
//        "height=230,width=450,status=no,toolbar=no,menubar=no,location=no"); 
	rsTCIntRapidSpellWebLauncher1 = new RSStandardInterface(varname);
	popUpCheckSpellingRapidSpellWebLauncher1('rsTCIntRapidSpellWebLauncher1') 
}

//Rapid spell spell checker

function escQuotes(text){  var rx = new RegExp("\"", "g"); return text.replace(rx,"&#34;");}
function escEntities(text){var rx = new RegExp("&", "g"); return text.replace(rx,"&amp;");}

var rsTCIntRapidSpellWebLauncher1 = null;
var spellBoot="";
//<input type='hidden' name='UserDictionaryFile' value='d:\\RapidSpell\\UserDictionary\\UserDictionary.txt'>
function popUpCheckSpellingRapidSpellWebLauncher1(interfaceObjectName){ 
 spellBoot = "<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
 spellBoot += "<body onLoad='document.forms[0].submit();'><font face='arial, helvetica' size=2>Spell checking document...</font><form action='../RapidSpell/PopUp.aspx' method='post'>";
 spellBoot += "<input type='hidden' name='textToCheck' value=\"";
 spellBoot += escQuotes(escEntities(eval(interfaceObjectName+'.getText()')))+"\"><input type='hidden' name='InterfaceObject' value='"+interfaceObjectName+"'><input type='hidden' name='mode' value='popup'><input type='hidden' name='DictFile' value=''><input type='hidden' name='SuggestionsMethod' value='HASHING_SUGGESTIONS'><input type='hidden' name='LanguageParser' value='ENGLISH'><input type='hidden' name='SeparateHyphenWords' value='False'>";
 spellBoot += "<input type='hidden' name='ShowFinishedMessage' value='False'><input type='hidden' name='ShowNoErrorsMessage' value='True'><input type='hidden' name='CreatePopUpWindow' value='True'><input type='hidden' name='FinishClosesWindow' value='True'><input type='hidden' name='WarnDuplicates' value='True'>";
 spellBoot += "<input type='hidden' name='SuggestSplitWords' value='True'><input type='hidden' name='CheckCompoundWords' value='False'><input type='hidden' name='CorrectionNotifyListener' value=''><input type='hidden' name='Modal' value='False'><input type='hidden' name='InformFinishListenerOfState' value='False'>";
 spellBoot += "<input type='hidden' name='IncludeUserDictionaryInSuggestions' value='True'><input type='hidden' name='LookIntoHyphenatedText' value='True'><input type='hidden' name='FinishedListener' value=''><input type='hidden' name='GuiLanguage' value='ENGLISH'><input type='hidden' name='callBack' value=''><input type='hidden' name='IgnoreXML' value='False'><input type='hidden' name='IgnoreCapitalizedWords' value='False'><input type='hidden' name='ConsiderationRange' value='-1'></form></body>";
 spellBoot += "</html>";
 var sc = window.open('', 'rspellwin', 'resizable=yes,scrollbars=auto,dependent=yes,toolbar=no,left=100,top=100,status=no,location=no,menubar=no,width=370,height=400');
 sc.focus(); sc.document.open();  sc.document.write(spellBoot); sc.document.close();
}
function RSStandardInterface(tbElementName){
//	alert(tbElementName)
	this.tbName = tbElementName;this.getText = getText;this.setText = setText;
	function getText(){
		if(!document.getElementById(this.tbName)) {
			alert('Error: element '+this.tbName+' does not exist, check TextComponentName.');
			return '';
		} else
			 return document.getElementById(this.tbName).value;
	}
	function setText(text){
		if(document.getElementById(this.tbName)) document.getElementById(this.tbName).value = text;
	}
}
//<!--<input name="RapidSpellWebLauncher1:_ctl0" type="button" value="Check Spelling" onClick="popUpCheckSpellingRapidSpellWebLauncher1('rsTCIntRapidSpellWebLauncher1')" />-->
//end of RapidSpell code


//Size limit on text area field
/**
 * DHTML textbox character counter (IE4+) script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function taLimit(taObj) {
	if (taObj.value.length==taObj.getAttribute('maxLength')*1) return false;
}

function taCount(taObj,visCnt) { 
	var msg=''
	if (taObj.value.length>taObj.getAttribute('maxLength')*1) {
		taObj.value=taObj.value.substring(0,taObj.getAttribute('maxLength')*1);
		alert('Text is over the limit, please attach a file with your comments/corrections!')
	}
	if (visCnt) {
		msg = '<b>' + (taObj.getAttribute('maxLength')-taObj.value.length) + '</b> characters remaining.'
		if (taObj.getAttribute('maxLength')-taObj.value.length == 0) msg+= ' <span style="color:red">Please attach a file with your comments/corrections.</span>'
		visCnt.innerHTML=msg
	}
}


function showtimeoutwarning() {
//	window.alert('Your session will expire soon, please submit your note now.\n\nOr copy your note to word or notepad and continue editing there. (And submit the file when you are ready.)')
}

function timeoutwarning() {
//	setTimeout('showtimeoutwarning()',900000) //15 minutes
}
	
function removeDiv(sDiv){
	var o = document.getElementById(sDiv);
	if (o) o.parentNode.removeChild(o);
}
function preventExpiry(){
	var oScript = document.createElement('script');
	oScript.src = 'TimeoutAJAX.asp?AJAX=1';
	document.body.appendChild(oScript);
	resetTimeout();
	resetSubTimeout();
	resetOpenerTimeout();
	if (window.opener && !window.opener.closed) {try{window.opener.resetSubTimeout();}catch(err){};}
}

function Timeout() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}

	var oTimeoutDiv = document.createElement('div');
	oTimeoutDiv.id = 'div_timeout';
	oTimeoutDiv.style.left = ((scrOfX - 175) + (myWidth / 2)) + 'px';
	oTimeoutDiv.style.top = ((scrOfY - 44) + (myHeight / 2)) + 'px';
	oTimeoutDiv.innerHTML = '<div id="div_timeout_header"><div class="floatleft">Session Timeout</div><div class="floatright pointer" onClick="removeDiv(\'div_timeout\');document.title=sTitle;clearInterval(oTimer);">X&nbsp;</div><div class="clear"></div></div><div id="divTimeoutText">Your session is about to expire: <span id="divTimeCountdown">5:00</span>. <br><a href="javascript:void(null);" onclick="preventExpiry();">Click here</a> to prevent your session from expiring.</div>';
	document.body.appendChild(oTimeoutDiv);
	if (window.opener && !window.opener.closed) {
		//expireTimeout = setTimeout('window.close();',(5*60000)+60000)
	} else {
		expireTimeout = setTimeout('expireSession();',(5*60000)+60000)
	}
	oTimer = setInterval('updateTimer();',1000);
}

function expireSession() {
	setLoginCookie('nextpage',window.location,null);
	window.location = 'logout.asp';
}

function updateTimer() {
	var s;
	var lSeconds;
	if (isNaN(lTimer)) lTimer = 5 * 60;
	lTimer -= 1;
	lSeconds = lTimer % 60;
	if (lSeconds < 0) {lSeconds = (lTimer + 60) % 60} else if (lSeconds < 10) {lSeconds = '0' + lSeconds;}
	s = Math.floor(lTimer / 60) + ':' + lSeconds;
	if (lTimer >= 0) {
		document.getElementById('divTimeCountdown').innerHTML = s
		if (lTimer % 2 == 0) {document.title = s + ' - ' + sTitle;} else {document.title = sTitle;}
	} else {
		if (window.opener && !window.opener.closed) {
			document.getElementById('divTimeoutText').innerHTML = 'Your session has expired. Please login on another page before clicking submit. <a href="javascript:void(null);" onclick="removeDiv(\'div_timeout\');document.title=sTitle;clearInterval(oTimer);">Close</a>.'
		} else {
			document.getElementById('divTimeoutText').innerHTML = 'Your session has expired. You will be redirected to the login page: '+lSeconds+'. <a href="javascript:void(null);" onclick="window.location = \'logout.asp\';">Go there now</a>.'
		}
	}
}

function setLoginCookie(c_name,value,expiredays) {
	var sVal = c_name+ "=" +escape(value)
	if (expiredays!=null) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		sVal += ";expires="+exdate.toGMTString();
	}
	document.cookie=sVal
}

function getLoginCookie(c_name){
	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1) {
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return "";
}

function resetTimeout() {
	try{
		removeDiv('div_timeout');
		removeDiv('divTimeoutText');
		clearTimeout(expireTimeout);
		clearInterval(oTimer);
		lTimer = 5 * 60;
		document.title = sTitle;
		if (getLoginCookie('LoginInfo')=='') expireTimeout = setTimeout('Timeout();',(dTimeout - 6) * 60000);
	} catch(err) {};
}

function resetOpenerTimeout() {
	if (window.opener && !window.opener.closed) {
		var o = window.opener;
		try{
			o.removeDiv('div_timeout')
			o.dTimeout = dTimeout;
			o.resetTimeout();
			o.resetSubTimeout();
		} catch(err) {};
	}
}
function resetSubTimeout() {
	for (i=0; i < aSubWindows.length;i++) {
		try{
			aSubWindows[i].removeDiv('div_timeout');
			aSubWindows[i].dTimeout = dTimeout;
			aSubWindows[i].resetTimeout();
		} catch(err) {};
	}
}
