/***********************************************************************************
** Desc:     common.js
**
** Author:    
** Date:      04/09/2003
************************************************************************************
** Change History
************************************************************************************
** Date			Author		Description
** ----------	---------	----------------------------------------------------------
** 04/09/03		jefjohns	added new method to support multi-select.
** 04/09/03		a-justsc	added new method to support getting a domain value from a modal window
** 04/22/03		a-justsc	commented functions getValue, getSelected..., toggleViewOption
** 04/24/03		a-justsc	add function openObjectBrowser to allow for viewing extended Opty details
** 06/18/03		a-justsc	made openObjectBrowser pass data through arguments, 
							added populateObjectBrowser to fill popup with data from arguments
** 1/09/04		v-amitg	    added new method to find control based on id which is present in cs file.
** 01/12/04		v-mikea		Added new function to prevent mutliple saves.	
** 03/01/04		v-mikea		Added function to set the focus to fields that are invalid.						
***********************************************************************************/	

function ACB_SetPageControlFocus(ctlID)
{
	var ctl = document.getElementById(ctlID);
	if((ctl != null) && (ctl.style.display != 'none') && (ctl.style.visibility != 'hidden') && (ctl.disabled != true))
	{
		//alert(ctl.style.pixelLeft + ' ' + ctl.style.pixelTop);

		ctl.focus();
		
		if(ctl.tagName == "INPUT" && ctl.type == "text")
		{
			var range = ctl.createTextRange()
			range.select();
		}
	}
}

function Init()
{
	//Page load entry point for aspx pages.
	CheckMessages();
	SetUpDirtyCheck();
}

function InitSpecial(method)
{
	Init();
	eval(method);
}

//Checks for any form fields titled message and shows an alert box.
function CheckMessages()
{
	
	//it's possible that more than one form will exist on the page
	//so we walk all the forms and look for a field called Message to display.
	var found;
	for(i = 0; i < document.forms.length; i++)
	{
		try  //Try catch this as not all forms will have a message field, if they dont' we don't care about it anyway.
		{
			if( (document.forms[i].message != null) && (document.forms[i].message.value != "") )
			{
				alert(document.forms[i].message.value);
				document.forms[i].message.value = "";
			}

			if( (document.forms[i].errorMessage != null) && (document.forms[i].errorMessage.value != "") )
			{
				alert(document.forms[i].errorMessage.value);
				document.forms[i].errorMessage.value = "";
				found=true;
			}

		}
		catch(exception)
		{
			//We're just going to ignore any errors that come up
		}
	}	
	if (found) history.back();
}

function ConfirmDelete(confirmMessage)
{
	if (confirm(confirmMessage)) return true; else return false;
}

function showTable(table, imgID)
{

	var displayStyle = "none";
	if(table.rows[1].style.display == "none")
	{
		displayStyle = "";
		imgID.src = "images/collapse.gif";
	}
	else
	{
		imgID.src = "images/expand.gif";
	}
	
	//start at the 2nd row(index 1) as we don't want to hide the first row which has the collapse / expand image.
	for(i = 1; i < table.rows.length; i++)
	{
		table.rows[i].style.display = displayStyle;
	}
}


function LaunchCalendar(elm)
{
//Purpose: Launches a modal window allowing a user to pick a date from a calendar
//elm should be a html text box, this is where the date will get written back to when the calendar is closed.

	d = new Date();
	var modalOptions = "dialogHeight:290px; dialogWidth:280px; Center: Yes; Help: No; Status: No;"
	var modalArguments = "";
	var modalReturnValue = null;
	//pull any existing values in the elm.value so we can default the calendar to that date. If it's not a date the calendar will just ignore it.
	modalReturnValue = window.showModalDialog("calendarframe.aspx?ihcInd=" + d.getDate + "&DefaultDate=" + elm.value, modalArguments, modalOptions)
	if(modalReturnValue != null)
	{
		//write the selected value back to the form field.
		elm.value = modalReturnValue;
	}
		
}

