/* CommonJavascriptFunctions.js contains javascript functions 
	that are commonly used across several application pages
 
 Revision History:
 Date			Programmer			Revision Description
 -----------	---------------	--------------------------------------------
 2003 Oct      Andrea Callin       initial release

 Other Notes:
*/

/*
	This function allows for a control to cause a postback event
	.NET will automatically generate and insert this javascript
	function when you indicate a control is autopostback.
	This code may be duplicated in the Plumtree portal if multiple
	pages have postback events.  Because the form name is specified in 
	teh javascript function, this will cause an unexpected result in the postback 
	(i.e the wrong result form is displayed)
	
	To solve this problem, this function has been customised and
	can be custom called from a Plumtree portal page to cause a custom autopostback
	instead of the generic autopostback in .NET
	This function also allows the setting of a single specified value to a specified field 
	before postback occurs - useful for setting flag fields
	There are 2 ways to implement this (they seem to work differently with different controls)
	1.
	don't set any controls (i.e drop down lists) as autopostback, instead handle them this way:
	add the following 2 hidden fields to your form
	<input type="hidden" name="__EVENTTARGET">
	<input type="hidden" name="__EVENTARGUMENT">	
	now set up the custom autopostback in the PageLoad function.
	cboDepartment.Attributes.Add("onchange", "gfnTransit__doPostBack('cboDepartment','','frmGetEmployeeGroup');")
	
	2.
	leave controls (i.e buttons) as autopostback
	and remove the default click event and replace it with the custom one by placing the following code in the
	page load
	cmdFirst.Attributes.Remove("onclick")
    cmdFirst.Attributes.Add("onclick", "gfnTransit__doPostBack('cmdFirst','','frmSkatingTimes');")
        
*/
function RouteSchedulePostBack(eventTarget, eventArgument,strFormName, strTargetField, strTargetValue)
{
		var theform = document.forms[strFormName];
		theform.__EVENTTARGET.value = eventTarget.replace(/\$/g, ":");
		theform.__EVENTARGUMENT.value = eventArgument;
		//check if value needs to be passed through to form submit
		if (strTargetField != '')
			theform[strTargetField].value = strTargetValue;
		theform.submit();
}

function gfnTransit__doPostBack(eventTarget, eventArgument, strFormName) {
		var theform = document.forms[strFormName];
		theform.__EVENTTARGET.value = eventTarget;
		theform.__EVENTARGUMENT.value = eventArgument;
		theform.submit();
	}


/*this function circumvents the ASP.NET natural postback functionality and
allows a post to a different page while still allowing all the native .NET
form features
this function replaces a part of the Old(existing) form url with a new part of the url
it does not simply replace the whole url to ensure that surrounding parts of the url
i.e plumtree url redirection stuff stays intact
to implement this function in a page, simply add a line of code to the Page_Load event
 that adds an onclick attribute to the submit button 
(if there is an existing Submit button onclick event - just add the line of code that calls noPostBack there)
i.e: cmdSubmit.Attributes.Add("onclick", "gfnTransit_SwitchPostBackUrl('GetEmployeeGroups_Portlet.aspx','EmployeeList.aspx','frmGetEmployeeGroup','_blank','NOVIEWSTATE');
this function can also be used to change back to allow the form to be submitted back to itself in certain circumstances (i.e for drop down list changes)
cboDepartment.Attributes.Add("onclick", "gfnTransit_SwitchPostBackUrl('EmployeeList.aspx','GetEmployeeGroups_Portlet.aspx','frmGetEmployeeGroup','_self','__VIEWSTATE');")
*/
function gfnTransit_SwitchPostBackUrl(strOldFormAction,strNewFormAction, strFormName, strNewFormTarget,strViewState)
{
	var strNewPostBackUrl;
	var idx;
	var reRegExp;
	//create regular expression using the page that is in the existing form post url
	reRegExp = new RegExp(strOldFormAction,"i");
	
    if(document.layers) //The browser is Netscape 4
    {
		strNewPostBackUrl = document.forms[strFormName].action
		idx = strNewPostBackUrl.indexOf(".aspx");
		strNewPostBackUrl = strNewPostBackUrl.substring(0, idx + 5);
		strNewPostBackUrl = strNewPostBackUrl.replace(reRegExp,strNewFormAction)
        document.forms[strFormName].__VIEWSTATE.name = strViewState;
        document.forms[strFormName].action = strNewPostBackUrl;
        document.forms[strFormName].target = strNewFormTarget;
        
    }
    else //It is some other browser that understands the DOM
    {
		
		strNewPostBackUrl = document.forms[strFormName].action
		idx = strNewPostBackUrl.indexOf(".aspx");
		strNewPostBackUrl = strNewPostBackUrl.substring(0, idx + 5);
		strNewPostBackUrl = strNewPostBackUrl.replace(reRegExp,strNewFormAction)
		document.forms[strFormName].action = strNewPostBackUrl;
		document.forms[strFormName].target = strNewFormTarget;
        document.forms[strFormName].__VIEWSTATE.name = strViewState;
       
       
    }
}

