﻿// JScript File

//////////////////////////////////////////////////////////////
// Globals
//////////////////////////////////////////////////////////////

// Used during debug mode to update window size message
var _isDebug;

// Used to hold the id of the button that was clicked
var currentActionButtonId;

// Message displayed in the status bar during AJAX calls
var _pleaseWaitMessage = "Please Wait...";

// AJAX Messages (compatibility, session timeout, max request length, SQL timeout, etc.)
var _ajax_CompatibilityMessage = "The entire suite of TEMS web applications uses AJAX technology and your browser settings are configured to disabled the component required by AJAX.  \n\nPlease contact the CEVA Helpdesk for more information regarding this issue.";
var _ajax_SessionTimeoutMessage = "Your session has expired, please login again."; 
var _ajax_MaxRequestLengthMessage = "Your request exceeds the maximum allowed.  Please try limiting your criteria and re-try your request again.";
var _ajax_SQLTimeoutMessage = "TEMS is currently experiencing a large volume of traffic.  Please re-try your request again.";

//////////////////////////////////////////////////////////////
// Redirect to home page on timeout (iframe, popup, etc.)
//////////////////////////////////////////////////////////////
function SiteTimeout( url )
{
    if (parent.location.href!=window.location.href) 
    { 
        window.open( url,'_top' ); 
    }
    else if (window.opener)
    { 
        window.opener.location = url;
        window.close();
    }
}

//////////////////////////////////////////////////////////////
// Function to set the clicked button for later use
//////////////////////////////////////////////////////////////
function Processing(obj)
{
	// Disable the buttons, set the clicked button to "Processing..." 
	// and continue to raise the button click event
	if ( obj != null && obj != undefined )
	{
	    // Store off the button that is disabled
        currentActionButtonId = obj.id;
	
        // Disable the button (gets re-enabled by the EndRequestHandler or a normal postback)
		obj.disabled = true;

        // Make sure the focus is on the page not the next button
        window.focus();

		// Continue the event
		javascript:__doPostBack( obj.name, null);
	}
}

//////////////////////////////////////////////////////////////
// Worker function to disable all buttons on the page
//////////////////////////////////////////////////////////////
function DoDisableButtons()
{
	// Get the Buttons to disable
	var buttonCollection = document.body.getElementsByTagName("BUTTON");
	if (buttonCollection!=null)
	{
	    for (i=0; i<buttonCollection.length; i++)
		{
			buttonCollection[i].disabled = true;
		}
	}

	// Get the input - submit & button to disable
	var inputCollection = document.body.getElementsByTagName("INPUT");
	if (inputCollection!=null)
	{
	    for (i=0; i<inputCollection.length; i++)
		{
			if ( inputCollection[i].type.toUpperCase() == "SUBMIT" || inputCollection[i].type.toUpperCase() == "BUTTON" || inputCollection[i].type.toUpperCase() == "IMAGE" )
			{
				inputCollection[i].disabled = true;
			}
		}
	}
}

//////////////////////////////////////////////////////////////
// AJAXInitializeHandler Helper function 
//////////////////////////////////////////////////////////////
function InitializeRequest(sender, args)
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if ( prm.get_isInAsyncPostBack() ) 
    {
        args.set_cancel(true);
    }
}

//////////////////////////////////////////////////////////////
// AJAXBeginRequestHandler Helper function 
//////////////////////////////////////////////////////////////
function BeginRequestHandler(sender, args)
{
    window.status = _pleaseWaitMessage;
    document.body.style.cursor = "wait";
}

//////////////////////////////////////////////////////////////
// AJAXEndRequestHandler Helper function 
//    will re-enable the button if a error happens
//////////////////////////////////////////////////////////////
function EndRequestHandler(sender, args)
{
    window.status = "";
    document.body.style.cursor = "default";
    var currentActionButton;    
    
    // Get the current action button if it exists
    if ( currentActionButtonId != null )
    {
        currentActionButton = document.getElementById( currentActionButtonId );
        currentActionButtonId = null;
    }
    
    if ( args.get_error() != undefined )
    {
		var message = args.get_error().message;
		var response = "";

        // Make sure we have a response to look at
		if ( args.get_response().get_responseAvailable() )
		{
		    args.get_response().get_responseData();
		}

        // Check for common error types
        if ( response.indexOf( "document.AUTOSUBMIT.submit();" ) != -1 )
		{
		    // Check to see if we are getting a Siteminder session timeout		
		    // and if so, give the user a message & redirect to the home page
			alert( _ajax_SessionTimeoutMessage );
			args.set_errorHandled(true);
			top.location = "/default.aspx";
		}
		else if ( message.indexOf( "System.Web.HttpException: Maximum request length exceeded." ) != -1 )
	    {
	        // Check to see if the request exceeded the max length
	        alert( _ajax_MaxRequestLengthMessage );
	        args.set_errorHandled(true);
	    }
		else if ( message.indexOf( "The timeout period elapsed prior to completion of the operation or the server is not responding." ) != -1 )
	    {
	        // Check to see if the request exceeded the max length
	        alert( _ajax_SQLTimeoutMessage );
	        args.set_errorHandled(true);
	    }
        
        // If there was an error we may need to re-enable the button that caused the event
        if ( currentActionButton != null )
        {
            if ( currentActionButton.disabled )
            {
                currentActionButton.disabled = false;
            }
        }
    }
    
    // Set the focus back to the item that caused the event
    if ( currentActionButton != null )
    {
        currentActionButton.setActive();
    }
}

//////////////////////////////////////////////////////////////
// Abort the AJAX call for the <ESC> key
//////////////////////////////////////////////////////////////
function AbortRequestHandler()
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if ( prm.get_isInAsyncPostBack() ) 
    {
        if ( currentActionButtonId != null )
        {
            currentActionButton = document.getElementById( currentActionButtonId );
            currentActionButton.disabled = false;
            currentActionButtonId = null;
        }
        prm.abortPostBack();
    }
}

//////////////////////////////////////////////////////////////
// Check for AJAX compatibility
//////////////////////////////////////////////////////////////
function CheckAJAXCompatibility()
{
    var xmlRequest,e;
    try 
    {
        xmlRequest = new XMLHttpRequest();
    }
    catch(e)
    {
        try 
        {
            xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e) {}
    }
    // Check to see if they can use AJAX
    if ( xmlRequest == undefined || xmlRequest == null )
    {
        alert(_ajax_CompatibilityMessage);
    }
}

//////////////////////////////////////////////////////////////
// Open Popup Function
//////////////////////////////////////////////////////////////
function OpenPopup(url, name, width, height, toolbars, scrollbars, status, menubar, resizable)
{
	// Get the screen resolution so we can center the dialog box
	var nScreenWidth 	= window.screen.width;
	var nScreenHeight	= window.screen.height;
	var sWindowsLocationText = "";

	// If we have the width/height create the centering info
	if (nScreenWidth != "" && nScreenHeight != "")
	{
		sWindowsLocationText = ",left=" + (nScreenWidth - width) / 2;
		sWindowsLocationText +=  ",top=" + (nScreenHeight - height) / 2;  // Special to remove space for status bar
	}

	// if in debug mode, always make popups resizable and show the status bar
	if (_isDebug == true)
	{
	    status = "Yes";
	    resizable = "Yes";
	}

	var parameters = "width=" + width + ",height=" + height + ",toolbars=" + toolbars + ",scrollbars=" + scrollbars + ",status=" + status + ",menubar=" + menubar + ",resizable=" + resizable + sWindowsLocationText;

	var myPopup = window.open( url, name, parameters );
    myPopup.focus();
	return myPopup;
}

