var hexL = new Array('F','E','D','C');
var hexN = new Array('F','E','D','C','B','A','9','8','7','6','5','4','3','2','1','0');
var hexColors = hexArray();
var hexCounter = hexColors.length-1;

function hexArray(){
var duo = null;var trio = null;var arrHex = new Array();
	for(i=0; hexL.length>i; i++){
		for(j=0; hexN.length>j; j++){
			duo = hexL[i]+hexN[j];
			trio = duo + duo + duo;
			arrHex.push(trio);}}
return arrHex;
}
fadeBackgroundErrorProxy = function(){
	fadeBackground("divErrors",hexCounter);
}
var fadeBackgroundObject = null;
function fadeBackground(objID,counter){
	if(fadeBackgroundObject == null){
		if(typeof(objID) == 'object'){
			fadeBackgroundObject = objID;
		}else{
			fadeBackgroundObject = document.getElementById(objID);
		}
	}
	if(counter >= 0){
		fadeBackgroundObject.style.backgroundColor = '#'+hexColors[counter];
		counter= counter-1;
		setTimeout("fadeBackground(''," + counter+ ")",16);
	}else{
		fadeBackgroundObject = null;
	}
return counter;	
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

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

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function indexInArray(theArray, theValue){
var arr_Length = theArray.length;
var i;
	for(i=0; i<arr_Length; i++){
		if(theArray[i] == theValue){return i;}}
return -1;
}
function copyObjectProperties(setObj,getObj){
var err=null;var i;	
try{if(getObj && setObj){
	for(i in getObj){
	setObj[i] = getObj[i];}}}
catch(e){err=e;}
return (!err)? setObj : err;
}
function readCookie(cookieName, ignoreKeys){
	//The ignoreKeys argument allows you to skip the check for a key name
	var cookieValue = "";
	var search = cookieName;
	if(typeof(ignoreKeys) == 'undefined' || ignoreKeys == false){
		ignoreKeys = false;
		//Check to see if this is a multi-keyed cookie, if so, set the cookiename appropriately
		if (cookieName.indexOf(".") != -1) {
			//We have a multi-keyed cookie	
			var cookieSplit = cookieName.split(".");
			search = cookieSplit[0];
		}else{
			ignoreKeys = true;
		}
	}
	//Add the equal sign onto the end to search through the cookie
	search = search + "=";
	if(document.cookie.length > 0){ 
		offset = document.cookie.indexOf(search);
		if (offset != -1){ 
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) end = document.cookie.length;
			cookieValue = unescape(document.cookie.substring(offset, end));
			if(ignoreKeys == false){
				//Need to find a specific key value from the cookieValue
				search = cookieSplit[1] + '=';
				offset = cookieValue.indexOf(search);
				if (offset != -1) {
					//We found the key we're looking for
					offset += search.length;
					end = cookieValue.indexOf('|', offset);
					cookieValue = cookieValue.substring(offset, end);
				}else{
					//The key didn't exist, return an empty string
					cookieValue = '';
				}
			}
		}
	}
   return cookieValue;
}
function writeCookie(cookieName, cookieValue, cookieExpires){
  var cookieExpiration = "";
  if(cookieExpires != null){
    cookieExpiration = new Date((new Date()).getTime() + cookieExpires * 3600000);
    cookieExpiration = ";expires=" + cookieExpiration.toGMTString();
  }
  document.cookie = cookieName + "=" + escape(cookieValue) + ";domain=.lynda.com;path=/" + cookieExpiration;
}
function switchCookieValue(condition,cookieName,yesValue,noValue){
	var cookieValue = (condition)?yesValue:noValue;
	writeCookie(cookieName,cookieValue)//TODO: ADD EXPIRES BACK,';domain=.lynda.com;path=/; expires='+readCookie(cookieName).expires);
}
//------------------------------------------------------------------------------------
// CREATED: July 10, 2005
// LAST MODIFIED:  September 26, 2007
//
// FUNCTION: dwfaq_alternateTableRows
//   
// REQUIREMENTS: NONE
//
// DESCRIPTION: Used to alternate the row classes (i.e., background color) and collect an
//			array of found rows. Assigning var foo = dwfaq_alternateTableRows([argumemts])
//			allows for the use of foo to perform additional actions on the rows such 
//			as counting the total to display the number of results.
//
// ARGUMENTS:
//		obj - STRING/OBJECT: The table ID as a string or the table as an object
//		startRow - NUMBER: The row of the table to start alternating (Use to skip a <th>)
//		class1 - STRING: The class to apply to row 1 and subsequent odd rows
//		class2 - STRING:  The class to apply to row 2 and subsequent even rows
//		target - DOCUMENT OBJECT: The document containing the table
//		excludeLastRow - TRUE/FALSE (OPTIONAL): Alternate the final row of the table
//
// RETURNS:
//		ARRAY  - All rows contained in the table, despite startRow and excludeLastRow
//------------------------------------------------------------------------------------
function dwfaq_alternateTableRows(obj,startRow,class1,class2,target,excludeLastRow){//v1.0
var i,arrRows,rowCount,curRow,container,curClass;
	if(typeof(obj) == "string"){
		container = (target)? target : document;
		obj = container.getElementById(obj);
	}
	if(!obj){return false;}
	arrRows = obj.getElementsByTagName("TR");
	rowCount = arrRows.length;
	i=startRow;//Start looping after the specified startRow
	for(i; i < rowCount; i++){
		curRow = (i%2==0)?class1:class2;
		if(!excludeLastRow || (excludeLastRow && (i+1 != rowCount))){
			curClass = arrRows[i].getAttribute("class");
			curClass = (curClass && curClass!= 'null')?curClass+" ":"";
			arrRows[i].setAttribute("class",curClass+curRow);
		}
	}
return arrRows;
}
//------------------------------------------------------------------------------------
// CREATED: September 26, 2007
// LAST MODIFIED:  October 2, 2007
//
// FUNCTION: applyStyles
//   
// REQUIREMENTS: indexInArray - May be required for specific cases
//
// DESCRIPTION: Used to apply CSS styles dynamically, for a variety of purposes.
//
// ARGUMENTS:
//		apply - STRING: The only required argument of this function, it is the case statement that should be run.
// NAMED ARGUMENTS: These arguments are specific to case statements and supplied as a named argument to the function.
//		id - STRING or OBJ: The ID of the element or the object itself.
//		total - NUMBER: The total number of columns in a table.
//		adjust - STRING: A comma separated list of columns to adjust.
//		align - STRING (right|left|center): The alignment for a given list of columns.
//
// CASES:
//		results - Used to apply alternating row colors to any table on a page with class="results"
//		align-columns - Used to align <td> contents to the specified align value.
//
// RETURNS:
//		TRUE/FALSE - True if a statement was run, false if not.
//------------------------------------------------------------------------------------
function applyStyles(apply){
	var retVal = true;
	if(typeof(document.appliedStyles)=='undefined'){document.appliedStyles= new Object();}
	switch(apply.toLowerCase()){
		//Tables with the .results class applied to them get alternating row colors
		case 'results':
			/* Run only once per page */
			if(!document.appliedStyles.results){
				var arrTables = document.getElementsByTagName("TABLE");
				var arrTables_length = arrTables.length;
				var i;
				for(i=0; i < arrTables_length; i++){
					if(arrTables[i].className.indexOf('results') != -1){;
						var startRow = (typeof(arrTables[i].getElementsByTagName('TR')[0].getElementsByTagName('TH')[1]) == 'object')?1:0;//Skip first row if it has more than one th
						var c1=(startRow==1)?'even':'odd';
						var c2=(c1=='odd')?'even':'odd';
						dwfaq_alternateTableRows(arrTables[i],startRow,c1,c2,document,false); 
					}
				}
			document.appliedStyles.results = true;
			}
		break;
		
		case 'align-columns':
			var cols = adjust.split(",");
			var obj = (typeof(id) == 'object')?id:document.getElementById(id);
			if(!obj){alert("You don't have a valid object or ID.\nThe id passed to this function was:"+id); return false;}
			var arrTR = obj.getElementsByTagName("TR");
			var arrTR_length = arrTR.length;
			var arrTD,arrTD_length;
			var i,j,adj,pos;
			for(i=0; i < arrTR_length; i++){
				//Get the TDs
				arrTD = arrTR[i].getElementsByTagName("TD");
				arrTD_length = arrTD.length;				
				//If the number of TDs is less than the total number of cells, assume there's a th or th with colspans
				adj=(arrTD_length < total)?(total - arrTD_length)+1:1;
				//Loop over the total number of columns, checking if the column was specified
				for(j=1; j <= total; j++){
					pos = (indexInArray(cols, j));
					currCol = parseInt(cols[pos]-(adj))
					if(pos != -1 && currCol >=0 && arrTD[currCol]){
					arrTD[currCol].style.textAlign = align;
					}
				}

			}
		break;
		
		default:
		retVal = false;
	}
return retVal;
}