function getCorrectForm()
{
	//find the first POST form. MNP quick search is a get and we don't want to use that.
	for(i = 0; i < document.forms.length; i++)
	{
		if(document.forms[i].method.toUpperCase() == "POST")
		{
			return document.forms[i];
		}
	}
	//if we are still here there was probably trouble.
	//shouldn't happen though.
	return null;
}
//run on the page_load event. Sets up the process to warn a user before leaving a page
//if they have made a change to any form element.
function SetUpDirtyCheck()
{


	//if the dirty field exists and there is a value for it, then assume we need to do the dirty check.
	if(document.all.item("dirty") != null && document.all.item("dirty").value != "")
	{
		var oForm = getCorrectForm();
		window.attachEvent("onbeforeunload", warnForDirty);
		oForm.attachEvent("onsubmit", formSubmitCancelDirtyCheck);
		
		// for each form item and add an onchange event
		// so we will know if a form has changed.
		for(i = 0; i < oForm.elements.length; i++)
		{
			oForm.item(i).attachEvent("onchange", setDirtyForm)
			
		}	
	}
	else
	{
		//we shouldn't check for dirty. Just return.
		return;
	}					
}

//sets the dirty field to "" so the user wont be prompted about navigating away from the page.
function formSubmitCancelDirtyCheck()
{
	//if the form is being submitted we want to not warn about check for dirty
	if(document.all.item("dirty") != null && document.all.item("dirty").value != "")
	{
	    document.all.item("dirty").value = "";
	}
}

//sets the hidden text field dirty to be true so we know a value has changed on the form.
function setDirtyForm()
{
	document.all.item("dirty").value = "true";
}

//checks to see if the page has had values change on it and if the user wants to navigate away from the page
//without saving changes.
function warnForDirty()
{
	try
	{
		var oForm = getCorrectForm();
		//the dirty field is == true then let the user know their changes won't be saved.
		if(oForm.dirty.value == "true")
		{
			event.returnValue = oForm.dirty.errorMessage;
		}
	}
	catch(e)
	{
	}
}

//walks all the input checkbox items and checks or unchecks
//all the checkboxes that have a ClientName attribute value matching
//the ClientName property.
function toggleAll(ClientName, toggleControl)
{
	try
	{
		var container = getCorrectForm();
		if (container != null) 
		{
			var oItems = container.getElementsByTagName("input");
			var bChecked = container.chkToggle.checked;
			for(i = 0; i < oItems.length; i++)
			{
				if(oItems[i].type == "checkbox")
				{
					if(oItems[i].getAttribute("ClientName") == ClientName && oItems[i].disabled == false)
					{
						oItems[i].checked = bChecked;
					}
				}
			}
		}
	}
	catch(e)
	{
	}
}

///Walks all the input type checkbox items in the oForm
///and any that have a ClientName attribute equal to ClientName
///parameter and are checked will be returned in an array.
function GetSelectedIDs(ClientName, oForm)
{
	//get all the input boxes.

	var oItems = oForm.getElementsByTagName("input");
	var entityIDs = new Array();
	for(i = 0; i < oItems.length; i++)
	{
		//if the item is a checkbox
		if(oItems[i].type == "checkbox")
		{
			//has to match ClientName passed in.
			if(oItems[i].getAttribute("ClientName") == ClientName && oItems[i].checked)
			{	
				//add the item to the array.
				entityIDs.push(oItems[i].value);
			}
		}
	}
	
	//return the array of entityIDs.
	return entityIDs;
}


//Walks all the input type checkbox items on the page
//and any that have a ClientName attribute value equal to ClientName
//parameter and that are checked will be sent along to be added to the partner group.
function AddIdsToGroup(ClientName, HiddenName, ErrorMessage, Limiter)
{
	try
	{
		//Form 0 is the MNP Form, Form 1 is the ASPX form ... we may want to possible modify this, passing into the
		//function a form name, but for now this seems to work fine for what it was designed
		var container = getCorrectForm();
		
		if (container == null) return false;
		var oItems = container.getElementsByTagName("input");
		
		var entityIDs = new Array();
		for(i = 0; i < oItems.length; i++)
		{
			if(oItems[i].type == "checkbox")
			{
				if(oItems[i].getAttribute("ClientName") == ClientName && oItems[i].checked)
				{
					entityIDs.push(oItems[i].value);
				}
			}
		}
		
		//If a limiting control ID has been passed in, make sure the user hasn't selected more than they are allowed
		if(Limiter != '')
		{
			var oLimitItem = document.getElementById(Limiter);
			var limitingValue = oLimitItem.value;
			if(entityIDs.length > limitingValue)
			{
				alert('You have chosen more items than you are allowed.  Please reduce your selection.');
				return false;
			}
		}
		//If no IDs are selected, return an error message and exit
		if(entityIDs.length == 0)
		{
			alert(ErrorMessage);
			return false;
		}
		else
		{

			oItems = container.getElementsByTagName("input");
			for(i = 0; i < oItems.length; i++)
			{
				if(oItems[i].type == "hidden")
				{
					if(oItems[i].name == HiddenName)
					{
						oItems[i].value = entityIDs.join("|");
					}
				}
			}
			return true;
		}
	}
	catch(e)
	{
	}

}