//////////////////////////////////////////////////////////////
// Show the calendar control
//////////////////////////////////////////////////////////////
function ShowCalendar(returnTextBox, currentDate, calImageName)
{	
	x = getOffsetLeft(document.images[calImageName]) + document.images[calImageName].width; 
	y = getOffsetTop(document.images[calImageName]);
	
	// Handle adjusting for the bottom/side of a page
	if ( x + 200 > document.body.clientWidth )
	{
		x = x - 200;
		y = y + 22;
	}
	if ( y + 153 > document.body.clientHeight )
	{
		y = y - 155;
		x = x - 22;
	}

    var calendarIFrame = document.getElementById("CalendarIFrame");

	if ( calendarIFrame.style.display == "block" )
	{
		calendarIFrame.style.display = "none";
	}
	else if ( document.all.CalendarIFrame.style.display == "none" )
	{
		calendarIFrame.style.left = x + 4;
		calendarIFrame.style.top = y;
		calendarIFrame.src = "../_Controls/calendar.aspx?ReturnTextBox=" + returnTextBox + "&CurrentDate=" + currentDate;
		calendarIFrame.style.display = "block";
	}
}

function getOffsetLeft (el) 
{
    var ol = el.offsetLeft;
    while ((el = el.offsetParent) != null)
    {
        ol += el.offsetLeft;
    }
    return ol;
}

function getOffsetTop (el) 
{
    var ot = el.offsetTop;
    while((el = el.offsetParent) != null)
    {
        ot += el.offsetTop;
    }
    return ot;
}

//////////////////////////////////////////////////////////////
// Hide the calendar control
//////////////////////////////////////////////////////////////
function HideCalendar()
{
    var calendarIFrame = document.getElementById("CalendarIFrame");
	if(calendarIFrame != null)
	{
		// If the calendar is visible then hide it
		if ( calendarIFrame.style.display == "block" )
		{
			calendarIFrame.style.display = "none";
		}
	}
}

//////////////////////////////////////////////////////////////
// New calendar control
//////////////////////////////////////////////////////////////
function Calendar_Button_OnClick(alignElement, calendar, textBox, dateFormat )
{
    //alert(textBox.value);
    if (calendar.get_popUpShowing())
    {
        calendar.hide();
    }
    else
    {
        var date;
        var parts = textBox.value.split("/");
        
        if ( parts.length == 3 )
        {
            if ( isNaN( parts[0] ) || isNaN( parts[1] ) || isNaN( parts[2] ) )
            {
                date = new Date();
            }
        	else if ( dateFormat == "dd/MM/yyyy" || dateFormat == "d/MM/yyyy" || dateFormat == "d/M/yyyy" )
		    {
			    date = new Date( parts[2], parts[1]-1, parts[0] );
		    }
		    else if ( dateFormat == "yyyy/MM/dd" || dateFormat == "yyyy/M/d" )
		    {
			    date = new Date( parts[0], parts[1]-1, parts[2] );
		    }
		    else
		    {
			    date = new Date( parts[2], parts[0]-1, parts[1] );
		    }	
        }
        else
        {
            date = new Date();
        }
        calendar.setSelectedDate( date );
        calendar.show(alignElement);
    }
}
function Calendar_Button_OnMouseUp(calendar)
{
    if (calendar.get_popUpShowing())
    {
        event.cancelBubble=true;
        event.returnValue=false;
        return false;
    }
    else
    {
        return true;
    }
}

//////////////////////////////////////////////////////////////
// Show the Page Message Div & IFrame
//////////////////////////////////////////////////////////////
function ShowPageMessage()
{
	var pageMessageDiv = document.getElementById("PageMessageDiv");
	var pageMessageiFrame = document.getElementById("PageMessageIFrame");
	if ( pageMessageDiv != null && pageMessageiFrame != null )
	{
		toggleDiv( "PageMessageDiv", 1 );
		toggleIFrame( "PageMessageIFrame", 1 );
	}
}

//////////////////////////////////////////////////////////////
// Set Hide Info Message	
//////////////////////////////////////////////////////////////
function HidePageMessage()
{
	toggleDiv("PageMessageDiv",0);
	toggleIFrame("PageMessageIFrame",0);
}

//////////////////////////////////////////////////////////////
// Hide/Show a Div
//////////////////////////////////////////////////////////////
function toggleDiv(DivID, State) // 1 visible, 0 hidden
{
	var obj = document.getElementById(DivID);
	obj.style.visibility = State ? "visible" : "hidden";
	if (State == 0)
	    obj.style.zIndex = -99;
}

//////////////////////////////////////////////////////////////
// Hide/Show a IFrame
//////////////////////////////////////////////////////////////
function toggleIFrame(FrameID, State) // 1 visible, 0 hidden
{
	var obj = document.getElementById(FrameID);
	obj.style.visibility = State ? "visible" : "hidden";
	if (State == 0)
	    obj.style.zIndex = -100;
}

//////////////////////////////////////////////////////////////
// Hide/Show a Table
//////////////////////////////////////////////////////////////
function toggleTable(TableID, State) // 1 visible, 0 hidden
{
	var obj = document.getElementById(TableID);
	//alert(obj)
	if ( obj != null )
	{
	    obj.style.display = State ? "inline" : "none";
	}
}

//////////////////////////////////////////////////////////////
// Set focus and select a element if it exists	
//////////////////////////////////////////////////////////////
function SetFocus(FormFieldName)
{
	var obj = document.getElementById(FormFieldName);
	if ( obj != null && obj != undefined )
	{
		obj.focus();
		if ( obj.options == null )
		{
			obj.select();	
		}
	}
}

//////////////////////////////////////////////////////////////
// Checks all check boxes in the grid calling it.
//////////////////////////////////////////////////////////////
function toggleCheckBoxChecked( checkbox )
{
	parentObj = GetParentByType( checkbox, "TABLE" );

	// Get all input types from the parent container	
	var colInput =  parentObj.all.tags('input');

	// iterate all the check boxes on the page with
	// this group name and set their checked value accordingly.
	for ( i = 0; i < colInput.length; i++ )
	{
		var myType = colInput[i].type;
      if ( myType == 'checkbox' )
		{
			colInput[i].checked = checkbox.checked;
		}
	}
}

//////////////////////////////////////////////////////////////
// Checks all check boxes in the grid calling it.
//////////////////////////////////////////////////////////////
function ClickCheckBox( checkbox )
{
    if (checkbox != null && checkbox.checked != null)
    {
        checkbox.checked = !checkbox.checked;
    }
}

//////////////////////////////////////////////////////////////
// Set radio button state
//////////////////////////////////////////////////////////////
function SetRadioButtonCheckState( checkedObject )
{
    if (checkedObject) // If null or undefined, will evaluate to false. 
    {
	    parentObj = GetParentByType(checkedObject, "TABLE");
	    if (parentObj) // If null or undefined, will evaluate to false. 
	    {
	        // Get all input types from the parent container	
	        var colInput =  parentObj.all.tags('input');
	        if (colInput) // If null or undefined, will evaluate to false. 
	        {
	            // iterate all the radio buttons on the page with
	            // this group name and set their state to unchecked.
	            for (i = 0; i < colInput.length; i++)
	            {
		            var myType = colInput[i].type;
                    if (myType == 'radio')
		            {
			            colInput[i].checked = false;
		            }
	            }
                // finally set the checked state of this radio button to checked.
                checkedObject.checked = true;
            }
        }
    }
}