function validateSingupStep1Form() {
	var errortext = '';

	if (document.frank.contact_name.value == '') {
		errortext += 'Please enter your Name.\n';
	}
	if (document.frank.Phone.value == '') {
		errortext += 'Please enter your Phone Number.\n';
	}
	if (document.frank.email.value == '') {
		errortext += 'Please enter your Email Address.\n';
	}
	if (document.frank.Password.value == '') {
		errortext += 'Please enter your Password.\n';
	}
	if (document.frank.Password2.value == '') {
		errortext += 'Please enter your Password the second time.\n';
	}
	if (document.frank.Password.value != document.frank.Password2.value) {
		errortext += 'Your passwords do not match. Please enter your passwords again.\n';
	}
	if (errortext != '') {
		alert('Correct the following errors before submitting:\n\n' + errortext);
	} else {
		document.frank.submit();
	}
}


/* cfwindow functions to prevent flash of content */
function windowCleanup(id) {
   ColdFusion.Window.destroy(id, true);
}

function showWindow(id, title, source, center, modal, draggable, height, width, autodestroy, dontReturn) {
	if(autodestroy == null){autodestroy = true;}
	
	if(autodestroy){
		try {
			//Destroy the window if it still exists
			ColdFusion.Window.destroy(id,true);
		} catch(e) { }
	}

	try {
		//Try to show the existing window object, and if it doesnt't exist, create it
		ColdFusion.Window.show(id);
	}catch(e){
		ColdFusion.Window.create(id, title, source, {center: center, modal: modal, draggable: draggable, height: height, width: width});
	}

	if(autodestroy == true){
		//If we want to autodestroy the window, then clean it up when it's hidden
		ColdFusion.Window.onHide(id, windowCleanup);
	}
	//return false to prevent link from following
    if(dontReturn == null || !dontReturn){
        return false;
    }
}