//  Gets the select value from a modal Dialog window to apply an event reason to an action or possibly for future extension.
//	Works by opening up DomainDialog.aspx with Query String values
//  Parameters/Usage : domainName - specifies the domain to populate the selection utility (query string value)
//					   dialogType - specifies the selection utility (currently options are 'RadioList' or 'DropDown') (query string value)
//					   hiddenName - specifies the hidden control in which to store the collection of IDs
//					   errorMessage - a pop-up message displayed if no IDs are selected
//					   popUpTitle - the <Title> of the pop-up window (query string value)
//					   limiter - the control that provides a value which may limit how many IDs the user can apply an action to
//					   returnControlName - the control to store the returned value in
// use : Opportunities.ascx (MyPendingOpportunities.aspx)
function getValue( domainName, dialogType, hiddenName, errorMessage, popUpTitle, limiter, returnControlName )
{
	if(AddIdsToGroup('chkAdd', hiddenName, errorMessage, limiter))
	{
		var oEl = event.srcElement;
		var oTxtEl = document.getElementById(returnControlName);
		var pageName = "DomainDialog.aspx?Domain="+domainName+"&DialogType="+dialogType+"&Title="+popUpTitle;
		var sFeatures="dialogHeight: 180px; dialogWidth: 285px; help: no; resizable: no; status: no; scroll: no;";
		var returnValue = window.showModalDialog(pageName, oTxtEl.value, sFeatures);
		if(returnValue == null)
		{
			return false;
		}
		else
		{
			oTxtEl.value = returnValue;
			return true;
		}
	}
	else
	{
		return false;
	}

}

//	Gets the selected item, presumably from a RadioList control
//  used : DomainDialog.aspx
function getSelectedRadioItem()
{
	var oItems = document.getElementsByTagName("input");
	
	var entityIDs = new Array();
	for(i = 0; i < oItems.length; i++)
	{
		if(oItems[i].type == "radio")
		{
			if(oItems[i].checked)
			{
				return oItems[i].value;
			}
		}
	}
}

//	Gets the selected item, presumably from a DropDown control, whose ID is specified in the parameter
//  used : DomainDialog.aspx
function getSelectedDropDownItem( controlID )
{
	var oItem = document.getElementById(controlID);
	return oItem.value;
}

//  Switches the value in a hidden control (specified by the parameter) between
//  True and False, providing a binary switch for changing between Admin and normal
//  Contact views of data
//  used : MyOpenOpportunities.aspx, MyClosedOpportunities.aspx
function toggleViewOption( viewOptionControl )
{
	var oViewOptionControlItem = document.getElementById(viewOptionControl);
	if(oViewOptionControlItem.value == 'False')
		oViewOptionControlItem.value = 'True';
	else
		oViewOptionControlItem.value = 'False';
	return true;
}

//  Opens a modal window to browse an object, specified by the ObjectType and ObjectID, passing data to view through the Arguments
function openObjectBrowser( ObjectType, ObjectID, Argument1, Argument2, Argument3 ,Argument4,Argument5,Argument6, ParentObjectID)
{
		var modalArguments = new Array();
		modalArguments.push(Argument1);
		modalArguments.push(Argument2);
		modalArguments.push(Argument3);
		modalArguments.push(Argument4);
		modalArguments.push(Argument5);
    	modalArguments.push(Argument6);
		modalArguments.push(ObjectType);
		
		var pageName = "ObjectBrowser.aspx?ObjectType="+ObjectType+"&ObjectID="+ObjectID+"&ParentObjectID="+ParentObjectID;
		var sFeatures="dialogHeight: 650px; dialogWidth: 700px; help: no; resizable: yes; status: no;";
		var returnValue = window.showModalDialog(pageName, modalArguments, sFeatures);
		return returnValue;	
}

