/*****************************************************************
*  File usage:  views\accounts\add_order_account.tpl
*				          \edit_account.tpl
*				          \route_account.tpl
*				 \admin\case_form.tpl
*				       \ddManager.tpl
*				       \ddManagerAddPopup.tpl
*				       \ddManagerEditPopup.tpl
*					  \edit_company.tpl
*					  \lead_form.tpl
*					  \toolboxManager\toolboxManager.tpl
*				 \campaigns\edit_campaign.tpl
*				           \predictive_dialer.tpl
*				 \contacts\edit_contact.tpl
*				 \contact_groups\edit_contact_group.tpl
*				 \emails\edit_email.tpl
*				 \employees\edit_employee.tpl
*				 \import\contact_import_match.tpl
*					   \contact_import_review.tpl
*					   \dnc.tpl
*					   \lead_import.tpl
*					   \lead_import_match.tpl
*					   \lead_import_review.tpl
*				 \leads\edit_lead.tpl
*					  \edit_lead_predictive.tpl
*				 \orders\add_order_customer_detail.tpl
*					   \add_order_product_details.tpl
*					   \add_order_select_customer_detail.tpl
*					   \edit_order.tpl
*				 \scripts\edit_script.tpl
*					    \script.tpl
*				 \sysadmin\edit_company.tpl
*				 \welcome\clients.tpl
*
*------------------------------------------------------------------
*  Function usage:
*			moveTop():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*						 \toolboxManager\toolboxManager.tpl
*			moveBottom():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*						 \toolboxManager\toolboxManager.tpl
*			moveUp():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*						 \toolboxManager\toolboxManager.tpl
*			moveDown():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*						 \toolboxManager\toolboxManager.tpl
*			privateMoveUp():
*				js\dropdownFunctions.js
*			privateMoveDown():
*				js\dropdownFunctions.js
*			moveItems():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*						 \toolboxManager\toolboxManager.tpl
*			deleteSelectedItems():
*				js\dropdownFunctions.js
*				views\scripts\edit_script.tpl
*			saveDropdownData():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*						 \toolboxManager\toolboxManager.tpl
*			openAddWindow():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*			openEditWindow():
*				js\dropdownFunctions.js
*				views\admin\ddManager.tpl
*			selectChange():
*				 js\dropdownFunctions.js
*				   \functions.js
*				 views\accounts\add_order_account.tpl
*							\edit_account.tpl
*					 \admin\edit_company.tpl
*						  \lead_form.tpl
*					 \contacts\edit_contact.tpl
*					 \employees\edit_employee.tpl
*					 \leads\edit_lead.tpl
*						  \edit_lead_predictive.tpl
*					 \orders\add_order_customer_detail.tpl
*					 \sysadmin\edit_company.tpl
*
*******************************************************************/
function sortSelect(theSelect, ascending) 
{
	values = new Array();
	
	for(i=0; i<theSelect.length; i++)  
	{
		values[i] = theSelect.options[i].text+"@@"+theSelect.options[i].value;
	}

	if (ascending)
	{
		values.sort();
	}
	else
	{
		values.sort(sortSelectDesc);
	}
	

	for(i=0; i<theSelect.length; i++)  
	{
		pair = values[i].split("@@");
		theSelect.options[i].text = pair[0];
		theSelect.options[i].value = pair[1];
	}
}

function sortSelectDesc(a, b) 
{ 
   if(a > b) 
      return -1 
   if(a < b) 
      return 1 
   return 0 
} 

