//////////////////////////////////////////////////////////////////////////////
// IDX.js																	//
// The code contained herein is soley for use within the IDX Broker System	//
// The code is not for reproduction											//
// Copyright 2006 IDX Inc.													//
//////////////////////////////////////////////////////////////////////////////

/*****************************************************************************
 * asyncronous functions
 */
var requests = new Array(); // We hold an *array* of requests and destinations.
var heights = new Array(); // placeholder heights.

function httpRequest(reqType, url, parameter, asynch, destination, placeHolderHeight)
{
	if(!destination)
		destination = document.getElementById("ajaxInformant").alt;
	if(placeHolderHeight)
		heights[destination] = placeHolderHeight;

	//Mozilla-based browsers
    if(window.XMLHttpRequest)
	{
        requests[destination] = new XMLHttpRequest();
    }
	else if (window.ActiveXObject)
	{
        requests[destination] = new ActiveXObject("Msxml2.XMLHTTP");
        if (!requests[destination])
		{
            requests[destination] = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
	
    //the request could still be null if neither ActiveXObject
    //initialization succeeded
    if(requests[destination])
	{
        initReq(reqType,url,parameter,asynch, destination);
    }
	else
	{
        alert("Your browser does not permit the use of all of this application's features!");
    }
}


function initReq(reqType,url,parameter,bool, destination)
{
	if (reqType == "GET")
	{
		parameter = null;
	}
	requests[destination].onreadystatechange=handleResponse; 
    requests[destination].open(reqType,url,bool);
	if (reqType == "POST")
	{
		requests[destination].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		requests[destination].setRequestHeader("Content-length", parameter.length);
		requests[destination].setRequestHeader("Connection", "close");
	}
    requests[destination].send(parameter);
}

//event handler for XMLHttpRequest
function handleResponse( )
{
	j = 0;
	for ( destination in requests )
	{
		//document.getElementById('dump').innerHTML += "<br />Working on " + destination + "..." + requests[destination].readyState;
		//document.getElementById('dump').innerHTML += "<br />requests[]:";
		if (requests[destination].readyState < 4)
		{
			var heightString = '';
			if(heights[destination] != 'undefined')
				heightString = ' style="height: ' + heights[destination] + 'px" ';
			document.getElementById(destination).innerHTML= '<center><div' + heightString + '><img src="/images/icons/ajax-loader.gif" width="16" height="16" alt="loading" /></div></center>';
		}//if
		else if (requests[destination].readyState == 4)
		{
			if(requests[destination].status == 200)
			{
				/* Grab the result as a string */
				var returnedResult = requests[destination].responseText;
				if (returnedResult)
				{
					document.getElementById(destination).style.display = 'block';
					document.getElementById(destination).innerHTML = returnedResult;
				}//if
				else
				{
					if (document.getElementById(destination).type != 'select-multiple')
						document.getElementById(destination).style.display = 'none';
				}//else
				//document.getElementById('dump').innerHTML += "<br /><b>Deleting request object for " + destination + " at location " + j + "</b>";
				requests[destination] = 0;
			} //if
			else
			{
				document.getElementById(destination).innerHTML= 'A problem occurred with communicating between the XMLHttpRequest object and the server program.';
			}//else
		}//else if
		j++;
	}//for
}//handleResponse

/**
 * writeReposition - This confusing bit of code loops through every drag'n'droppable object on the page
 *  and formats a GET string, which is passed via Ajax to a handler page (this page MUST be provided!)
 *
 *  The GET string looks like this:
 *     cid=(int)clientID&objects['divID']=(int)position&objects['divID2']=(int)position, etc
 *  Thus, the page handling the repositioning SQL has a very handy keyed array, each key being an object's ID, the value it's position
 *
 *  The 'page' parameter needs to be a fully-qualified URL.
 *****/
function writeReposition(page)
{
	// Using the Scriptaculous library, populate the hidden DIVs with our sorting information
	populateHiddenVars();

	// The 'inputs' are all the objects on our page that will have sortable elements
	var inputs = document.getElementById('inputs').value;
	// Split them into individual elements
	var inputArray = inputs.split(',');

	// Initialize the string which will eventually hold all of our GET parameters
	var params = '';

	// The tally is here to keep a global counter running.
	// If there was only ONE editable (drag and droppable) object on our page, this wouldn't be a problem,
	//  but since pages can have multiple editable sections, a global counter, in this case 'tally', is necessary.
	var tally = 0;
	// Loop through each editable object on our page
	for (var i = 0; i < inputArray.length; i++)
	{
		/**
		 * NOTE: Scriptaculous does a very strange thing here, and does not store the information as cleanly as I would like.
		 * The format of the positioning dump that Scriptaculous gives is: parentObject[]=1&parentObject[]=2&(etc).
		 * It gives no information about child objects on the page. So what this next section does is discover all the child
		 *  objects of 'parentContainer' and associates them the original positions values (1,2,3,etc) given by Scriptaculous.
		 *
		 * For an overview of how to access DOM elements from javascript, please see this document:
		 *      http://krook.org/jsdom/
		 */
		// Store the text dump from the editable object we are currently looking at
		var div = document.getElementById(inputArray[i]).value;
		// The 'parentObject' string is repeated for each element, so we only need to strip off the first occurance.
		div = div.substring(0, div.indexOf('['));
		// loop through each child node of that parentContainer...
		for(var k = 0; k < document.getElementById(div).childNodes.length; k++)
		{
			// grab that child node's id...
			divID = document.getElementById(div).childNodes.item(k).id;
			// strip off the existing formating information...
			divID = divID.substring(0, divID.indexOf('_'));
			// append the parameter string with the following:  &objects['divID']=position
			params += ('&objects[' + divID + ']=' + tally);
			// Increment the ongoing global tally
			tally++;
		}//for
	}//for

	// Place a database call to store the state
	var myAjax = new Ajax.Request(
		page, 
		{
			method: 'get', 
			parameters: 'cid=' + cid + params
		});
}//writeReposition

function suggest(path,inputId,suggestDivId,suggestDivWidth)
{
	var input = document.getElementById(inputId);
	var div = document.getElementById(suggestDivId);
	var informant = document.getElementById('ajaxInformant');
	
	informant.alt = suggestDivId;
	div.style.width = suggestDivWidth + 'px';
	
	if (input.value != '' && input.value.length > 2)
	{
		div.style.display = 'block';
	}
	else
	{
		div.style.display = 'none';
	}
	
	if (input.value && input.value.length > 2)
	{
		var url = path + "?preString=" + input.value + "&inputId=" + inputId + "&hide=" + suggestDivId;
		httpRequest("GET",url,null,true);
	}
}

/**
 * toggle field types according to prop type for basic search page 
 */
function toggleFieldTypes(url,informant)
{

	//  httpRequest(reqType, url, parameter, asynch, destination, placeHolderHeight)
	httpRequest("GET",url,null,true,informant);
	handleResponse( );

} // end function


/**
 * toggle field types according to prop type for basic search page 
 */
function toggleFieldTypesMgmt(url)
{

	//alert('test');
	httpRequest("GET",url,null,null);
	handleResponse( );

} // end function


/**
 * functions for photo management
 * photoChanger()
 * this function makes the confirm changes box visable if the order of photos has changed
 */
function photoChanger()
{
	populateHiddenVars();
	
	var stateArray = document.getElementById('divOrder-default').value.split(',');
	var currentArray = document.getElementById('divOrder').value.split('&');
	var displayConf = false;
	for (var i = 0; i < stateArray.length; i++)
	{
		var currentValueArray = currentArray[i].split('=');
		if (stateArray[i] != currentValueArray[1])
			displayConf = true;
	}
	if (document.getElementById('IDX-confirmChangesBox').style.display == 'none' && displayConf == true)
	{
		document.getElementById('IDX-confirmChangesBox').style.display = 'block';
		hardToss('IDX-confirmChangesBox');
		toss('IDX-confirmChangesBox');
		
		document.getElementById('IDX-confirmChangesBox2').style.display = 'block';
		hardToss('IDX-confirmChangesBox2');
		toss('IDX-confirmChangesBox2');
		
		window.displayConf = true;
	}
}

/**
 * photoRemover()
 * this function changes the id of a photo div so it can be removed.
 */
function photoRemover(divToRemove)
{
	document.getElementById(divToRemove).style.display = 'none';
	document.getElementById(divToRemove).id = document.getElementById(divToRemove).id + 'd';
	photoChanger()
}

/**
 * writeNote - Places a note in the database for a particular account/lead, and updates the notes div
 */
function writeNote(type, id, clean)
{
	if(type != "account" && type != "lead")
		return false;
		
	var page = "/mgmt/ajax/writeNote.php";
	var note = $F("note");

	var public = '';
	if(type == "account")
		public = "&public=" + $F('publicNote');

	document.getElementById("noteTaker").reset();

	// Place a database call to store the state
	var myAjax = new Ajax.Updater(
		'IDX-notesList',
		page, 
		{
			method: "post", 
			parameters: "cid=" + cid + "&type=" + type + "&id=" + id + "&clean=" + clean + "&note=" + note + public
		});
}//writeNotes
	
function flipNotePrivacy(type, id, noteID, state)
{
	if(type != "account" && type != "lead")
		return false;
		
	var page = "/mgmt/ajax/writeNote.php";

	// Place a database call to store the state
	var myAjax = new Ajax.Updater(
		'IDX-notesList',
		page, 
		{
			method: "post", 
			parameters: "cid=" + cid + "&type=" + type + "&id=" + id  + "&noteID=" + noteID + "&public=" + state + "&flip=1"
		});
}//end function editNote
	
function deleteNote(type, noteID, id)
{
	if(type != "account" && type != "lead")
		return false;

	var agree = confirm("Press \"OK\" to delete the Note.");
		
	if(!agree)
		return false ;

	var page = "/mgmt/ajax/writeNote.php";

	// Place a database call to store the state
	var myAjax = new Ajax.Updater(
		'IDX-notesList',
		page, 
		{
			method: "post", 
			parameters: "cid=" + cid + "&type=" + type + "&id=" + id + "&noteID=" + noteID + '&delete=1'
		});
	// This is the function for clearing the overlib
	return nd();
}// end function deleteNote
	
/**
 * searchKB - Calls a search to the searchKB.php file to gather relevant pages
 */
function searchKB()
{
	var page = "/mgmt/ajax/searchKB.php";
	var param = "keywords=" + document.getElementById('keywords').value;

	// Place a database call to store the state
	var myAjax = new Ajax.Updater(
		'IDX-kbSearchContainer',
		page, 
		{
			method: "post", 
			parameters: param
		});
}//end function searchKB

/*****************************************************************************
 * general functions
 */
 
/**
 * simple function for generating popup windows
 */
function popUp(URL,width,height)
{
			day = new Date();
			id = day.getTime();
			eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=" + width + ",height=" + height + ",left = 315,top = 268');");
} // end popUp

/**
 * simple function to display a confirmation before processing a delete
 * @param itemToDelete - the name of the thing you're trying to delete
 */
function confirmSubmit(itemToDelete)
{
	var agree=confirm("Are you sure you wish to delete this " + itemToDelete + "?");
	if (agree)
	{
		return true ;
	}
	else
	{
		return false ;
	}
} // end confirmSubmit

/**
 * simple function for inserting text into a form field
 * @param targetID - the ID of thing form element you want to insert into
 * @param source - what you want to insert into the targeg
 * @param submitTF - weather or not to submit the form after the value is inserted
 * @param forID - the ID of the form to be submitted.
 */
function insert(targetID,source,submitTF,formID)
{
	var target = document.getElementById(targetID);
	target.value = source;
		
	if (submitTF == 'TRUE')
	{
		document.getElementById(formID).submit();
	}
} // end insert

/**
 * function for checking the validity of login and change password forms
 * @param formID - the id of the form conatining the username and password field
 */
function loginCheck(formID)
{
	/**
	 * variable to check to see is we need to check retypes
	 */
	var checkMatch = false;
	
	/**
	 * check for the various items we may want to check for
	 * if they exist arr them to the checkElements array
	 */
	var checkElements = new Array();
	if(typeof document.getElementById(formID).username != "undefined")
	{
		checkElements.push(document.getElementById(formID).username);
	}
	if(typeof document.getElementById(formID).password != "undefined")
	{
		checkElements.push(document.getElementById(formID).password);
	}
	if(typeof document.getElementById(formID).newPassword1 != "undefined")
	{
		checkElements.push(document.getElementById(formID).newPassword1);
		checkMatch = true;
	}
	if(typeof document.getElementById(formID).newPassword2 != "undefined")
	{
		checkElements.push(document.getElementById(formID).newPassword2);
	}
	
	/**
	 * regex for checking validity (i.e. no characters other than alphanumerics and underscores)
	 */
	var invalid = /[^a-zA-Z0-9_]/;
	/**
	 * var to double check validity
	 */
	var isValid = true;
	
	/**
	 * step through each element and check that is is filled out and has valid characters
	 */
	for (var i = 0; i < checkElements.length; i++)
	{
		if (checkElements[i].value == '')
		{
			alert('One or more fields was not filled out properly.');
			checkElements[i].focus();
			isValid = false;
			return false;
		}
		else if (invalid.test(checkElements[i].value))
		{
			alert('Invalid character(s) used.');
			checkElements[i].focus();
			isValid = false;
			return false;
		}
	}
	
	/**
	 * is this is a change password form then check to makes sure the passwords match
	 * if they do not then empty the password fields
	 */
	if (checkMatch && document.getElementById(formID).newPassword1.value != document.getElementById(formID).newPassword2.value)
	{
		alert('New passwords do not match');
		document.getElementById(formID).newPassword1.value = '';
		document.getElementById(formID).newPassword2.value = '';
		document.getElementById(formID).newPassword1.focus();
		isValid = false;
		return false;
	}

	/** 
	 * if everything is valid return true
	 */
	if (isValid)
	{
		return true;
	}
	/**
	 * if something is invalid then return false
	 */
	else
	{
		alert("Form does not validate.");
		return false;
	}
} // end loginCheck

/**
 * functions for switching beween divs (toggling display none/block) on an event
 * @param activeDivID - the div to make active
 * @param allDivID - CSV of all the div's which we'll be acting on
 * @note: this function prefixes the "IDX-" and appends the 'Div' to the names of all the ID's entered
 */
function divSwitch(activeDivID,allDivID)
{
	var divArray = allDivID.split(',');
	for (var i = 0; i < divArray.length; i++)
	{
		document.getElementById('IDX-' + divArray[i] + 'Div').style.display = 'none';
	}
	document.getElementById('IDX-' + activeDivID + 'Div').style.display = 'block';
} // end divSwtich

// confirm or delete in supplemental
function confirmscript(pagetogo,thetext,checkedornot)
{
	var theval = confirm(thetext);
	if (theval == 1)
	{			
		window.location=pagetogo;			
	}
	else
	{
		alert("You have chosen not to delete this listing");
	}
} // end confirmscript

var check = true;
function deleteSelected()
{
	var agree = confirm("By pressing \"OK\" you will delete all selected entries?\nAre you sure you want to proceed?");
	if (agree)
		document.forms.searchResults.submit();
	else
		return false ;
}
	
function checkAll(formName)
{
	var ele = formName["selected[]"];
	var value = !ele[0].checked;
	for (i = 0; i < ele.length; i++)
		ele[i].checked = value;
}//end function (checkAll)