//Fills in the controls in the ObjectBrowser popup window with data from the modal windows arguments
function populateObjectBrowser()
{
	var arguments = new Array();
	arguments = window.dialogArguments;
	var objectType = arguments.pop();
	//The first argument specifies what type of object we're browsing
	if(objectType == 'PartnerOpportunity')
	{
		var arg1 = document.getElementById('smbPartnerOpportunitySummary_DaysHeldData');
		var arg2 = document.getElementById('smbPartnerOpportunitySummary_NonServerRevenueData');
		var arg3 = document.getElementById('smbPartnerOpportunitySummary_ServerRevenueData');
		var arg4 = document.getElementById('smbPartnerOpportunitySummary_DescriptionData');
		var arg5 = document.getElementById('smbPartnerOpportunitySummary_PostalCodeData');
		var arg6 = document.getElementById('smbPartnerOpportunitySummary_CityData');
		if (arg1 != null)
			arg1.value = (arguments.pop()).replace(eval("/(~\\|~\\|)/ig"), "\r\n");
		if (arg2 != null)
			arg2.value = (arguments.pop()).replace(eval("/(~\\|~\\|)/ig"), "\r\n");
		if (arg3 != null)
			arg3.value = (arguments.pop()).replace(eval("/(~\\|~\\|)/ig"), "\r\n");
		if (arg4 != null)
			arg4.value = (arguments.pop()).replace(eval("/(~\\|~\\|)/ig"), "\r\n");
		if (arg5 != null)
			arg5.value = (arguments.pop()).replace(eval("/(~\\|~\\|)/ig"), "\r\n");
		if (arg6 != null)
			arg6.value = (arguments.pop()).replace(eval("/(~\\|~\\|)/ig"), "\r\n");
	}
}
//Get the control based on id 
function GetControl(id)
{
	var oForm = getCorrectForm();
  	for ( iLoop = 0; iLoop < oForm.length; iLoop++ )
	{
		control = oForm.elements[iLoop];
		if(control.id.indexOf(id) != -1)
		{	
			return control ;
		}
	}
}
	
	
	var timesClicked = 0;
	//Some pages use client-side validators and some do not.  This function
	//runs the validators if they exist.
	function PageValidForSubmitting()
	{
		try
		{
			if (Page_ValidationActive == true)
			{
				ValidatorOnSubmit();
				if (Page_IsValid == false)
				{
					//In the case of a save reset the counter
					//since the page was not validated.
					timesClicked = 0;
					return event.returnValue;
				}
				else
					return true;
			}
			else
				return true;
		}
		catch(e)
		{
			//Page did not load web ui validation
			return true;
		}	
	}		
				
	//Function to prevent users from clicking the Save button multiple times

	function formSubmit()
	{	
		//Check to see if this is the first or subsequent click
	    if (PageValidForSubmitting() == true)
	    {
			if (timesClicked > 0)
				return false;
			else
			{
				timesClicked++;
				return true;
			}
		}
		else
		{
			FocusInvalidField();
			return false;
		}
	}
	
 //Function to determine field to focus on.
 function FocusInvalidField() 
 {
	try
	{
		var validationField, focusField;

		if (typeof(Page_ValidationSummaries) == "undefined") 
			return;
			
		//Go through each validator 
		for (i=0; i < Page_Validators.length; i++) 
		{
			if (Page_Validators[i].isvalid == false)
			{
				validationField = Page_Validators[i];
				i = Page_Validators.length;
			}
		}
	        
		//Focus on the invalid field       
		focusField = document.all[validationField.controltovalidate];
		focusField.focus();
		//Highlight if the field is a textbox
		if (focusField.type == "text")
			focusField.select();
	}
	catch(e)
	{
	}	
}
	
 