//////////////////////////////////////////////////////////////
// Set radio button state for Double GridView
//////////////////////////////////////////////////////////////
function SetRadioButtonCheckStateDG( checkedObject )
{
    if (checkedObject) // If null or undefined, will evaluate to false. 
    {
	    parentObj = document.getElementById('resizableDiv');
	    if (parentObj) // If null or undefined, will evaluate to false. 
	    {
	        // Get all input types from the parent container	
	        var colInput =  parentObj.all.tags('input');
	        if (colInput) // If null or undefined, will evaluate to false. 
	        {
	            // iterate all the radio buttons on the page with
	            // this group name and set their state to unchecked.
	            for (i = 0; i < colInput.length; i++)
	            {
		            var myType = colInput[i].type;
                    if (myType == 'radio')
		            {
			            colInput[i].checked = false;
		            }
	            }
                // finally set the checked state of this radio button to checked.
                checkedObject.checked = true;
            }
        }
    }
}

// Function to get the parent object by a specific tag type
function GetParentByType( childObj, findTagType )
{
	var tempObj = childObj.parentNode;
	
    while (tempObj) // If null or undefined, will evaluate to false. 
	{
	    if (tempObj.tagName.toUpperCase() == findTagType.toUpperCase())
		{
		    break;
		}
		tempObj = tempObj.parentNode;
	}
	return tempObj;
}


//////////////////////////////////////////////////////////////
// Runs after browser resize 
//////////////////////////////////////////////////////////////
function PageResize() 
{
	// If the calendar is visible the hide it
    HideCalendar();
	
	// Show the Page Message Dialog
	//ShowPageMessage();
	
	// If the _isDebug global has been set then show the window size in the status bar
	if( _isDebug == true)
	{
	    window.status = document.body.clientWidth + " x " + document.body.clientHeight;
	}
	
	df=document.getElementById('<%=UpdateProgress.ClientID %>');
	if(df)
	{
       dfs = df.style;

       if (window.innerWidth)
       {
          dfs.left = (window.innerWidth - df.offsetWidth) / 2;
          dfs.top = (window.innerHeight - df.offsetHeight) / 2;
       }
       else
       {
          dfs.left = (document.body.offsetWidth - df.offsetWidth) / 2;
          dfs.top = (document.body.offsetHeight - df.offsetHeight) / 2;
       }
   }

}

//////////////////////////////////////////////////////////////
// Generically handles setting an event in javascript so that 
//		an enter key goes to a specific object
//////////////////////////////////////////////////////////////
function HandleDefaultAction(obj)
{
	if ( (event.which && event.which == 13) || (event.keyCode && event.keyCode == 13) ) 
	{
	   document.getElementById(obj).click();
	   return false;
	} 
	else 
	   return true;
}

//////////////////////////////////////////////////////////////
// This function is used by Search\NewLocationSearch.ascx
//////////////////////////////////////////////////////////////
function OpenLocationSearchPopup(FormField, SearchType, AliasDisabled, EntityType, EntityTypeEnabled, CustomerId) 
{
    var AliasInput = eval('document.all.' + FormField + '_txtAlias');
    var Alias = AliasInput.value;
 
	if (SearchType != "")
	{ 
		url = "../Searching/LocationSearch.aspx" + "?SearchType=" + SearchType + "&FormField="+FormField +"&Alias="+Alias +"&AliasDisabled="+AliasDisabled+"&EntityType="+EntityType+"&EntityTypeEnabled="+EntityTypeEnabled+"&CustomerId="+CustomerId;
	}

	// Adjust for less than 1024x768
	var nScreenHeight = window.screen.height;

	if ( nScreenHeight < 770 )
	{
		nScreenHeight = 520;
	}
	else
	{
		nScreenHeight = 675;
	}

	// Open Window
	OpenPopup( url, "locationsearch", 900, (nScreenHeight + 32), "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// This function is used by Searching\EntitySearch.ascx
//////////////////////////////////////////////////////////////
function OpenEntitySearchPopup(FormField, SearchType, EntityDisabled, EntityType, EntityTypeEnabled, CustomerId) 
{
    var EntityInput = eval('document.all.' + FormField + '_txtEntity');
    var Entity = EntityInput.value;
 
	if (SearchType != "")
	{ 
		url = "../Searching/EntitySearch.aspx" + "?SearchType=" + SearchType + "&FormField="+FormField +"&Entity="+Entity +"&EntityDisabled="+EntityDisabled+"&EntityType="+EntityType+"&EntityTypeEnabled="+EntityTypeEnabled+"&CustomerId="+CustomerId;
	}

	// Open Window
	OpenPopup( url, "EntitySearch", 750, 582, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// Clear Values for Entity Search 
//////////////////////////////////////////////////////////////
function Entity_Changed(name)
{
	var txtbox = eval('document.all.' + name + '_txtEntity');
	if ( !txtbox.readOnly )
	{
		var txtbox = eval('document.all.' + name + '_txtEntityId');
		txtbox.value = '';
	}
}

//////////////////////////////////////////////////////////////
// Select the Entity
//////////////////////////////////////////////////////////////
function PickEntity(values, formfield)
{
   // The values parameter is an array that contains
   // all the values to be used to populate the calling form fields.
   var answers = eval(values);   
   
   if(window.opener && !window.opener.closed)
   {
     var xBox = eval('window.opener.document.all.' + formfield + "_txtEntity");
     xBox.value =  answers[0];
                                            
     var  xBox2 = eval('window.opener.document.all.' + formfield + "_txtEntityId");
     xBox2.value = answers[1];    
     
     window.close();
   }
}

//////////////////////////////////////////////////////////////
// Clear Values for Location Search 
//////////////////////////////////////////////////////////////
function Location_Changed(name)
{
	var txtbox = eval('document.all.' + name + '_txtAlias');
	if ( !txtbox.readOnly )
	{
		var imgDetails = eval('document.all.' + name + '_Details');
		imgDetails.alt = 'If there is an alias click to view details otherwise Address Details will be shown';

		var imgDetails = eval('document.all.' + name + '_Search');
		imgDetails.alt = 'Click to Search for Location';

		var imgDetails = eval('document.all.' + name + '_Validate');
		imgDetails.alt = 'Click to Validate Alias';

		var txtbox = eval('document.all.' + name + '_txtEntityId');
		txtbox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIName');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIAdd1');
		xBox.value = '';
     
		var xBox = eval('document.all.' + name + '_txtADIAdd2');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADICity');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIState');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIPostalCode');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADICountryCode');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIContactName');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIDayPhone');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIEvePhone');
		xBox.value = '';
		
		var xBox = eval('document.all.' + name + '_txtADIId');
		xBox.value = '';

		var xBox = eval('document.all.' + name + '_txtEntityName');
		xBox.value = '';

		var xBox = eval('document.all.' + name + '_Search');
		xBox.style.cursor = "hand";
		xBox.disabled = false;		

		var xBox = eval('document.all.' + name + '_Validate');
		xBox.style.cursor = "hand";
		xBox.disabled = false;
	}
}