/*
	This Function will replace the submit url (action) with the same url with
	an appended # tag to ensure that the portal displays in the correct place when it returns
*/
function gfn_Transit_ReplaceActionUrl(strFormName) {
		var strAction;
		
		//create regular expression the new # tag
		var theform = document.forms[strFormName];
		strAction = theform.action;
		theform.action = strAction;		
	}


//This function receives a Route Number from a child form (Route Lookup) and submits the Route Schedule parent form
function AutoSubmitRouteSchedule(strRouteNumber)
{
	var wndRouteSchedule = parent.window.opener;
	if (wndRouteSchedule != null)
	{
		wndRouteSchedule.document.forms["frmRouteScheduleForm"].txtRouteNumber.value = strRouteNumber;
		if (wndRouteSchedule.ValidateRouteSchedule())
		{
			wndRouteSchedule.gfnTransit_SwitchPostBackUrl('RouteSchedule.aspx','RouteSchedule_Results.aspx','frmRouteScheduleForm','_blank','NOVIEWSTATE');
			wndRouteSchedule.RouteSchedulePostBack('', '','frmRouteScheduleForm', '','');
		}
	}
	else
		alert("Please return to the Route Schedule page to display a Route Schedule");
}

function SetParentWindowRouteNumber(strRouteNumber)
{
	var wndRouteSchedule = parent.window.opener;
	if (wndRouteSchedule != null)
	{
		wndRouteSchedule.document.forms["frmRouteScheduleForm"].txtRouteNumber.value = strRouteNumber;
	}
	else
		alert("Please return to the Route Schedule page to display a Route Schedule");
}

//This function receives a Route Number from a child form (Route Lookup) and submits the Route Schedule parent form
function AutoSubmitBusStopSchedule(strBusStopNumber)
{
	var wndRouteSchedule = parent.window.opener;
	if (wndRouteSchedule != null)
	{
		wndRouteSchedule.document.forms["frmBusStopScheduleForm"].txtBusStopNumber.value = strBusStopNumber;
		if (wndRouteSchedule.ValidateBusStopSchedule())
		{
			wndRouteSchedule.gfnTransit_SwitchPostBackUrl('BusStopSchedule.aspx|BusStopLookup.aspx','BusStopSchedule_Results.aspx','frmBusStopScheduleForm','_blank','NOVIEWSTATE');
			wndRouteSchedule.RouteSchedulePostBack('', '','frmBusStopScheduleForm', '','');
		}
	}
	else
		alert('The Bus Stop Schedule window has been closed, you must start a new Bus Stop Schedule Search');
}

/*This function loops until the form exists, the field exists and the combo boxes are populatd (if applicable)
with the expectd values, at that point it submits the form to display the results*/
var intAutoSubmitTripInfiniteLoopCatch = 0;
function AutoSubmitTrip(strSelectedStartLandMarkID, strSelectedDestinationLandMarkID)
{ 
	intAutoSubmitTripInfiniteLoopCatch +=1;
	if (intAutoSubmitTripInfiniteLoopCatch <50)
	{
		var blnValidDestinationAndStartLandmarks = true;
		if (document !=null)
		{
			if (document.forms !=null)
			{
				if (document.forms["frmTripSolutionForm"] !=null)
				{
					if (document.forms["frmTripSolutionForm"].cboDestinationLandMarks !=null)
					{
						if (strSelectedStartLandMarkID !="")
						{
							if (document.forms["frmTripSolutionForm"].cboStartLandMarks[document.forms["frmTripSolutionForm"].cboStartLandMarks.selectedIndex].value !=
								strSelectedStartLandMarkID)
									blnValidDestinationAndStartLandmarks = false;
						}
						if (strSelectedDestinationLandMarkID !="")
						{
							if (document.forms["frmTripSolutionForm"].cboDestinationLandMarks[document.forms["frmTripSolutionForm"].cboDestinationLandMarks.selectedIndex].value !=
								strSelectedDestinationLandMarkID)
							{
								blnValidDestinationAndStartLandmarks  = false;
							}
						}
						if (blnValidDestinationAndStartLandmarks==false)
						{
							window.setTimeout("AutoSubmitTrip('" + strSelectedStartLandMarkID + "','" + strSelectedDestinationLandMarkID + "') ;",500);
						}
						else
						{							
							if (ValidateTripSolution())
							{
								intAutoSubmitTripInfiniteLoopCatch = 0;
								gfnTransit_SwitchPostBackUrl('TripSolution.aspx|BusStopLookup.aspx','TripSolution_Results.aspx','frmTripSolutionForm','_blank','NOVIEWSTATE');
								RouteSchedulePostBack('', '','frmTripSolutionForm', '','');

							}
						}
					}
					else
						window.setTimeout("AutoSubmitTrip('" + strSelectedStartLandMarkID + "','" + strSelectedDestinationLandMarkID + "') ;",500);
				}
				else
					window.setTimeout("AutoSubmitTrip('" + strSelectedStartLandMarkID + "','" + strSelectedDestinationLandMarkID + "') ;",500);
			}
			else
				window.setTimeout("AutoSubmitTrip('" + strSelectedStartLandMarkID + "','" + strSelectedDestinationLandMarkID + "') ;",500);
		}
		else
			window.setTimeout("AutoSubmitTrip('" + strSelectedStartLandMarkID + "','" + strSelectedDestinationLandMarkID + "') ;",500);
	}
	else
	{
		intAutoSubmitTripInfiniteLoopCatch = 0;
		alert("Early Late Trip could not be displayed as requested, please use the Trip Solution Form to request your trip");
	}
}