//////////////////////////////////////////////////////////////////////////////
//
//  moveTop()
//
//////////////////////////////////////////////////////////////////////////////
function moveTop(theSelect) {
	var selIndex = theSelect.selectedIndex;
	if (theSelect.length > 1 && selIndex > 0) {
		var options = theSelect.options;
		for (var i = selIndex; i > 0; i--) {
			privateMoveUp(options, i);
		}
		theSelect.focus();
		theSelect.selectedIndex = 0;
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  moveBottom()
//
//////////////////////////////////////////////////////////////////////////////
function moveBottom(theSelect) {
	var selIndex = theSelect.selectedIndex;

	// Need at least 2 items and something selected, but not the last one
	if (theSelect.length >  1 &&
	    selIndex         > -1 &&
	    selIndex         < theSelect.length - 1)
	{
		var options = theSelect.options;
		for (var i = selIndex; i < theSelect.length - 1; i++) {
			privateMoveDown(options, i);
		}
		theSelect.focus();
		theSelect.selectedIndex = theSelect.length - 1;
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  moveUp()
//
//////////////////////////////////////////////////////////////////////////////
function moveUp(theSelect) {
	if (theSelect.length > 1) {
		var options = theSelect.options;

		// find which ones are selected...
		var selectedIds = new Array ();
		var index = 0;
		for (var i = 1; i < theSelect.length; i++) {
			if (options[i].selected) {
				selectedIds[index] = i;
				index++;
			}
		}
		// move each selected option up
		var selId;
		for (var i = 0; i < selectedIds.length; i++) {
			selId = selectedIds[i];
			privateMoveUp(options, selId);
			options[selId].selected     = false;
			options[selId - 1].selected = true;
		}
		theSelect.focus ();
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  moveDown()
//
//////////////////////////////////////////////////////////////////////////////
function moveDown(theSelect) {
	if (theSelect.length > 1) {
		var options = theSelect.options;

		// find which ones are selected
		var selectedIds = new Array ();
		var index       = 0;
		for (var i = theSelect.length-2; i >= 0; i--) {
			if (theSelect.options[i].selected) {
				selectedIds[index] = i;
				index++;
			}
		}
		// move each selected element down
		var selId;
		for (var i = 0; i < selectedIds.length; i++) {
			selId = selectedIds[i];
			privateMoveDown(options, selId);
			options[selId].selected     = false;
			options[selId + 1].selected = true;
		}
		theSelect.focus ();
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  privateMoveUp()
//
//////////////////////////////////////////////////////////////////////////////
function privateMoveUp (options, index) {
	var newOption = new Option(options[index - 1].text,
				   options[index - 1].value);
	options[index - 1].text  = options[index].text;
	options[index - 1].value = options[index].value;
	options[index].text      = newOption.text;
	options[index].value     = newOption.value;
}

//////////////////////////////////////////////////////////////////////////////
//
//  privateMoveDown()
//
//////////////////////////////////////////////////////////////////////////////
function privateMoveDown (options, index) {
	var newOption = new Option(options[index + 1].text,
				   options[index + 1].value);
	options[index + 1].text  = options[index].text;
	options[index + 1].value = options[index].value;
	options[index].text      = newOption.text;
	options[index].value     = newOption.value;
}

//////////////////////////////////////////////////////////////////////////////
//
//  moveItems()
//
//////////////////////////////////////////////////////////////////////////////
function moveItems(list1,list2){
	//loop through the items in list one and put the selected ones in list two
	for (i = 0; i < list1.length; i++) {
		if (list1.options[i].selected) {
			// move the option to list 2
			list2.options[list2.length] = new Option(list1.options[i].text,
								 list1.options[i].value);
			list1.options[i] = null;
			// the next item becomes the item at index i so
			// decrement i so that we are sure to check the
			// next element
			i--;
		}
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  selectAll()
//
//////////////////////////////////////////////////////////////////////////////
function selectAll(list1){
	for (i = 0; i < list1.length; i++) {
		list1.options[i].selected = true;
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  deleteSelectedItems()
//
//////////////////////////////////////////////////////////////////////////////
function deleteSelectedItems(list1){
	//loop through the items in the list delete the option if its selected
	for (i = 0; i < list1.length; i++) {
		if (list1.options[i].selected) {
			list1.options[i] = null;
			// the next item becomes the item at index i so
			// decrement i so that we are sure to check the
			// next element
			i--;
		}
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  saveDropdownData()
//
//////////////////////////////////////////////////////////////////////////////
function saveDropdownData(theDropDown,theHiddenField){
	// loop through the dropdown and add the values to the hidden field
	// use the following delimited format:
	//   value1|value2|value3
	theData = "";
	for (i = 0; i < theDropDown.length; i++) {
		theData += theDropDown.options[i].value + "|";
	}
	// trim the right bar "|"
	theData = theData.substr(0, theData.length - 1);
	// put the string in the hidden field
	theHiddenField.value = theData;
}

//////////////////////////////////////////////////////////////////////////////
//
//  saveDropdownDataWithLabel()
//
//////////////////////////////////////////////////////////////////////////////
function saveDropdownDataWithLabel(theDropDown,theHiddenField){
	// loop through the dropdown and add the values to the hidden field
	// use the following delimited format:
	//   value1|value2|value3
	theData = "";
	for (i = 0; i < theDropDown.length; i++) {
		theData += theDropDown.options[i].value + "==" + theDropDown.options[i].text + "|||";
	}
	// trim the right bar "|"
	theData = theData.substr(0, theData.length - 3);
	// put the string in the hidden field
	theHiddenField.value = theData;
}

//////////////////////////////////////////////////////////////////////////////
//
//  openAddWindow()
//
//////////////////////////////////////////////////////////////////////////////
function openAddWindow(ddName, template, width, height){
	if(ddName == "Email Template Categories")
	{
		window.open();
	}
	window.open(template+"?ddName=" + ddName,
		    "",
		    "width="+width+",height="+height+",resizable");
}

//////////////////////////////////////////////////////////////////////////////
//
//  openEditWindow()
//
//////////////////////////////////////////////////////////////////////////////
function openEditWindow(selectList,selectList2,ddName, template, width, height){
	// check if more that one item is selected
	counter        = 0;
	selectedOption = -1;
	for (i = 0; i < selectList.options.length; i++) {
		if (selectList.options[i].selected) {
			selectedOption = i;
			counter++;
			if (counter > 1) {
				alert("You can only edit one option at a time.");
				return false;
			}
			theValue = selectList.options[i].value;
		}
	}
	if (selectedOption >= 0) {
		window.open(template+"?id=" + theValue + "&ddName=" + ddName,
			    "",
			    "width="+width+",height="+height+",resizable");
		/*
		window.open("/admin/ddManagerEditPopup?id=" + theValue + "&ddName=" + ddName,
			    "",
			    "width=300,height=120");*/
	} else {
		counter        = 0;
		selectedOption = -1;
		for (i = 0; i < selectList2.options.length; i++) {
			if (selectList2.options[i].selected) {
				selectedOption = i;
				counter++;
				if (counter > 1) {
					alert("You can only edit one option at a time.");
					return false;
				}
				theValue = selectList2.options[i].value;
			}
		}
		if (selectedOption >= 0) {
			window.open(template+"?id=" + theValue + "&ddName=" + ddName,
			    "",
			    "width="+width+",height="+height+",resizable");
		/*
		window.open("/admin/ddManagerEditPopup?id=" + theValue + "&ddName=" + ddName,
			    "",
			    "width=300,height=120");*/
		} else {
			alert("You must select an option.");
			return false;
		}
	}
	
}

//////////////////////////////////////////////////////////////////////////////
//
//  selectChange()
//
//////////////////////////////////////////////////////////////////////////////
function selectChange(control, controlToPopulate, ItemArray, GroupArray,selected)
{
	if(typeof(control) == "undefined" || typeof(controlToPopulate) == "undefined") return;
	var myEle ;
	var x ;
	// Empty the second drop down box of any choices
	for (var q = controlToPopulate.options.length; q >= 0; q--) {
		controlToPopulate.options[q] = null;
	}

	// Add Default Choice - in case there are no values
	myEle = new Option("[SELECT]", '');
	controlToPopulate.options[controlToPopulate.length] = myEle;
	//myEle       = document.createElement("option");
	//myEle.value = 0;
	//myEle.text  = "[SELECT]";
	//controlToPopulate.add(myEle);
	// Now loop through the array of individual items
	// Any containing the same child id are added to
	// the second dropdown box
	none = true;
	
	for (var x in ItemArray) {
		if (GroupArray[x][1] == control.value) { //If state_id tied to current country
			none = false;
			myEle = new Option(ItemArray[x][1], ItemArray[x][0]);
			
			controlToPopulate.options[controlToPopulate.length] = myEle;
			//myELe       = document.createElement("option");
			//myEle.value = x;
			//myEle.text  = ItemArray[x];
			//controlToPopulate.add(myEle);
			if (ItemArray[x][0] == (selected)) {
				myEle.selected = true;
			}
		}
	}
	if (none) {
		controlToPopulate.options[0] = new Option("[NONE]", 0);
	}
}

//////////////////////////////////////////////////////////////////////////////
//
//  The following functions are for use in quickly adding a new state or country
//  to the dropdowns without having to go to the admin tab first.
//  Functions Include:
//		updateList()					- updates the States or Countries DD
//		setUrlWithCurrentCountryId()	- opens a state popup for a valid country
//		getCountryUrl()					- opens a country popup.
//		centerPopup()					- is called from the previous two for centering.
//
//	Pages using these functions include:
//		add_country.act
//		add_country_state.act
//		edit_lead.tpl
//
//////////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////////
	//
	//  function:  updateList()
	//  is called from the quick add popups when they are submitted. (states and countries).
	//
	//////////////////////////////////////////////////////////////////////////////
	function updateList(id, value, fieldname){
		if (fieldname == "country_id") {
			fieldDD = document.editPage.country_id;
		} else {
			fieldDD = document.editPage.state_id;
		}
		if(typeof(fieldDD) == "undefined") return;
		fieldDD.options[fieldDD.length] = new Option(value,id);
		new_selection = fieldDD.options.length - 1; // Make the new item the current option.
		fieldDD.options.selectedIndex = new_selection;
		if (fieldname == "country_id") {
			fieldDD = document.editPage.state_id; // Make sure that the state drop down has valid states for the new country.
			if(typeof(fieldDD) == "undefined") return;
			selectChange(fieldDD.options[fieldDD.options.selectedIndex], fieldDD, stateArray, stateCountryArray,stateid);
		}
	}

	//////////////////////////////////////////////////////////////////////////////
	//
	//  setUrlWithCurrentCountryId() enforces the user to add states to the correct countries. 
	//  the add state popup requires a country id and this provides it.
	//
	//////////////////////////////////////////////////////////////////////////////
	function setUrlWithCurrentCountryId(usa_id) {
		if(typeof(document.editPage.country_id) != "undefined"){
			countryDD = document.editPage.country_id;
			country_id = countryDD.options[countryDD.options.selectedIndex].value;
			if (country_id == "") {
				alert("You must select OR create a country before proceeding.  ");
				return;
			}
		}
		else{
			country_id = usa_id;//They don't have a country dd so it has to go to the USA since those are the states that are visible.
		}
		window.open('/admin/add_country_state_popup?country_id='+country_id+'&closePopup=1&FieldName=state_id','States','width=627,height=250,scrollbars,'+centerPopup());

	}

	//////////////////////////////////////////////////////////////////////////////
	//
	//  getCountryUrl() returns a centered popup window for adding a new country
	//
	//////////////////////////////////////////////////////////////////////////////
	function getCountryUrl() {
		window.open('/admin/add_country_popup?closePopup=1&FieldName=country_id','Countries','width=627,height=250,scrollbars,'+centerPopup());
	}

	//////////////////////////////////////////////////////////////////////////////
	//
	//  centerPopup() is called when the popup windows are created (it centers).
	//
	//////////////////////////////////////////////////////////////////////////////
	function centerPopup() {
		from_left = (screen.width / 2) - 325;  // center the popup.
		from_top  = (screen.height  / 2) - 125; 
		center_vals = 'left='+from_left+',top='+from_top;
		return center_vals;
	}