//////////////////////////////////////////////////////////////
// Show Location Details 
//////////////////////////////////////////////////////////////
function Location_Details(entityId)
{
	if ( entityId == "" )
	{
		return;
	}
	// jrp: expand popup width- was a little too small
	OpenPopup("../Searching/LocationDetails.aspx?entityId=" + entityId, "LocationDetails", 700, 450, "no", "no", "yes");
}

//////////////////////////////////////////////////////////////
// Select the location
//////////////////////////////////////////////////////////////
function PickLocation(values, formfield)
{
    PickLocation(values, formfield, false);
}

function PickLocation(values, formfield, doPostBack)
{
   // The values parameter is an array that contains
   // all the values to be used to populate the calling form fields.
   var answers = eval(values);   
   
   if(window.opener && !window.opener.closed)
   {
     var xBox1 = eval('window.opener.document.all.' + formfield + "_txtEntityName");
     xBox1.value = answers[0];
                                            
     var xImg = eval('window.opener.document.all.' + formfield + "_Details");
     xImg.alt = "Click to View Details for " + answers[0];
     
     var xBox3 = eval('window.opener.document.all.' + formfield + "_txtAlias");
     xBox3.select();
     xBox3.value = answers[1];  
    
     var  xBox4 = eval('window.opener.document.all.' + formfield + "_txtEntityId");
     xBox4.value = answers[2];    
     
     if (doPostBack)
     {
        window.opener.document.forms[0].submit();
     }

     window.close();
   }
}

//////////////////////////////////////////////////////////////
// This function is used by _Controls\RouteSearch.cs
//////////////////////////////////////////////////////////////
function ShowRouteSearch(FormField) 
{
	var url = "../Searching/RouteSearchDlg.aspx?" + "FormField=" + FormField;
		
	OpenPopup(url, "routesearch", 550, 532, "no", "no", "yes", "no")
}

function ShowRouteSearchWithOD(FormField, OriginRequired, Origin, DestinationRequired, Destination ) 
{
   
	var formVar = eval('document.all.'+FormField);

	if (Origin == null || Origin == '')
	{
		var OriginInput = ReturnLocationString('Origin',FormField,formVar);
	}
	else
	{
		var OriginInput = Origin;
	}
	
	if (Destination == null || Destination == '')
	{
		var DestinationInput = ReturnLocationString('Destination',FormField,formVar);
	}
	else
	{
		var DestinationInput = Destination;
	}
	
	//get the destination alias from the selected control
	var url = "../Searching/RouteSearchDlg.aspx?" + "FormField=" + FormField + "&Origin=" + OriginInput + "&OriginRequired=" + OriginRequired + "&Destination=" + DestinationInput + "&DestinationRequired=" + DestinationRequired;
		
	OpenPopup(url, 'routesearch', 600, 532, "no", "no", "yes", "no")
}


//////////////////////////////////////////////////////////////
// Set Return Values for Route Search 
//////////////////////////////////////////////////////////////
function ReturnRouteSearch(returnValues, formfield)
{
	// The values parameter is an array that contains
	// all the values to be used to populate the calling form fields.
	var answers = eval(returnValues); 
  
	if(window.opener && !window.opener.closed)
	{
		var xBox = eval('window.opener.document.all.' + formfield);
		xBox.value =  answers[0];
      
		var xBox1 = eval('window.opener.document.all.' + formfield + 'Id');
		xBox1.select();
		xBox1.value =  answers[1];
	
	   if( 'window.opener.document.all.' + formfield + 'btnPostBack' != null )
	   {
	      var btn = eval('window.opener.document.all.' + formfield + 'btnPostBack');
	      btn.click();
	   }
	   
	   window.close();
	   
	}
}

//////////////////////////////////////////////////////////////
// Clear Values for Route Search 
//////////////////////////////////////////////////////////////
function Route_Changed(name)
{
	var txtbox = eval('document.all.' + name + 'Id');
	txtbox.value = '';
}