/* Functions dealing with ajax-based login, saving properties and saving searches */
var saveProperty = function(invid){
	var result = '';
	var statusResult = '';
	var statusel = document.getElementById('propertyCountText');
	var statusdiv = 'statusOMatic';
	if(!statusel){
		statusel = document.getElementById('save' + invid);
		statusdiv = statusel.id
	}
	statusel.style.display = 'inline';
	if(!loggedIn){
		showWindow('loginWindow', 'Login or Register', '/shared/ajax/login.cfm?nextAction=saveProperty&nextActionString=' + invid, true, true, false, 515, 550, true);
		return false;
	}

	if(!parseInt(invid)){
		statusResult = 'Please enter a valid property id';
	}
	if(statusResult == ''){
		result = rc.savePropertyToUser(invid);
		statusResult = result;
		if(parseInt(result) == result){
			//We got a valid integer back, update the counter;
			document.getElementById('savedInvCounter').innerHTML = result.toString();
			statusResult = 'Property number ' + invid.toString() + ' successfully saved.';

		}else{
			//There was an error, but we need to go ahead and update the counter just in case
			var splitResult = result.split('|');
			if(splitResult[1] == 'You\'re either not logged in, or your login has expired.'){
				//The user isn't logged in, update the loggedIn variable and try again
				loggedIn = false;
				saveProperty(invid);
				return false;
			}
			document.getElementById('savedInvCounter').innerHTML = splitResult[0].toString();
			statusResult = splitResult[1];
		}
	}

	//Update the text of the statusOMatic
	if(statusel){
		showStatus(statusResult, statusdiv);
	}

	return true;
}

/* Functions dealing with ajax-based login, saving properties and saving searches */
var saveSearch = function(searchString){
	var result = '';
	if(!loggedIn){
		showWindow('loginWindow', 'Login or Register', '/shared/ajax/login.cfm?nextAction=saveSearch&nextActionString=' + searchString, true, true, false, 515, 550, true);
		return false;
	}

	var result = rc.saveSearchToUser(searchString);
	var statusResult = 'There was a problem saving your search';
	if(result){
		statusResult = 'Search Successfully Saved';
	}
		
	//Update the text of the statusOMatic
	showStatus(statusResult, 'statusOMatic');

	return true;
}

var showStatus = function(content, id){
	//Get the old property count
	var statusContainer = document.getElementById(id);
	var origContent = statusContainer.innerHTML;
	statusContainer.innerHTML = content;

	//Add a black border
	statusContainer.style.borderColor = 'green';
	statusContainer.style.color = 'green';
	fadeBackground(id, hexCounter);

	window.revertStatus = function(content){
		statusContainer.style.color = 'black';
		statusContainer.style.borderColor = '#ffffff';
		statusContainer.innerHTML = origContent;
	}

	//3 seconds after the fade is done, revert everything back to its original state
	setTimeout('revertStatus();', 3000);

}