//This function receives a Route Number from a child form (Route Lookup) and submits the Route Schedule parent form
function ReturnBusStopNumber(strBusStopNumber,strFormName,strTextBoxName)
{
	var wndRouteSchedule = parent.window.opener;
	if (wndRouteSchedule != null)
	{
		wndRouteSchedule.document.forms[strFormName][strTextBoxName].value = strBusStopNumber;
	}
}

//This function resubmits the parent form - indicating that a return trip has been selected, so the
//start and destination fields will be reversed
function SetModifyTrip(strModifyTripType,strDate,strHour,strMinutes)
{
	var wndRouteSchedule = parent.window.opener;
	var intCount;
	if (wndRouteSchedule != null)
	{
		wndRouteSchedule.focus();
		wndRouteSchedule.document.forms['frmTripSolutionForm']['txtHiddenModifyTrip'].value = strModifyTripType
		/*set date, hour and minutes input fields on the form to the value on the results*/
		if (strDate !='')
			wndRouteSchedule.document.forms['frmTripSolutionForm']['txtTravelDate'].value=strDate
		if (strHour !='')
		{
			for (intCount=0;intCount<wndRouteSchedule.document.forms['frmTripSolutionForm']['cboHour'].length;intCount++)
			{
				if (wndRouteSchedule.document.forms['frmTripSolutionForm']['cboHour'][intCount].value==strHour)
				{
					wndRouteSchedule.document.forms['frmTripSolutionForm']['cboHour'].selectedIndex=intCount;
				}
				
			}
		}
		if (strMinutes !='')
		{
			for (intCount=0;intCount<wndRouteSchedule.document.forms['frmTripSolutionForm']['cboMinute'].length;intCount++)
			{
				if (wndRouteSchedule.document.forms['frmTripSolutionForm']['cboMinute'][intCount].value==strMinutes)
				{
					wndRouteSchedule.document.forms['frmTripSolutionForm']['cboMinute'].selectedIndex=intCount;
				}
				
			}
		}
		wndRouteSchedule.gfnTransit_SwitchPostBackUrl('TripSolution_Results.aspx','TripSolution.aspx','frmTripSolutionForm','_self','__VIEWSTATE');
		wndRouteSchedule.RouteSchedulePostBack('', '','frmTripSolutionForm', '','');
		
	}
	else
		alert('The Trip Solution window has been closed or your browser cannot perform this function, please go back and start a New Trip Solution for your return trip');
}

//This function sets the Stop Time to the desired value (this function is called before submitting to the BusStopSchedule results page
//This function is called from the Trip Solutions Results page.  The user clicks on a Bus Stop and instead
//of using the original Trip Time to generate the Bus Stop Schedule, use the time associated with that specific Option
function gfn_SetStopTime(strHourField,strHourValue, strMinuteField, strMinuteValue)
{
	//set hour and minute fields
		if (strHourField != '')
			document.forms['frmTripSolutionResults'][strHourField].value = strHourValue;
	//set hour and minute fields
		if (strMinuteField != '')
			document.forms['frmTripSolutionResults'][strMinuteField].value = strMinuteValue;
}

function openWindow(URL, windowName, windowFeatures)
{
    if (URL.indexOf("http") < 0)
    {
        var strNewPostBackUrl;
	    var idx;
		strNewPostBackUrl = document.location.href;
		idx = strNewPostBackUrl.indexOf("/transit/");
		strNewPostBackUrl = strNewPostBackUrl.substring(0, idx + 9);
		URL = strNewPostBackUrl + URL		
    }
	window.open(URL, windowName, windowFeatures);
}