//////////////////////////////////////////////////////////////
// This function is used by _Controls\CarrierSearch.cs
//////////////////////////////////////////////////////////////
function ShowCarrierSearch(FormField, Text) 
{
	var url = "../Searching/CarrierSearch.aspx?" + "FormField="+FormField +"&Text=" + Text;
		
	OpenPopup(url, "carriersearch", 600, 582, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// This function is used by _Controls\CarrierSearch.cs
//////////////////////////////////////////////////////////////
function ShowCarrierDetails(FormField, Text) 
{
	if( Text == "" )
	{
		return;
	}
	var url = "../Searching/CarrierDetails.aspx?" + "FormField="+FormField +"&Text=" + Text;
		
	OpenPopup(url, "carrierdetails", 811, 417, "no", "yes", "yes", "no")
}

//////////////////////////////////////////////////////////////
// Set Return Values for Carrier Search 
//////////////////////////////////////////////////////////////
function ReturnCarrierSearch(returnValues, formfield)
{
	// The values parameter is an array that contains
	// all the values to be used to populate the calling form fields.
	var answers = eval(returnValues); 
  
	if(window.opener && !window.opener.closed)
	{
		var xBox = eval('window.opener.document.all.' + formfield);
		xBox.value =  answers[0];
		xBox.select();

		var xBox = eval('window.opener.document.all.' + formfield + 'SCAC');
		xBox.value =  answers[1];
		
		var xBox = eval('window.opener.document.all.' + formfield + 'Name');
		xBox.value =  answers[2];
		
		var xBox = eval('window.opener.document.all.' + formfield + 'Alias');
		xBox.value =  answers[3];
     
		window.close();
	}
}

//////////////////////////////////////////////////////////////
// Clear Values for Carrier Search 
//////////////////////////////////////////////////////////////
function Carrier_Changed(name)
{
	var txtbox = eval('document.all.' + name + 'SCAC');
	txtbox.value = '';
	var txtbox = eval('document.all.' + name + 'Name');
	txtbox.value = '';
	var txtbox = eval('document.all.' + name + 'Alias');
	txtbox.value = '';
}

//////////////////////////////////////////////////////////////
// This function is used by _Controls\RouteSearch.cs
//////////////////////////////////////////////////////////////
function ShowRouteSearch(FormField) 
{
	var url = "../Searching/RouteSearchDlg.aspx?" + "FormField=" + FormField;
		
	OpenPopup(url, "routesearch", 550, 532, "no", "no", "yes", "no")
}

function ShowRouteSearchWithOD(FormField, OriginRequired, Origin, DestinationRequired, Destination ) 
{
   
	var formVar = eval('document.all.'+FormField);

	if (Origin == null || Origin == '')
	{
		var OriginInput = ReturnLocationString('Origin',FormField,formVar);
	}
	else
	{
		var OriginInput = Origin;
	}
	
	if (Destination == null || Destination == '')
	{
		var DestinationInput = ReturnLocationString('Destination',FormField,formVar);
	}
	else
	{
		var DestinationInput = Destination;
	}
	
	//get the destination alias from the selected control
	var url = "../Searching/RouteSearchDlg.aspx?" + "FormField=" + FormField + "&Origin=" + OriginInput + "&OriginRequired=" + OriginRequired + "&Destination=" + DestinationInput + "&DestinationRequired=" + DestinationRequired;
		
	OpenPopup(url, 'routesearch', 600, 532, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// This function is used by Search\LocationSearch.ascx
//////////////////////////////////////////////////////////////
function OpenUserDataPopup(FormName, width, height, url, SessionLoc, AppType) 
{
	url = url + "?FormName=" + FormName + "&SessionLoc=" + SessionLoc +"&AppType="+AppType;
	
	// Get the screen resolution so we can center the dialog box	
	var nScreenWidth 	= window.screen.width;
	var nScreenHeight	= window.screen.height;
	var sWindowsLocationText = "";	

	// If we have the width/height create the centering info
	if (nScreenWidth != "" && nScreenHeight != "")
	{
		sWindowsLocationText = ",left=" + (nScreenWidth - width) / 2; 
		sWindowsLocationText +=  ",top=" + (nScreenHeight - height) / 2; 
	}	
		
	// Open Window
	curVar = OpenPopup(url, 'user_data', width, height, "no", "no", "yes", "no")

    if (!curVar.opener) 
	{
		curVar.opener = self;
	}
}

//////////////////////////////////////////////////////////////
// Set Return Values for Parts Search 
//////////////////////////////////////////////////////////////
function ReturnUserData(formName)
{  
   if(window.opener && !window.opener.closed)
   {
     eval('window.opener.document.' + formName + '.submit();');
     window.close();
   }
}

//////////////////////////////////////////////////////////////
// This function is used by Search\ContainersSearch.ascx
//////////////////////////////////////////////////////////////
function OpenContainersSearchPopup(FormField, width, height, url, CustomerId ) {
   
    var ContainerNumberInput = eval('document.all.' + FormField + '_txtContainerNumber');
    var Container = ContainerNumberInput.value;
    
	var formVar = eval('document.all.'+FormField);
		
	//get the destination alias from the selected control
	url = url + "?FormField="+FormField+"&Container="+Container+"&CustomerId="+CustomerId;
		
	// Open Window
	curVar = OpenPopup(url, 'container_search', width, height, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// Set Return Values for Container Search 
//////////////////////////////////////////////////////////////
function ReturnContainerSearch(values, formfield)
{
   // The values parameter is an array that contains
   // all the values to be used to populate the calling form fields.
   var answers = eval(values); 
  
   if(window.opener && !window.opener.closed)
   {
     var xBox = eval('window.opener.document.all.' + formfield + '_txtContainerID');
     xBox.select();
     xBox.value =  answers[0];
     var xBox = eval('window.opener.document.all.' + formfield + '_txtContainerNumber');
     xBox.value =  answers[1];
     
     var xBox = eval('window.opener.document.all.' + formfield + '_btnPostBack');
		if( xBox != null )
		{
			xBox.click();
		}
	   
	   window.close();
   }
}

//////////////////////////////////////////////////////////////
// Used by the Container Search Control to wipe the description 
// and ID when a user types a value in
//////////////////////////////////////////////////////////////
function Container_Changed(container)
{			
	var name = document.getElementById(container.id+'_txtContainerID');
	name.value = '';
}


//////////////////////////////////////////////////////////////
// This function is used by _Controls\PowerUnitSearch.cs
//////////////////////////////////////////////////////////////
function ShowPowerUnitSearch(FormField, Text) 
{
	var url = "../Searching/PowerUnitSearch.aspx?" + "FormField="+FormField +"&Text=" + Text;
		
	OpenPopup(url, "powerunitsearch", 600, 582, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// Set Return Values for Power Unit Search 
//////////////////////////////////////////////////////////////
function ReturnPowerUnitSearch(returnValues, formfield)
{
	// The values parameter is an array that contains
	// all the values to be used to populate the calling form fields.
	var answers = eval(returnValues); 
  
	if(window.opener && !window.opener.closed)
	{
		var xBox = eval('window.opener.document.all.' + formfield);
		xBox.value =  answers[0];
		xBox.select();

		var xBox = eval('window.opener.document.all.' + formfield + 'SCAC');
		xBox.value =  answers[1];
		
		var xBox = eval('window.opener.document.all.' + formfield + 'Name');
		xBox.value =  answers[2];
		
		var xBox = eval('window.opener.document.all.' + formfield + 'Id');
		xBox.value =  answers[3];
		
		try
		{
		    window.opener.SetPowerUnitSCAC( answers[1] );
		}
		catch (e) {}
     
		window.close();
	}
}

//////////////////////////////////////////////////////////////
// Clear Values for Power Unit Search 
//////////////////////////////////////////////////////////////
function PowerUnit_Changed(name)
{
	var txtbox = eval('document.all.' + name + 'SCAC');
	txtbox.value = '';
	var txtbox = eval('document.all.' + name + 'Name');
	txtbox.value = '';
	var txtbox = eval('document.all.' + name + 'Id');
	txtbox.value = '';
}

//////////////////////////////////////////////////////////////
// This function is used by _Controls\PowerUnitSearch.cs
//////////////////////////////////////////////////////////////
function ShowConveyanceSearch(FormField, Text) 
{
	var url = "../Searching/ConveyanceSearch.aspx?" + "FormField="+FormField +"&Text=" + Text;
		
	OpenPopup(url, "conveyancesearch", 600, 582, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// Set Return Values for Power Unit Search 
//////////////////////////////////////////////////////////////
function ReturnConveyanceSearch(returnValues, formfield)
{
	// The values parameter is an array that contains
	// all the values to be used to populate the calling form fields.
	var answers = eval(returnValues); 
  
	if(window.opener && !window.opener.closed)
	{
		var xBox = eval('window.opener.document.all.' + formfield);
		xBox.value =  answers[0];
		xBox.select();

		var xBox = eval('window.opener.document.all.' + formfield + 'SCAC');
		xBox.value =  answers[1];
		
		var xBox = eval('window.opener.document.all.' + formfield + 'Name');
		xBox.value =  answers[2];
		
		var xBox = eval('window.opener.document.all.' + formfield + 'Id');
		xBox.value =  answers[3];
     
		window.close();
	}
}

//////////////////////////////////////////////////////////////
// Clear Values for Power Unit Search 
//////////////////////////////////////////////////////////////
function Conveyance_Changed(name)
{
	var txtbox = eval('document.all.' + name + 'SCAC');
	txtbox.value = '';
	var txtbox = eval('document.all.' + name + 'Name');
	txtbox.value = '';
	var txtbox = eval('document.all.' + name + 'Id');
	txtbox.value = '';
}

//////////////////////////////////////////////////////////////
// This function is used by Search\PartsSearch.ascx
//////////////////////////////////////////////////////////////
function OpenPartsSearchPopup(FormField, OriginRequired, Origin, DestinationRequired, Destination, CustomerId, width, height, url ) 
{   
    var PartNumberInput = eval('document.all.' + FormField + '_txtPartNumber');
    var Part = PartNumberInput.value;
    
	var formVar = eval('document.all.'+FormField);
	//get the origin alias from the selected control
	if (Origin == null || Origin == '')
	{
		var OriginInput = ReturnLocationString('Origin',FormField,formVar);
	}
	else
	{
		var OriginInput = Origin;
	}
	if (Destination == null || Destination == '')
	{
		var DestinationInput = ReturnLocationString('Destination',FormField,formVar);
	}
	else
	{
		var DestinationInput = Destination;
	}
	
	//get the destination alias from the selected control
	url = url + "?FormField="+FormField+"&Part="+Part+"&Origin="+OriginInput+"&OriginRequired="+OriginRequired+"&Destination="+DestinationInput+"&DestinationRequired="+DestinationRequired+"&CustomerId="+CustomerId;
		
	// Open Window
	curVar = OpenPopup(url, 'part_search', width, height, "no", "no", "yes", "no")
}


//////////////////////////////////////////////////////////////
// This function is used as a utility by OpenPartsSearchPopup
//////////////////////////////////////////////////////////////
function ReturnLocationString(ControlName, FormField, formVar)
{
	var Input = formVar.getAttribute(ControlName + "ControlName", true);
	if (Input != null)
	{
		var Input = eval('document.all.' + Input + '_txtAlias');
	}
	else
	{
		var Input = formVar.getAttribute(ControlName, true);
	}
	if (Input == null)
	{
		var Input = "";
	}
	else
	{
		var Input = Input.value;
	}
	return Input;
}

//////////////////////////////////////////////////////////////
// Set Return Values for Parts Search 
//////////////////////////////////////////////////////////////
function ReturnPartSearch(values, formfield)
{
   // The values parameter is an array that contains
   // all the values to be used to populate the calling form fields.
   var answers = eval(values); 
  
   if(window.opener && !window.opener.closed)
   {
     var xBox = eval('window.opener.document.all.' + formfield + '_txtPartNumber');
     xBox.select();
     xBox.value =  answers[0];
     var xBox = eval('window.opener.document.all.' + formfield + '_txtPartDescription');
     xBox.value =  answers[1];
     var xBox = eval('window.opener.document.all.' + formfield + '_txtPartPackagingID');
     xBox.value =  answers[2];
     
     window.close();
   }
}

//////////////////////////////////////////////////////////////
// Used by the Part Search Control to wipe the description 
// and ID when a user types a value in
//////////////////////////////////////////////////////////////
function Part_Changed(clientId)
{			
	var name = document.getElementById(clientId.id+'_txtPartDescription');
	name.value = '';
	var name = document.getElementById(clientId.id+'_txtPartPackagingID');
	name.value = '';
}

function Part_Validate(clientId)
{			
	var name = document.getElementById(clientId.id+'_imgValidate');
	name.click();
}

//////////////////////////////////////////////////////////////////////////////////////////////
// This function is used by _Controls\LocationSearch.ascx to open the Address Details popup
//////////////////////////////////////////////////////////////////////////////////////////////
function OpenAddressDetailsPopup(FormField, CustomerId, ADIId, ADIName, Add1, Add2, City, State, PostalCode, CountryCode, ContactName, DayPhone, EvePhone) 
{
 
	url = "../Searching/AddressDetails.aspx" + "?CustomerId=" + CustomerId + "&ADIId=" + ADIId + "&FormField="+FormField+"&ADIName="+ADIName+"&Add1="+Add1+"&Add2="+Add2+"&City="+City+"&State="+State+"&PostalCode="+PostalCode+"&CountryCode="+CountryCode+"&ContactName="+ContactName+"&DayPhone="+DayPhone+"&EvePhone="+EvePhone;

	// Open Window
	OpenPopup( url, "addressdetails", 750, 325, "no", "no", "yes", "no")
}

//////////////////////////////////////////////////////////////
// Set Address Values for Location Search 
//////////////////////////////////////////////////////////////
function ReturnLocationSearch(returnValues, formfield)
{
	// The values parameter is an array that contains
	// all the values to be used to populate the calling form fields.
	var answers = eval(returnValues); 
  
	if(window.opener && !window.opener.closed)
	{
		var xBox = eval('window.opener.document.all.' + formfield);
		xBox.value =  answers[0];

		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIName');
		xBox.value =  answers[0];		
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIAdd1');
		xBox.value =  answers[1];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_Details');
        xBox.alt = 'Click to view details for ' + answers[0] + ', ' + answers[1];
     
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIAdd2');
		xBox.value =  answers[2];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADICity');
		xBox.value =  answers[3];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIState');
		xBox.value =  answers[4];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIPostalCode');
		xBox.value =  answers[5];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADICountryCode');
		xBox.value =  answers[6];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIContactName');
		xBox.value =  answers[7];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIDayPhone');
		xBox.value =  answers[8];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIEvePhone');
		xBox.value =  answers[9];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtADIId');
		xBox.value =  answers[10];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtAlias');
		xBox.value =  answers[11];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtEntityId');
		xBox.value =  answers[12];
		
		var xBox = eval('window.opener.document.all.' + formfield + '_txtEntityName');
		xBox.value = answers[0] + ", " + answers[1];		
		
		var xBox = eval('window.opener.document.all.' + formfield + '_Validate');
		xBox.style.cursor = "default";
		xBox.disabled = true;
		xBox.alt = "";

		var xBox = eval('window.opener.document.all.' + formfield + '_Search');
		xBox.style.cursor = "default";
		xBox.disabled = true;
		xBox.alt = "";

		window.close();
	}
}
//////////////////////////////////////////////////////////////
// Generically handles refreshing a opening page and 
//		closing the popup
//////////////////////////////////////////////////////////////
function ReturnAndClose( )
{
	if(window.opener && !window.opener.closed)
	{
		window.opener.document.forms[0].submit();
	}
	window.close();
}
//////////////////////////////////////////////////////////////
// Generically handles refreshing a opening page but NOT 
//		closing the popup
//////////////////////////////////////////////////////////////
function Return( )
{
	if(window.opener && !window.opener.closed)
	{
		window.opener.document.forms[0].submit();
	}
}
//////////////////////////////////////////////////////////////
// This function is used by _Controls\DriverSearch.cs
//////////////////////////////////////////////////////////////
function ShowDriverSearch(FormField, DriverId, DriverNameClient, DriverPhoneClient)
{
	var url = "../Searching/DriverSearch.aspx?" + "FormField="+ FormField + "&DriverId=" + DriverId + "&DriverNameClient=" + DriverNameClient + "&DriverPhoneClient=" + DriverPhoneClient;
		
	OpenPopup(url, "driversearch", 687, 607, "no", "no", "yes", "no")
}
//////////////////////////////////////////////////////////////
// Set Return Values for Location Address Search 
//////////////////////////////////////////////////////////////
function ReturnDriverSearch(controlName, driverId, driverNameClient, driverNameValue, driverContactClient, driverContactValue)
{
	// The values parameter is an array that contains
	// all the values to be used to populate the calling form fields.	
	if(window.opener && !window.opener.closed)
	{
		var xBox = eval('window.opener.document.all.' + controlName + '_txtDriverId');
		xBox.value = driverId;
		
		var xBox1 = eval('window.opener.document.all.' + controlName + '_txtDriverName');
	   xBox1.value = driverNameValue;
   	
	   var xBox2 = eval('window.opener.document.all.' + controlName + '_txtDriverPhone');
	   xBox2.value = driverContactValue;
   	
	   var xBox3 = eval('window.opener.document.all.' + driverNameClient);
	   xBox3.value = driverNameValue;
   	
	   var xBox4 = eval('window.opener.document.all.' + driverContactClient);
	   xBox4.value = driverContactValue;
	}
	window.close();
}
//////////////////////////////////////////////////////////////
// Change the Values for Driver Search 
//////////////////////////////////////////////////////////////
function Driver_Changed(controlName, driverNameClient, driverNameValue, driverContactClient, driverContactValue)
{
	var xBox = eval('document.all.' + controlName + '_txtDriverName');
	xBox.value = driverNameValue;
	
	var xBox1 = eval('document.all.' + controlName + '_txtDriverPhone');
	xBox1.value = driverContactValue;
	
	var xBox2 = eval('document.all.' + driverNameClient);
	xBox2.value = driverNameValue;
	
	var xBox3 = eval('document.all.' + driverContactClient);
	xBox3.value = driverContactValue;
}
//////////////////////////////////////////////////////////////
// Cookie methods used for Confirm logic to track dirty flags 
//////////////////////////////////////////////////////////////
function GetCookie(name)
{
    var arg = name + '=';
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
        {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(' ', i) + 1;
        if (i == 0) break;
    }
    return null;
}
function getCookieVal(offset)
{
    var endstr = document.cookie.indexOf(';', offset);
    if (endstr == -1)
    {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}
function SetCookie(name, value)
{
    SetCookie(name, value, Date(), 
        window.document.location, 
        window.document.domain, 
        null)
}
function SetCookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + '=' + escape(value) +
        ((expires) ? '; expires=' + expires.toGMTString() : '') +
        ((path) ? '; path=' + path : '') +
        ((domain) ? '; domain=' + domain : '') +
        ((secure) ? '; secure' + secure : '');
}
//////////////////////////////////////////////////////////////
// Confirm navigate away methods
//////////////////////////////////////////////////////////////
function InitConfirm(msg)
{
    SetCookie(window.document.nameProp + '.ConfirmMsg', msg);
    SetCookie(window.document.nameProp + '.IsDirty', false);
    SetCookie(window.document.nameProp + '.ShowConfirm', false);
}
function SetConfirmOn()
{
    var msg = GetCookie(window.document.nameProp + '.ConfirmMsg');
    if (msg != null && msg != '')
    {
        window.onbeforeunload = ConfirmExit;
        SetCookie(window.document.nameProp + '.IsDirty', true);
        SetCookie(window.document.nameProp + '.ShowConfirm', true);
    }
}
function SetConfirmOff()
{
    window.onbeforeunload = '';
    SetCookie(window.document.nameProp + '.IsDirty', false);
    SetCookie(window.document.nameProp + '.ShowConfirm', false);    
}
function SuppressConfirm()
{
    window.onbeforeunload = '';
    SetCookie(window.document.nameProp + '.ShowConfirm', false);
}
function ConfirmExit()
{
    var IsDirty = eval(GetCookie(window.document.nameProp + '.IsDirty'));
    var ShowConfirm = eval(GetCookie(window.document.nameProp + '.ShowConfirm'));
    if (IsDirty && ShowConfirm)
    {
        event.returnValue = GetCookie(window.document.nameProp + '.ConfirmMsg');
        __doPostBack( window.document.name, null);
    }
}
// This is needed just to turn Confirm back on if isDirty after SuppressConfirm
// was initiated by a button or tab control.
if (eval(GetCookie(window.document.nameProp + '.IsDirty')))
    SetConfirmOn();


//================================================================
// FlashMessage
//
// Used by LoadAssignment and related pages
//----------------------------------------------------------------
function FlashMessage(text)
{
    try
    {
        var divFlashMessage = document.getElementById("divFlashMessage");
        
        if (text == "")
        {
            divFlashMessage.style.display = "none";
            divFlashMessage.innerHTML = "";
        }
        else
        {
            divFlashMessage.innerHTML = "<span>" + text + "</span>";
            divFlashMessage.style.display = "block";
        }
    }
    catch (e) {}
}

//================================================================
// Callback
//
// Default behavior when a callback is submitted
//----------------------------------------------------------------
function Callback()
{
    try { FlashMessage(_localizedStrings[14944]); /* Please Wait... */ }
    catch (e) 
    {
        try { FlashMessage(_localizedStrings[14513]); /* Processing... */ }
        catch (e) {}
    }
}

//================================================================
// CallbackError
//
// Default behavior when a callback fails
//----------------------------------------------------------------
function CallbackError()
{
    try
    {
        FlashMessage(_localizedStrings[14514]); // Error. Please retry.
    }
    catch (e) {}
}

//================================================================
// CallbackComplete
//
// Default behavior when a callback is complete
//----------------------------------------------------------------
function CallbackComplete()
{
    try
    {
        FlashMessage("");
    }
    catch (e) {}
}

//================================================================
// Constants
//
// Used by Rail Load Assignment to get/set TreeViewNode.Value
//----------------------------------------------------------------
var TV_PARAMETER_SEPARATOR = '|'; 
var TV_KEY_VALUE_SEPARATOR  = '=';

//================================================================
// GetNodeParameters 
//
// Used by Rail Load Assignment to get/set TreeViewNode.Value
//----------------------------------------------------------------
function GetNodeParameters(node)
{
    var parameters = new Array();
    var valueSplit = node.Value.split(TV_PARAMETER_SEPARATOR);
    
    for (var i in valueSplit)
    {
        parameter = valueSplit[i];
        var keyValueArray = parameter.split(TV_KEY_VALUE_SEPARATOR);
        if (keyValueArray.length == 2) 
        {
            parameters[keyValueArray[0]] = keyValueArray[1]; 
        }
    } 
    return parameters;
}

//================================================================
// SetNodeParameters 
//
// Used by Rail Load Assignment to get/set TreeViewNode.Value
//----------------------------------------------------------------
function SetNodeParameters(node, parameters)
{
    var nodeValue = "";
    for (var key in parameters)
    {
        value = parameters[key]; 
        nodeValue += key + TV_KEY_VALUE_SEPARATOR + value + TV_PARAMETER_SEPARATOR;
    }
    node.Value = nodeValue;
}

//================================================================
// SetNodeParameter 
//
// Used by Rail Load Assignment to get/set TreeViewNode.Value
//----------------------------------------------------------------
function SetNodeParameter(node, parameterName, parameterValue)
{
    var parameters = GetNodeParameters(node); 
    
    parameters[parameterName] = parameterValue; 

    SetNodeParameters(node, parameters);
}

//================================================================
// GetNodeParameter 
//
// Used by Rail Load Assignment to get/set TreeViewNode.Value
//----------------------------------------------------------------
function GetNodeParameter(node, parameterName)
{
    var parameters = GetNodeParameters(node); 
    
    return parameters[parameterName];
}

//////////////////////////////////////////////////////////////
// TreeView Helper functions
//
// tv            = the TreeView control being updated.
// tvData        = the Tree View Data Array that holds all the data.
// itemId        = the Id of the item being updated.
// itemIdIndex   = the index of the itemId in tvData array.  Used in GetTreeViewIndex.
// newText       = the new Text for tvData to be changed to.
//////////////////////////////////////////////////////////////
function UpdateTreeViewNodeText( tv, tvData, itemId, itemIdIndex, newText )
{    
	if ( tv && tvData )
	{
		var index        = GetTreeViewIndex( tvData, itemId, itemIdIndex );
		var obj          = tvData[ index ];
		obj[itemIdIndex][1][1] = newText;
		tvData[ index ]  = obj;
		tv.Render();		
	}
}

function GetTreeViewIndex( tvData, itemId, itemIdIndex )
{
	if ( tvData.length )
	{
		for ( var i = 0; i < tvData.length; i++ )
		{
			var obj = tvData[i];			
			if ( obj[itemIdIndex][0][1] == itemId )
			{
				return i;
			}
		}
	}
}

//Fleet Help
var fID = null;
var fName = null;
function FleetChanged(type, lfleetID, lfleetName) 
{
    var fleet = '';
    var fleetName = '';
    fID = lfleetID;
    fName = lfleetName; 
    if(type == '0')
    {
        fleet = document.getElementById(lfleetID).value;
        document.getElementById(lfleetName).value = '';
        if(fleet != '')
        {
           PageMethods.ValidateFleet(fleet, fleetName, onFleetSuccess, onFleetFail);
        }
    }
    else
    {
        fleetName = document.getElementById(lfleetName).value;
        document.getElementById(lfleetID).value = '';
        if(fleetName != '')
        {
            PageMethods.ValidateFleet(fleet, fleetName, onFleetSuccess, onFleetFail);
        }
    }
    
}

function onFleetSuccess(result)
{   
    if(result)
    {
        document.getElementById(fID).value = result[0];
        document.getElementById(fName).value = result[1];
    }
}

function onFleetFail(result)
{   
    OpenFleet(document.getElementById(fName).value);
}

function OpenFleet(name)
{
    var url = '../popup/FleetSearch.aspx';
    if(name != '')
    {
        url = '../popup/FleetSearch.aspx?FleetName='+name;
    }   
    window.frames['frameFleet'].location.href = url;
    document.getElementById('btnOpenFleet').click();
}

function FillFleet(fleetID, fleetName)
{
   if(window.parent)
   {
     var xBox1 = parent.document.getElementById('txtFleetID');
     xBox1.value = fleetID;               
     
     var xBox2 = parent.document.getElementById('txtFleetName');
     xBox2.value = fleetName;
   }
   parent.document.getElementById('btnOpenFleetClose').click();
    
}

function OpenTrip(manifest)
{
    var url = '../bec/TripDetails.aspx';
    if(manifest != '')
    {
        url = '../bec/TripDetails.aspx?Manifest='+manifest;
    }   
    window.frames['frameTrip'].location.href = url;
    document.getElementById('btnOpenTrip').click();
}

function CloseTrip()
{
   parent.document.getElementById('btnOpenTripClose').click();
    
}
/***For Account Selection ***/
function OpenAccount()
{
    var url = '../popup/AccountSelection.aspx';
    window.frames['frameAccount'].location.href = url;
    document.getElementById('btnOpenAccount').click();
}

function CloseAccount(selectedAccCusNo, selectedCusAlias, selectedAccountName)
{
     var ddlCustomer = parent.document.getElementById('ddlCustomer');
     var cusAccounts = selectedCusAlias.split("#$#");
     var cusAccCusNo = selectedAccCusNo.split(",");
                
     if(selectedAccCusNo != '')
     {
            ClearOptionList(ddlCustomer);
            AddToOptionList(ddlCustomer, "-2", "ALL" );
            if(cusAccCusNo.length > 1 )
                AddToOptionList(ddlCustomer, "-3", "SELECTED LIST" );
     
            for(i = 0; i < cusAccCusNo.length; i++)
            {
                AddToOptionList(ddlCustomer, cusAccCusNo[i], cusAccounts[i] );
            }
            parent.document.getElementById("tbSelectedAccCusNo").value = cusAccCusNo;
            
        if(cusAccCusNo.length >= 1 )
            ddlCustomer.selectedIndex = 1;
        else
            ddlCustomer.selectedIndex = 0;
        
    }
    parent.document.getElementById("tbSearchAccCusNo").value = ddlCustomer.options[ddlCustomer.selectedIndex].value;
    parent.document.getElementById("btnOpenAccountClose").click();
}

function ClearOptionList(OptionList) 
{
   for (x = OptionList.length; x >= 0; x--) 
   {
      OptionList[x] = null;
   }
}

function AddToOptionList(OptionList, OptionValue, OptionText)
{
   // Add option to the bottom of the list
   OptionList[OptionList.length] = new Option(OptionText, OptionValue);
}

function FillSelectedAccount()
{
    var e = document.getElementById("ddlCustomer");
    parent.document.getElementById("tbSearchAccCusNo").value = e.options[e.selectedIndex].value;
//    if(e.options[e.selectedIndex].value == '-2')
//        OpenAccount();
}

function checkboxclick(cb)
{   
    if (cb.checked)
    {
       cb.checked= false;
    }
    else
    {
       cb.checked= true;
    }
}

function checkboxcellclick(cb, tb)
{        
    checkB = document.getElementById(cb);
    tb1 = document.getElementById(tb);
    if(tb1.value == "1")
    {
        checkB.checked = false;
        tb1.value = "0";
    }
    else
    {
        checkB.checked = true;
        tb1.value = "1";        
    }
}

var allSelected = false;

function checkboxcellclickALL(cb)
{        
    checkB = document.getElementById(cb);
    if(allSelected)
    {
        checkB.checked = false;
        allSelected = false;
    }
    else
    {
        checkB.checked = true;
        allSelected = true;        
    }
  
    var grid = document.getElementById('gvDetails');
    var cell;
    if(grid.rows.length > 0)
    {
        if(allSelected)
        {
            for(i = 1; i < grid.rows.length; i++)
            {
                cell = grid.rows[i].cells[0];
                for(j=0;j < cell.childNodes.length; j++)
                {
                    if(cell.childNodes[j].type=="radio")
                    {
                        cell.childNodes[j].checked = true;
                    }
                    if(cell.childNodes[j].type=="text")
                    {
                        cell.childNodes[j].value = "1";
                    }
                }
            }
        }
        else
        {
            for(i = 1; i < grid.rows.length; i++)
            {
                cell = grid.rows[i].cells[0];
                for(j=0;j < cell.childNodes.length; j++)
                {
                    if(cell.childNodes[j].type=="radio")
                    {
                        cell.childNodes[j].checked = false;
                    }
                    if(cell.childNodes[j].type=="text")
                    {
                        cell.childNodes[j].value = "0";
                    }
                }
            }
        }
    }
}
/*************Account Selection***********************/
// use for calendar to block off drop down list element to appear ontop of the calendar

function dateEditor_OnShown(dateControl, emptyEventArgs)
   {
       var shimWidth = dateControl._width;
       var shimHeight = dateControl._height;
       var dateEditorShim;
       dateEditorShim = document.getElementById("dateEditorShim");
       dateEditorShim.style.width = dateControl._popupDiv.offsetWidth;
       dateEditorShim.style.height = dateControl._popupDiv.offsetHeight;
       dateEditorShim.style.top = dateControl._popupDiv.style.top;                                                                        
       dateEditorShim.style.left = dateControl._popupDiv.style.left;
       dateControl._popupDiv.style.zIndex = 999;
       dateEditorShim.style.zIndex = 998;
       dateEditorShim.style.display = "block";
       
   }
   function dateEditor_OnHiding(dateControl, emptyEventArgs)
   {
       var shimWidth = 0;
       var shimHeight = 0;
       var dateEditorShim;
       dateEditorShim = document.getElementById("dateEditorShim");
       dateEditorShim.style.width = 0;
       dateEditorShim.style.height = 0;
       dateEditorShim.style.top = 0;
       dateEditorShim.style.left = 0;
       dateEditorShim.style.display = "none";
   }