var usernameTimer;
var checkLogin = function(username, immediate){
	//Clear pervious timer if there was one.
	clearTimeout(usernameTimer);
	//Start a new one.
	if(username == ''){
		updateUsernameStatus(true);
	}else{
		if(immediate){
			updateUsernameStatus(rc.checkUsernameAvailability(username), username);
		}else{
			usernameTimer = setTimeout('updateUsernameStatus(rc.checkUsernameAvailability("' + username + '"), "' + username + '")', 750);
		}
	}
}

var originalStatus = '';
var updateUsernameStatus = function(result, username){
	var updateDiv = document.getElementById('registerUsernameStatus');
	if(originalStatus == ''){
		originalStatus = updateDiv.innerHTML;
	}

	if(validateEmail(username)){
		if(result){
			document.getElementById('inputRegisterUser').disabled = false;
			updateDiv.style.color = '#000000';
			updateDiv.innerHTML = originalStatus;
		}else{
			document.getElementById('inputRegisterUser').disabled = true;
			updateDiv.style.color = 'red';
			updateDiv.innerHTML = 'Email already in use. Login above.';
		}
	}else{
		document.getElementById('inputRegisterUser').disabled = true;
		updateDiv.style.color = 'red';
		updateDiv.innerHTML = 'Please enter a valid email address.';
	}
}


var validateEmail = function(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(address) == false) {
      return false;
   }
   return true;
}

var loginUser = function(username, password) {
	var statusField = document.getElementById('loginStatus');

	//Set logging in message
	var loadingMessage = showLoadingIndicator(statusField, 'Checking username and password');

	var result = rc.Authenticate(username, password);

	clearInterval(loadingMessage);

	if(result){
		loggedIn = true;
		loginProcessNextAction(ColdFusion.getElementValue('loginNextAction'), ColdFusion.getElementValue('loginNextActionString'));

	}else{
		statusField.style.textAlign = 'left';
		statusField.style.color = 'red';
		statusField.innerHTML = 'The username and password you entered are incorrect.'
	}
}

var registerUser = function(username, password, passwordconfirm, contactname, company){
	var statusField = document.getElementById('registrationStatus');

	//Set logging in message
	var loadingMessage = showLoadingIndicator(statusField, 'Processing Registration');

	var result = rc.Register(username, password, passwordconfirm, contactname, company);

	clearInterval(loadingMessage);

	if(result == true){
		rc.Authenticate(username, password);
		loggedIn = true;
		loginProcessNextAction(ColdFusion.getElementValue('registerNextAction'), ColdFusion.getElementValue('registerNextActionString'));
	}else{
		statusField.style.textAlign = 'left';
		statusField.style.color = 'red';
		statusField.innerHTML = result;
	}

}

var showLoadingIndicator = function(statusField, content){
	statusField.style.color = 'black';
	statusField.style.textAlign = 'center';
	statusField.innerHTML = content;
	var timerID = setInterval('document.getElementById("' + statusField.id + '").innerHTML += ".";', 500);
	return timerID;
}

var loginProcessNextAction = function(nextAction, nextActionString){
	//perform original action requested
	if(nextAction == 'saveProperty'){
		ColdFusion.Window.destroy('loginWindow', true);
		saveProperty(nextActionString);
	}else if(nextAction == 'addWantNeed'){
		ColdFusion.navigate('/shared/includes/wantsneeds/add.cfm', 'addWantNeed');
	}else if(nextAction == 'replyWantNeed'){
		ColdFusion.navigate('/shared/includes/wantsneeds/reply.cfm?'+nextActionString, 'replyWantNeed');
	}

}

var validateURL = function(url, urlField, statusDiv){
	//Check the URL, requires a remoteCFC definition
	var rc = new remoteCFC();
	var retVal = rc.validateURL(url);
	var bannerURL = document.getElementById(urlField);
	var statusDiv = document.getElementById(statusDiv);
	statusDiv.style.display = 'block';
	if(retVal == 'OK'){
		//Set the proper hidden form field for final banner submission.
		bannerURL.value = url;
		statusDiv.innerHTML = '&bull; The URL has been successfully validated!';
		statusDiv.style.border = '1px solid green';
	}else{
		//Clear the banner URL, and show an error
		bannerURL.value = '';
		statusDiv.innerHTML = '&bull; ' + retVal;
		statusDiv.style.border = '1px solid red';
	}
	fadeBackground(statusDiv, hexCounter);
}


var showPopupWindow = function(url,winname,features){
	window.open(url,winname,features);
}