﻿
var ajaxInProgress;
var disableAjaxFlag;

function giveFocus(controlId) {
    var control = document.getElementById(controlId);
    if (control == null) {
        //alert('Could not find control with element id ' + controlId + ' to give focus to.');
        return;
    }

    control.focus();

    // Move cursor to the end
    if (control.createTextRange) {
        var r = control.createTextRange();
        r.moveStart('character', (control.value.length));
        r.collapse();
        r.select();
    }
}
     
     
function disableAjax() {

    disableAjaxFlag = "YES";
}

function cancelWizard() {
    
    // This is called by the cancel button on the wizard.

    // Close the pop-up window, this will trigger wizardWindowClosing()
    amovadaYesNoConfirm('Cancel Wizard', 'Are you sure you want to cancel the wizard', 'Save Help.png', cancelWizardCallback);  
    
    // Return false to prevent the button from posting back
    return false;
}

function cancelWizardCallback(response){
	
	switch (response) {
	    case "yes":
	        closeThisPopUpWindow();
	        break;
     
        case "no":
           // Do nothing
            break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }

}

function AjaxStart(sender, args) {
    
    // Is there an ajax request in progress
    if (ajaxInProgress == "YES") {
        // Reset this flag incase it was set
        disableAjaxFlag = "NO";
        // Stop this request from doing anything
        return false;
    }
    else {

        // If there are any file upload controls that have values set then don't use ajax...
        var fileUploadArray = getElementsByClassName("AmovadaFileUpload", "div");
        for (var i = 0, il = fileUploadArray.length; i < il; i += 1) {
            var fileUpload = fileUploadArray[i];
            var radFileUpload = $find(fileUpload.id);
            if (radFileUpload == null) {
                alert("Could not find fileUpload " + fileUpload.id);
                return true;
            }
            // Does the file upload have a file set ?
            if (radFileUpload.getFileInputs()[0].value != "") {
                disableAjaxFlag = "YES";
                break;
            }

        }
        
        if (disableAjaxFlag == "YES") {
            disableAjaxFlag = "NO"
            args.set_enableAjax(false);
        }
        else {
            ajaxInProgress = "YES";
        }

        return true;
    }
}

function AjaxEnd(sender, args) {
    ajaxInProgress = "NO";
}

function refreshGroupAndItemAfterTimeout(titanGroup, titanItem) {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("GroupPanelBar", "refreshGroupAndItemAfterTimeout#" + titanGroup + "#" + titanItem);
    }
}

function sessionTimedOutInPopUpWindow() {
    window.parent.sessionTimedOut();
}

function sessionTimedOut() {
    
    // Use a normal alert to block execution
    alert('Your session has timed out, please login again');
   
    // Get the server to take action on the timeout 
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("GroupPanelBar", "sessionTimedOut");
    }
}

function submitForm() {
   
    var formToSubmit = window.document.Form1;
    if (formToSubmit == null) {
        alert("The formToSubmit could not be found");
        return;
    }

    formToSubmit.submit();
}


function closeThisPopUpWindow() {
    // Get the current RadWindow, this function should only be called
    // by pop up windows.
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        alert("The currentRadWindow could not be found");
        return;
    }

    currentRadWindow.close();
	
}

function refreshTitanShowTableHostInRadWindowViaAjax(radWindowName) {
   
    // Get the current RadWindow, this function should only be called
    // by pop up windows.
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        alert("The currentRadWindow could not be found");
        return;
    }

    // Now get a handle on the window manager for the current window...
    var currentRadWindowManager = currentRadWindow.get_windowManager();
    if (currentRadWindowManager == null) {
        alert("The currentRadWindowManager could not be found");
        return;
    }

    // Now get a handle on the window with the name radWindowName
    var titanHostShowTableRadWindow = currentRadWindowManager.getWindowByName(radWindowName);
    if (titanHostShowTableRadWindow == null) {
        alert("Cannot find titanHostShowTableRadWindow " + radWindowName);
        return;
    }

    // Call the Javascript on the TitanHostShowTableWindow
    // that will cause an AjaxPostback to
    // refresh the user control in the TitanHostShowTableWindow
    titanHostShowTableRadWindow.get_contentFrame().contentWindow.refreshTitanShowTableHostViaAjax();

}

function refreshTitanShowTableHostViaAjax() {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequest("refreshTitanShowTableHostViaAjax");
    }
}

function refreshMainWindowsCurrentTitanItemViewViaAjax() {

    // Get the current RadWindow, this function should only be called
    // by pop up windows.
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        alert("The currentRadWindow could not be found");
        return;
    }

    // Get a handle on the BrowserWindow
    var browserWindow = currentRadWindow.BrowserWindow;
    if (browserWindow == null) {
        alert("The browserWindow could not be found");
        return;
    }

    // Call the Javascript on the parent window that will cause an AjaxPostback to
    // refresh the current TitanItemView
    //titanEditHostWindow.BrowserWindow.refreshCurrentTitanItemViewDuringDrillDown();
    browserWindow.refreshCurrentTitanItemViewViaAjax();

}

function refreshCurrentTitanItemViewViaAjax() {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequest("refreshCurrentTitanItemViewViaAjax");
    }
}

function GetRadAjaxManager() {
    var radAjaxManager = $find("RadAjaxManager1");
    if (radAjaxManager == null) {
        alert("The radAjaxManager could not be found");
        return null;
    }
    else {
        return radAjaxManager;
    }
} 




function fieldPickerAddAllFields() {

    var RadDockZoneFieldsThatCanBeAdded = $find("RadDockZoneFieldsThatCanBeAdded");
    if (RadDockZoneFieldsThatCanBeAdded == null) {
        alert("Cannot find RadDockZoneFieldsThatCanBeAdded");
        return;
    }

    var RadDockZoneFieldsThatHaveBeenAdded = $find("RadDockZoneFieldsThatHaveBeenAdded");
    if (RadDockZoneFieldsThatHaveBeenAdded == null) {
        alert("Cannot find RadDockZoneFieldsThatHaveBeenAdded");
        return;
    }

    var numberDocksInZone = RadDockZoneFieldsThatCanBeAdded.get_docks().length;
    var docksArray = RadDockZoneFieldsThatCanBeAdded.get_docks();
    for (var i = 0; i < numberDocksInZone; i++) {
        RadDockZoneFieldsThatHaveBeenAdded.dock(docksArray[i]);
    }  
}

function fieldPickerRemoveAllFields() {
   
    var RadDockZoneFieldsThatCanBeAdded = $find("RadDockZoneFieldsThatCanBeAdded");
    if (RadDockZoneFieldsThatCanBeAdded == null) {
        alert("Cannot find RadDockZoneFieldsThatCanBeAdded");
        return;
    }
    
    var RadDockZoneFieldsThatHaveBeenAdded = $find("RadDockZoneFieldsThatHaveBeenAdded");
    if (RadDockZoneFieldsThatHaveBeenAdded == null) {
        alert("Cannot find RadDockZoneFieldsThatHaveBeenAdded");
        return;
    }

    var numberDocksInZone = RadDockZoneFieldsThatHaveBeenAdded.get_docks().length;
    var docksArray = RadDockZoneFieldsThatHaveBeenAdded.get_docks();
    for (var i = 0; i < numberDocksInZone; i++) {
        RadDockZoneFieldsThatCanBeAdded.dock(docksArray[i]);
    }

}

function GetCurrentRadWindow() {
    // Get the current RadWindow, if we are not in a RadWindow then this
    // will return null.
    var oWindow = null;
    if (window.radWindow)
        oWindow = window.radWindow;
    else if (window.frameElement == null)
        return null;
    else if (window.frameElement.radWindow)
        oWindow = window.frameElement.radWindow;
    return oWindow;
}

/*
Developed by Robert Nyman, http://www.robertnyman.com
Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function(className, tag, elm) {
    if (document.getElementsByClassName) {
        getElementsByClassName = function(className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
    nodeName = (tag) ? new RegExp("\\b" + tag + "\\b", "i") : null,
    returnElements = [],
    current;
            for (var i = 0, il = elements.length; i < il; i += 1) {
                current = elements[i];
                if (!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        getElementsByClassName = function(className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
    classesToCheck = "",
    xhtmlNamespace = "http://www.w3.org/1999/xhtml",
    namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace) ? xhtmlNamespace : null,
    returnElements = [],
    elements,
    node;
            for (var j = 0, jl = classes.length; j < jl; j += 1) {
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        getElementsByClassName = function(className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
    classesToCheck = [],
    elements = (tag === "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag),
    current,
    returnElements = [],
    match;
            for (var k = 0, kl = classes.length; k < kl; k += 1) {
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for (var l = 0, ll = elements.length; l < ll; l += 1) {
                current = elements[l];
                match = false;
                for (var m = 0, ml = classesToCheck.length; m < ml; m += 1) {
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
}

function executeToolbarCommandAndUpdateJustTheTreeAreaViaAjax(toolbarCommand) {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("AjaxProxyForUpdatingJustTreeArea", "executeToolbarCommand#" + toolbarCommand);
    }
}

function executeToolbarCommandAndUpdateTreeAndGroupsAndContentAreaViaAjax(toolbarCommand) {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("AjaxProxyForUpdatingTreeAndGroupsAndContent", "executeToolbarCommand#" + toolbarCommand);
    }
}

function simulateGroupClickViaAjax(titanGroup) {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("GroupPanelBar", "simulateGroupClickViaAjax#" + titanGroup);
    }
}

function simulateItemClickViaAjax(titanItem) {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("LeftPaneItemTree", "simulateItemClickViaAjax#" + titanItem);
    }
}

function selectGroupAndItemViaAjax(titanGroup, titanItem) {
    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager != null) {
        radAjaxManager.ajaxRequestWithTarget("GroupPanelBar", "selectGroupAndItemViaAjax#" + titanGroup + "#" + titanItem);
    }
}

function updatePopUpWindow(newTitle, newToolTip, newId) {
    
    // Get the current RadWindow, this function should only be called
    // by pop up windows.
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        // This happens when the window is closed.
        return;
    }
    
    if (newTitle != null) {
        currentRadWindow.set_title(newTitle);
    }

    if (newToolTip != null) {
        changeDrillDownWindowToolTip(currentRadWindow, newToolTip);
    }
//    Despite changing both these settings the newId does not effect the window that gets opened.
//    if (newId != null) {
//        currentRadWindow.get_popupElement().id = newId;
//        currentRadWindow._iframe.name = newId;
//    }
}
function OpenItemUserControlAddRecord(windowTitle, windowIcon, titanItemUserControlEditRecordId) {

    if (window.parent != window) {
        window.parent.OpenItemUserControlAddRecord(windowTitle, windowIcon, titanItemUserControlEditRecordId);
    }
    else {

        var urlAndQueryString = "TitanAddRecordHost.aspx";
        urlAndQueryString += "?context=" + titanItemUserControlEditRecordId;

        // The windowName and windowToolTip are the same as the windowTitle 
        // Open the rad window
        var windowName = windowTitle;
        var windowToolTip = windowTitle;
        var newRadWindow = openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, 80, 60, addRecordWindowClosing);

        addCustomWindowButton(
        newRadWindow,
        "saveRecord",
        "Save this record",
        "Save.png",
        "saveRecord", "", true);
    }
}

function OpenItemUserControlWizardRecord(windowTitle, windowIcon, titanItemUserControlEditRecordId, queryContextKey, columnNameForPrimaryKey) {
     

    if (window.parent != window) {
        window.parent.OpenItemUserControlWizardRecord(windowTitle, windowIcon, titanItemUserControlEditRecordId, queryContextKey, columnNameForPrimaryKey);
    }
    else {

        var urlAndQueryString = "TitanWizardHost.aspx";
        urlAndQueryString += "?context=" + titanItemUserControlEditRecordId + "@" + queryContextKey + "@" + columnNameForPrimaryKey + "@" + windowIcon;

        // The windowName and windowToolTip are the same as the windowTitle 
        // Open the rad window
        var windowName = windowTitle;
        var windowToolTip = windowTitle;
        var newRadWindow = openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, 80, 60);
    }
    
}

function drillDownFromBarChart(windowTitle, windowIcon, groupWhere, queryContextKey) {


    var urlAndQueryString = "TitanShowTableHost.aspx";
    urlAndQueryString += "?context=" + queryContextKey + "@" + groupWhere;

    // The windowName and windowToolTip are the same as the windowTitle 
    // Open the rad window
    var windowName = windowTitle;
    var windowToolTip = windowTitle;

    var radWindow = openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, 80, 60);

    addCustomWindowButton(
        radWindow,
        "showHideCriteria",
        "Show / Hide criteria",
        "Calendar 2 Search.png",
        "showHideCriteria", "", false);

}

function OpenPieSegmentUserControlShowTable(queryContextKey, groupWhere) {

    
    var urlAndQueryString = "TitanShowTableHost.aspx";
    urlAndQueryString += "?context=" + queryContextKey + "@" + groupWhere;

    // The windowName and windowToolTip are the same as the windowTitle 
    // Open the rad window
    var windowTitle = "Show Records";
    var windowName = windowTitle;
    var windowToolTip = windowTitle;

    openNewRadWindow(windowName, windowTitle, windowToolTip, null, urlAndQueryString, 80, 60);
   
}

function OpenItemUserControlEditRecord(windowTitle, windowIcon, queryContextKey, columnNameForPrimaryKey, queryContextRecordNumber, recordUniqueId ) {

    if (window.parent != window) {
        window.parent.OpenItemUserControlEditRecord(windowTitle, windowIcon, queryContextKey, columnNameForPrimaryKey, queryContextRecordNumber, recordUniqueId);
    }
    else {
        var urlAndQueryString = "TitanEditRecordHost.aspx";
        urlAndQueryString += "?context=" + queryContextKey + "@" + columnNameForPrimaryKey + "@" + queryContextRecordNumber + "@" + recordUniqueId;

        // The windowName and windowToolTip are the same as the windowTitle 
        // Open the rad window
        var windowName = windowTitle;
        var windowToolTip = windowTitle;
        var newRadWindow = openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, 80, 60, editRecordWindowClosing);

        addCustomWindowButton(
        newRadWindow,
        "saveRecord",
        "Save this record",
        "Save.png",
        "saveRecord", "", true);

        addCustomWindowButton(
        newRadWindow,
        "undoChanges",
        "Undo the changes to the record",
        "Undo.png",
        "beforeUndoChanges", "", true);

        addCustomWindowButton(
        newRadWindow,
        "previousRecord",
        "Move to previous record",
        "Arrow up.png",
        "beforePreviousRecord", "", true);

        addCustomWindowButton(
        newRadWindow,
        "nextRecord",
        "Move to next record",
        "Arrow Down.png",
        "beforeNextRecord", "", true);

        addCustomWindowButton(
        newRadWindow,
        "deleteRecord",
        "Delete this record",
        "Delete.png",
        "beforeDeleteRecord", "", true);

        addCustomWindowButton(
        newRadWindow,
        "printRecord",
        "Print this page",
        "Print.png",
        "printRecord", "", true);

    }

}

function OpenQuickSearchResultsWindow(windowTitle, windowIcon, searchText, titanItemId) {

    if (window.parent != window) {
        window.parent.OpenQuickSearchResultsWindow(windowTitle, windowIcon, searchText, titanItemId);
    }
    else {
        var urlAndQueryString = "TitanQuickSearchHost.aspx";
        urlAndQueryString += "?context=" + searchText + "@" + titanItemId;

        // The windowName and windowToolTip are the same as the windowTitle 
        // Open the rad window
        var windowName = windowTitle;
        var windowToolTip = windowTitle;
        var newRadWindow = openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, 80, 60);

        addCustomWindowButton(
        newRadWindow,
        "saveAsFavourite",
        "Save this quick search as a favourite",
        "Save.png",
        "saveAsFavourite", "", true);
    }

}

function OpenFieldPicker(titanItemUserControlId, titanTableControlId, htmlFilePath, xmlFilePath, dataTableAssemblyQualifiedName, queryContextKey) {

    // If the field picker is being opened from a pop-up then pass the radWindowName
    // so that the field picker can refresh the correct window.

    // Get the current RadWindow, this will be null if we are not currently within a RadWindow
    var currentRadWindow = GetCurrentRadWindow();
    var radWindowName = "";
    if (currentRadWindow != null) {
        radWindowName = currentRadWindow.get_name();  
    }
    
    var urlAndQueryString = "TitanFieldPicker.aspx";
    urlAndQueryString += "?context=" + titanItemUserControlId + "@" + titanTableControlId + "@" + htmlFilePath + "@" + xmlFilePath + "@" + dataTableAssemblyQualifiedName + "@" + queryContextKey + "@" + radWindowName;

    // The windowName and windowToolTip are the same as the windowTitle 
    // Open the rad window
    var windowTitle = "Field Picker";
    var windowName = windowTitle;
    var windowToolTip = windowTitle;
    var windowIcon = "Find Check.png";

    var newRadWindow = openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, null, null);

    newRadWindow.setSize(700, pageHeight() * 90 / 100);
    
    // Center the window
    newRadWindow.Center();
  
}

function openNewRadWindow(windowName, windowTitle, windowToolTip, windowIcon, urlAndQueryString, windowWidthPercentage, windowHeightPercentage, functionToCallWhenWindowClosed) {
    // READ VERY CAREFULLY
    // We do not set ReloadOnShow=True on the RadWindowManager as this appends rwndrnd=RandomNumber
    // onto the query string. The knock on effect of this is that if the child window needs to use
    // AJAX and maintain ViewState then the ViewState is not persisted because of the appended rwndrnd.
    // However if ReloadOnShow is not set to true then the second time the child window is loaded the
    // Page_Load event is not fired and so the content is not refreshed.
    // The work around to this is to put our own random number at the end of the query string.
    // Related to this is that we discovered that having more than 1 query string parameter
    // caused the view state to not work in the child page. Therefore we pass all the context in a single query string.
    // DO NOT SET oWnd.setUrl(oWnd.get_navigateUrl()) as described here:
    // http://www.telerik.com/community/forums/aspnet/window/the-page-cannot-be-found-rwndrnd.aspx
    // This causes the page to be loaded twice the first time it is opened.
    // Generate a random number, this is needed to make the URL different, otherwise the next time the field picker
    // is loaded for this table the window is recycled and page load at the server does not fire
    var randomNumber = Math.floor(Math.random() * 1000000)

    // Put the random number at the end.
    urlAndQueryString += "@" + randomNumber;

    // Get the current RadWindow, this will be null if we are not currently within a RadWindow
    var currentRadWindow = GetCurrentRadWindow();

    // Open the new window
    var newRadWindow;
    if (currentRadWindow == null) {
        newRadWindow = radopen(urlAndQueryString, windowName);
    }
    else {
        // We are within a RadWindow, get a handle on the window manager and then open a window
        newRadWindow = currentRadWindow.get_windowManager().open(urlAndQueryString, windowName);
    }

    // Set the title
    newRadWindow.set_title(windowTitle)

    // Centre the title
    newRadWindow._titleElement.style.textAlign = "center";
    newRadWindow._titleElement.style.width = "100%";

    // Make the window title fill as much space as possible by setting the TD to width 100%
    newRadWindow._titleElement.parentNode.style.width = "100%";

    if (windowWidthPercentage != null && windowHeightPercentage != null) {
        // Set the window size
        // newRadWindow.setSize( pageWidth() * windowWidthPercentage / 100, pageHeight() * windowHeightPercentage / 100);
        newRadWindow.setSize( pageHeight() * 0.9 * 4 / 3, pageHeight() * 0.9);
    }

    // Center the window
    newRadWindow.Center();

    // Change the window icon if it has been specified
    if (windowIcon != null) {
        changeDrillDownWindowIcon(newRadWindow, windowIcon);
    }

    // Change the window minimized tooltip if it has been specified
    if (windowToolTip != null) {
        changeDrillDownWindowToolTip(newRadWindow, windowToolTip);
    }

    // Is a functionToCallWhenWindowClosed specified ?
    if (functionToCallWhenWindowClosed != null) {
        newRadWindow.add_beforeClose(functionToCallWhenWindowClosed);
    }
	
	// We need to know when windows are minimized and maximised.
	 newRadWindow.add_command(radWindowCommand);

    return newRadWindow;
}

function radWindowCommand(sender, eventArgs)
 {
 	
	// Get a handle on the titleBarTableRow
    var titleBarTableRow = sender._titleIconElement.parentNode.parentNode;

    // Loop through all the table cells to see if the toolbarTableCell exists
    var TD = null;
    for (var childNodeIndex = 0, childNodeLength = titleBarTableRow.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var tableCell = titleBarTableRow.childNodes[childNodeIndex];
        if (tableCell.id == 'toolbarTableCell') {
            TD = tableCell;
            break;
        }
    }

    // Is there a toolbar ?
    if (TD != null) {
        switch (eventArgs._commandName) {
            case "Minimize":
                TD.style.display = "none";
                break;

            case "Restore":
                TD.style.display = "";
                break;
        }
    }
 }

 function editRecordWindowClosing(sender, eventArgs) {

     // The sender is the radwindow, we want to find the RadAjaxManager on the radwindow.
     var radAjaxManager = sender.get_contentFrame().contentWindow.$find("RadAjaxManager1")

     if (radAjaxManager == null) {
         //alert("Could not find RadAjaxManager1 in editRecordWindowClosing");
         // If the radAjaxManager is null we assume this is because the session has timed out.
         // We don't want to cancel the window closing so we just return.
         return;
     }

	sender.remove_beforeClose(editRecordWindowClosing);
   
	// Cancel the window closing, instead send an ajax request to 
	// see if the data is dirty...
	eventArgs.set_cancel(true);
	
	radAjaxManager.ajaxRequest("beforeWindowClose");
}

function addWindowClosingTriggerForEditRecordWindow() {
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        alert("The currentRadWindow could not be found");
        return;
    }
    currentRadWindow.add_beforeClose(editRecordWindowClosing)
}

function addWindowClosingTriggerForAddRecordWindow() {
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        alert("The currentRadWindow could not be found");
        return;
    }
    currentRadWindow.add_beforeClose(addRecordWindowClosing)
}

function addRecordWindowClosing(sender, eventArgs){

	sender.remove_beforeClose(addRecordWindowClosing);
   
	// Cancel the window closing, instead send an ajax request to 
	// see if the data is dirty...
	eventArgs.set_cancel(true);
	
	// The sender is the radwindow, we want to find the RadAjaxManager on the radwindow.
	var radAjaxManager = sender.get_contentFrame().contentWindow.$find("RadAjaxManager1")
	
	if (radAjaxManager == null) {
		alert("Could not find RadAjaxManager1 in editRecordWindowClosing");
		return;
	}
	
	radAjaxManager.ajaxRequest("beforeWindowClose");
}

function beforeWindowCloseConfirmCallbackOnAddRecord(response){
	var radAjaxManager = GetRadAjaxManager();
	if (radAjaxManager == null) return;
	
	var currentRadWindow = GetCurrentRadWindow();
	if (currentRadWindow == null) {
		alert("The currentRadWindow could not be found");
		return;
	}
				
	switch (response) {
        case "yes":
            radAjaxManager.ajaxRequest("saveRecordThenCloseWindow");
            break;

        case "no":
            // Close the window
			currentRadWindow.remove_beforeClose(addRecordWindowClosing);
   			currentRadWindow.close();
            break;

        case "cancel":
           // Do nothing
		   currentRadWindow.add_beforeClose(addRecordWindowClosing);
   
		   // Remove the fact that all custome window buttons are tempDisabled
		   removeTempDisabledFromAllCustomWindowButtons(currentRadWindow);
           break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }
}

function beforeWindowCloseConfirmCallbackOnEditRecord(response){
	var radAjaxManager = GetRadAjaxManager();
	if (radAjaxManager == null) return;
	
	var currentRadWindow = GetCurrentRadWindow();
	if (currentRadWindow == null) {
		alert("The currentRadWindow could not be found");
		return;
	}
				
	switch (response) {
        case "yes":
            radAjaxManager.ajaxRequest("saveRecordThenCloseWindow");
            break;

        case "no":
            // Close the window
			currentRadWindow.close();
            break;

        case "cancel":
           // Do nothing
		   currentRadWindow.add_beforeClose(editRecordWindowClosing);
   
		   // Remove the fact that all custome window buttons are tempDisabled
		   removeTempDisabledFromAllCustomWindowButtons(currentRadWindow);
           break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }
}


function recordChangedByOtherUserCallback(response) {

    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager == null)
        return;

    switch (response) {
        case "save":
            radAjaxManager.ajaxRequest("saveRecordIgnoringBehindScenesChanges");
            break;

        case "cancel":
            // Do nothing
            break;

        default:
            alert("response " + response + " not coded for.");
            break;
    }

    // Remove the fact that all custome window buttons are tempDisabled
    removeTempDisabledFromAllCustomWindowButtons();
}

function beforePreviousRecordConfirmCallback(response){

	var radAjaxManager = GetRadAjaxManager();
	if (radAjaxManager == null) 
		return;
	
	switch (response) {
        case "yes":
            radAjaxManager.ajaxRequest("saveRecordThenGotoPreviousRecord");
            break;

        case "no":
            radAjaxManager.ajaxRequest("previousRecord");
            break;

        case "cancel":
           // Do nothing
            break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }
	
	// Remove the fact that all custome window buttons are tempDisabled
	removeTempDisabledFromAllCustomWindowButtons();
}

function beforeNextRecordConfirmCallback(response){

    var radAjaxManager = GetRadAjaxManager();
    if (radAjaxManager == null) {
         return;
    }
    
	switch (response) {
        case "yes":
            radAjaxManager.ajaxRequest("saveRecordThenGotoNextRecord");
            break;

        case "no":
            radAjaxManager.ajaxRequest("nextRecord");
            break;

        case "cancel":
           // Do nothing
            break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }
	
	// Remove the fact that all custome window buttons are tempDisabled
	removeTempDisabledFromAllCustomWindowButtons();
}

function beforeUndoChangesConfirmCallback(response){

	var radAjaxManager = GetRadAjaxManager();
	if (radAjaxManager == null) 
		return;
	
	switch (response) {
        case "yes":
            radAjaxManager.ajaxRequest("undoChanges");
            break;

        case "no":
            // Do nothing
            break;

        case "cancel":
           // Do nothing
           break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }
	
	// Remove the fact that all custome window buttons are tempDisabled
	removeTempDisabledFromAllCustomWindowButtons();
}

function beforeDeleteRecordConfirmCallback(response){
	
	// Because this callback was wired at the client we need
	// to get the radAjaxManager a different way otherwise we end up
	// with the radAjaxManager for the titanHost page.
	
	//Getting rad window manager
  	var windowManager = GetRadWindowManager();
 
 	//Call GetActiveWindow to get the active window
  	var radWindow = windowManager.getActiveWindow();

	// Get a handle on the RadAjaxManager on the radwindow.
    var radAjaxManager = radWindow.get_contentFrame().contentWindow.$find("RadAjaxManager1")

    if (radAjaxManager == null) {
        alert("Could not find RadAjaxManager1 in beforeDeleteRecordConfirmCallback");
        return;
    }
		
	switch (response) {
        case "yes":
            radAjaxManager.ajaxRequest("deleteRecord");
            break;

        case "no":
            // Do nothing
            break;

        case "cancel":
           // Do nothing
            break;
        
		default:
            alert("response " + response + " not coded for.");
            break;
    }
	
	// Remove the fact that all custome window buttons are tempDisabled
	removeTempDisabledFromAllCustomWindowButtons(radWindow);

}

function removeTempDisabledFromAllCustomWindowButtons(radWindow) {

    if (radWindow == null) {
        radWindow = GetCurrentRadWindow();
        if (radWindow == null) {
            alert("The currentRadWindow could not be found");
            return;
        }
    }
   	
	addOrRemoveClassNameForAllCustomWindowButtons(radWindow, "tempDisabled", false);
}

function executeCustomWindowButtonCommand(radWindowName, customButtonName, customCommandName, customCommandArgument, disableAllButtonsWhenPressed) {

    var radWindowManager = $find("RadWindowManager3");
    if (radWindowManager == null) {
        alert("Cannot find RadWindowManager3");
        return;
    }

    var radWindow = radWindowManager.getWindowByName(radWindowName);
    if (radWindow == null) {
        alert("Cannot find RadWindow " + radWindowName);
        return;
    }
   
    // Get a handle on the titleBarTableRow
    var titleBarTableRow = radWindow._titleIconElement.parentNode.parentNode;

    // Loop through all the table cells to see if the toolbarTableCell exists, if it does get 
    // a handle on the UL within it
    var UL = null;
    for (var childNodeIndex = 0, childNodeLength = titleBarTableRow.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var tableCell = titleBarTableRow.childNodes[childNodeIndex];
        if (tableCell.id == 'toolbarTableCell') {
            UL = tableCell.childNodes[0].childNodes[0];
            break;
        }
    }

    // Does the toolbarTableCell not exist yet ?
    if (UL == null) {
        alert("Error, the toolbarTableCell could not be found in executeCustomWindowButtonCommand");
        return;
    }
  
     // Loop through all the LI items looking for one with an ID of customButtonName
    var LI = null;
    for (var childNodeIndex = 0, childNodeLength = UL.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var listItem = UL.childNodes[childNodeIndex];
        if (listItem.id == customButtonName) {
            LI = listItem;
            break;
        }
    }

    // Did we not find the list item
    if (LI == null) {
        alert("Error, could not find a list item with an ID of " + customButtonName + " in executeCustomWindowButtonCommand");
        return;
    }
    
    // Is the item currently disabled ?
    if ((LI.className.indexOf('disabled') != -1 ) ||
	  	(LI.className.indexOf('tempDisabled') != -1)) {
        // Don't do anything because the button is disabled...
        return;
   }

    if (disableAllButtonsWhenPressed) {
		// Loop through all the LI items and set them to disabled to prevent the button from being clicked twice
		addOrRemoveClassNameForAllCustomWindowButtons(radWindow, "tempDisabled", true);
	}
    
	// Get a handle on the RadAjaxManager on the radwindow.
    var radAjaxManager = radWindow.get_contentFrame().contentWindow.$find("RadAjaxManager1")
	
	if (radAjaxManager == null) {
	    alert("Could not find RadAjaxManager1 in executeCustomWindowButtonCommand");
	    return;
	}
	
    switch (customCommandName) {
        case "showHideCriteria":
            
            // Need to toggle criteria on active window
            //Getting rad window manager
            var windowManager = GetRadWindowManager();

            //Call GetActiveWindow to get the active window
            var radWindow = windowManager.getActiveWindow();

            // Get a handle on the RadAjaxManager on the radwindow.
            var radAjaxManager = radWindow.get_contentFrame().contentWindow.toggleCriteria();
          
            break;

        case "beforeNextRecord":
            radAjaxManager.ajaxRequest("beforeNextRecord");
            break;

        case "beforePreviousRecord":
            radAjaxManager.ajaxRequest("beforePreviousRecord");
            break;

        case "saveRecord":
            radAjaxManager.ajaxRequest("saveRecord");
            break;
			
		case "beforeUndoChanges":
		 	radAjaxManager.ajaxRequest("beforeUndoChanges");
            break;
			
		case "beforeDeleteRecord":
			// This is not conditional so we don't need to go back to the server...
			// But we do want to execute this in the context of the pop-up window...
			radWindow.get_contentFrame().contentWindow.amovadaYesNoCancelConfirm(
            	'Delete Record', 
             	'Are you sure you want to delete the current record', 
                'Delete.png', 
                beforeDeleteRecordConfirmCallback);
            break;

        case "printRecord":
            var content = radWindow.GetContentFrame().contentWindow;
            var pane = content.$find('TitanRecordUserControl_RadPane2');

            if (pane != null) {
                var cssFileAbsPath = '../Styles/Styles.css';
                var arrExtStylsheetFiles = [cssFileAbsPath];
                pane.Print(arrExtStylsheetFiles);
            }
            
            radAjaxManager.ajaxRequest("doNothing");
            break;
    }

}

function amovadaYesNoConfirm(title, prompt, icon, callbackFunction) {
    // Create the radwindow as normal
    var radWindow = radconfirm(prompt, callbackFunction, 300, 120, null, title);

    // We need a z index higher than the loading panel
    radWindow._popupElement.style.zIndex = 90001;

    // Get the window elementId
    var radwindowElementId = radWindow._element.id;

    // Now we create our own HTML to customise the pop up    
    var DIV = document.createElement('DIV');
    var html = '<DIV class=\'rwDialogPopup radconfirm\'><DIV class=rwDialogText>' + prompt + '</DIV>';
    html += '<DIV>'
    html += '<A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'yes\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>Yes</SPAN></SPAN></A>';
    html += '<A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'no\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>No</SPAN></SPAN></A>';
    html += '</DIV></DIV>';
    DIV.innerHTML = html;
    radWindow._contentElement.parentNode.replaceChild(DIV, radWindow._contentElement);


    if (icon != null) {
        changeDrillDownWindowIcon(radWindow, icon);
    }

    // We don't want any toolbar buttons on the right
    radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.None);

}


function amovadaYesNoCancelConfirm(title, prompt, icon, callbackFunction)
{
	// Create the radwindow as normal
    var radWindow = radconfirm(prompt, callbackFunction, 300, 120, null, title);

    // We need a z index higher than the loading panel
    radWindow._popupElement.style.zIndex = 90001;

    // Get the window elementId
    var radwindowElementId = radWindow._element.id;

    // Now we create our own HTML to customise the pop up    
    var DIV = document.createElement('DIV');
    var html = '<DIV class=\'rwDialogPopup radconfirm\'><DIV class=rwDialogText>' + prompt + '</DIV>';
    html += '<DIV>'
    html += '<A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'yes\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>Yes</SPAN></SPAN></A>';
    html += '<A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'no\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>No</SPAN></SPAN></A>';
    html += '<A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'cancel\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>Cancel</SPAN></SPAN></A>';
    html += '</DIV></DIV>';
    DIV.innerHTML = html;
    radWindow._contentElement.parentNode.replaceChild(DIV,radWindow._contentElement);
    
	
	if (icon != null){
		changeDrillDownWindowIcon(radWindow, icon);
  	}
   	
	// We don't want any toolbar buttons on the right
    radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.None);

}

function amovadaAlert(title, prompt, icon) {
    // Create the radwindow as normal
    var radWindow = radalert(prompt, 300, 120, title);

    // We need a z index higher than the loading panel
    radWindow._popupElement.style.zIndex = 90001;

    if (icon != null) {
        changeDrillDownWindowIcon(radWindow, icon);
    }

    // We don't want any toolbar buttons on the right
    radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.None);

}


function amovadaSaveCancelConfirm(title, prompt, icon, callbackFunction) {
    // Create the radwindow as normal
    var radWindow = radconfirm(prompt, callbackFunction, 300, 120, null, title);

    // We need a z index higher than the loading panel
    radWindow._popupElement.style.zIndex = 90001;

    // Get the window elementId
    var radwindowElementId = radWindow._element.id;

    // Now we create our own HTML to customise the pop up    
    var DIV = document.createElement('DIV');
    var html = '<DIV class=\'rwDialogPopup radconfirm\'><DIV class=rwDialogText>' + prompt + '</DIV>';
    html += '<DIV><A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'save\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>Save</SPAN></SPAN></A>';
    html += '<A class=rwPopupButton onclick="$find(\'' + radwindowElementId + '\').close(\'cancel\');" tabIndex=0 href="javascript:void(0);">';
    html += '<SPAN class=rwOuterSpan><SPAN class=rwInnerSpan>Cancel</SPAN></SPAN></A>';
    html += '</DIV></DIV>';
    DIV.innerHTML = html;
    radWindow._contentElement.parentNode.replaceChild(DIV, radWindow._contentElement);


    if (icon != null) {
        changeDrillDownWindowIcon(radWindow, icon);
    }

    // We don't want any toolbar buttons on the right
    radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.None);

}

function enableAllCustomWindowButtons() {
    
    // Get the current RadWindow, this function should only be called
    // by pop up windows.
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        // This happens when the window is closed
        return;
    }

    // Get a handle on the titleBarTableRow
    var titleBarTableRow = currentRadWindow._titleIconElement.parentNode.parentNode;

    // Loop through all the table cells to see if the toolbarTableCell exists, if it does get 
    // a handle on the UL within it
    var UL = null;
    for (var childNodeIndex = 0, childNodeLength = titleBarTableRow.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var tableCell = titleBarTableRow.childNodes[childNodeIndex];
        if (tableCell.id == 'toolbarTableCell') {
            UL = tableCell.childNodes[0].childNodes[0];
            break;
        }
    }

    // Does the toolbarTableCell not exist yet ?
    if (UL == null) {
        alert("You enable all custom window buttons on a window that does not have a toolbarTableCell");
        return;
    }

    // Loop through all the LI items setting the className to ''
    for (var childNodeIndex = 0, childNodeLength = UL.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var listItem = UL.childNodes[childNodeIndex];
        listItem.className = '';
    }
}

function addOrRemoveClassNameForAllCustomWindowButtons(radWindow, className, addIfTrueRemoveIfFalse) {
	
	// Get a handle on the titleBarTableRow
    var titleBarTableRow = radWindow._titleIconElement.parentNode.parentNode;
	
	// Loop through all the table cells to see if the toolbarTableCell exists, if it does get 
	// a handle on the UL within it
	var UL = null;
	for (var childNodeIndex = 0, childNodeLength = titleBarTableRow.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
		var tableCell = titleBarTableRow.childNodes[childNodeIndex];
		if (tableCell.id == 'toolbarTableCell') {
			UL = tableCell.childNodes[0].childNodes[0];
			break;
		}
	}
	
	// Does the toolbarTableCell not exist yet ?
	if (UL == null) {
		alert("You enable all custom window buttons on a window that does not have a toolbarTableCell");
		return;
	}
	
	// Loop through all the LI items....
	for (var childNodeIndex = 0, childNodeLength = UL.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
		var listItem = UL.childNodes[childNodeIndex];
		if (addIfTrueRemoveIfFalse) {
			listItem.className = listItem.className + " " + className;
		}
		else {
			var stringToRemove = " " + className;
			listItem.className = listItem.className.replace(stringToRemove, "");
		}
	}
}

function setCustomWindowButtonState(customButtonName, enabledState) {

    // Get the current RadWindow, this function should only be called
    // by pop up windows.
    var currentRadWindow = GetCurrentRadWindow();
    if (currentRadWindow == null) {
        // This happens when the window is closed
        return;
    }

    // Get a handle on the titleBarTableRow
    var titleBarTableRow = currentRadWindow._titleIconElement.parentNode.parentNode;

    // Loop through all the table cells to see if the toolbarTableCell exists, if it does get 
    // a handle on the UL within it
    var UL = null;
    for (var childNodeIndex = 0, childNodeLength = titleBarTableRow.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var tableCell = titleBarTableRow.childNodes[childNodeIndex];
        if (tableCell.id == 'toolbarTableCell') {
            UL = tableCell.childNodes[0].childNodes[0];
            break;
        }
    }

    // Does the toolbarTableCell not exist yet ?
    if (UL == null) {
        alert("You cannot set the state of a toolbar that does not have a toolbarTableCell");
        return;
    }

    // Loop through all the LI items looking for one with an ID of customButtonName
    var LI = null;
    for (var childNodeIndex = 0, childNodeLength = UL.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
        var listItem = UL.childNodes[childNodeIndex];
        if (listItem.id == customButtonName) {
            LI = listItem;
            break;
        }
    }

    // Did we not find the list item
    if (LI == null) {
        alert("Could not find a list item with an ID of " + customButtonName);
        return;
    }

    if (enabledState == true) {
        LI.className = '';
    }
    else {
        LI.className = 'disabled';
    }
}

 function addCustomWindowButton(radWindow, customButtonName, toolTip, iconName, customCommandName, customCommandArgument, disableAllButtonsWhenPressed) {

     // Get a handle on the titleBarTableRow
     var titleBarTableRow = radWindow._titleIconElement.parentNode.parentNode;

     // titleBarTableRow HTML looks like this...
     // <TR>
     //   <TD style="WIDTH: 16px">
     //     <A class=rwIcon style="BACKGROUND: url(../Icons/16x16/GSK.png) no-repeat left top"></A>
     //   </TD>
     //   <TD>
     //     <EM unselectable="on">The window title A</EM>
     //   </TD>
     //   <TD style="WHITE-SPACE: nowrap" noWrap>
     //     <UL class=rwControlButtons style="WIDTH: 93px">
     //       <LI>
     //         <A class=rwMinimizeButton title=Minimize href="javascript:void(0);"><SPAN>Minimize</SPAN></A>
     //       </LI>
     //       <LI>
     //         <A class=rwMaximizeButton title=Maximize href="javascript:void(0);"><SPAN>Maximize</SPAN></A>
     //       </LI>
     //       <LI>
     //         <A class=rwCloseButton title=Close href="javascript:void(0);"><SPAN>Close</SPAN></A>
     //       </LI>
     //     </UL>
     //   </TD>
     // </TR>"

     // Loop through all the table cells to see if the toolbarTableCell already exists, if it does get 
     // a handle on the UL within it
     var UL = null;
     for (var childNodeIndex = 0, childNodeLength = titleBarTableRow.childNodes.length; childNodeIndex < childNodeLength; childNodeIndex++) {
         var tableCell = titleBarTableRow.childNodes[childNodeIndex];
         if (tableCell.id == 'toolbarTableCell') {
             UL = tableCell.childNodes[0].childNodes[0];
             break;
         }
     }

     // Does the toolbarTableCell not exist yet ?
     if (UL == null) {
         var TD = document.createElement("TD");
         TD.id = "toolbarTableCell";

         // Get a handle on the table cell for the title element, this is the cell we want to
         // insert our new cell before...
         var titleTableCell = radWindow._titleElement.parentNode;

         // Insert our new table cell
         titleBarTableRow.insertBefore(TD, titleTableCell);

         // Create the toolbar
         var DIVtoolbar = document.createElement("DIV");
         DIVtoolbar.className = "popupToolbar";
         DIVtoolbar.style.zindex = "9000";
         TD.appendChild(DIVtoolbar);

         // Create the unordered list for the toolbar
         UL = document.createElement("UL");
         DIVtoolbar.appendChild(UL);
     }

     // Create the LI to hold the button
     var LI = document.createElement("LI");
     LI.id = customButtonName;
     UL.appendChild(LI);

     // Create the anchor to hold the image
     var A = document.createElement("A");
     LI.appendChild(A);
     A.style.cursor = "pointer";

     // Wire up the tool tip and function call
     A.href = "javascript:executeCustomWindowButtonCommand('" + radWindow.get_name() + "', '" +
           customButtonName + "', '" + customCommandName + "', '" + customCommandArgument + "'," + disableAllButtonsWhenPressed + ")";
     A.title = toolTip;

     // Stop onmousedown from doing anything
     A.onmousedown = amovadaCancelBubble;

     // Stop double clicks from doing anything...
     A.ondblclick = amovadaCancelBubble;

     // Create the image
     var IMG = document.createElement("IMG");
     IMG.src = '../Images/' + iconName;
     IMG.alt = toolTip;
      
     A.appendChild(IMG);
 }

function amovadaCancelBubble(event) {
     // In IE event is null, in firefox etc it isn't
    if (event == null) {
        event = window.event;
    }
    event.cancelBubble = true;
}

function changeDrillDownWindowIcon(radWindow, iconName) {

    // Get a handle on the titleIconElement
    var titleIconElement = radWindow._titleIconElement;

    // Set the icon we want
    titleIconElement.style.background = "transparent url('../Icons/16x16/" + iconName + "') no-repeat scroll left top";

    // Stop clicks and double clicks from doing anything...
    titleIconElement.onmousedown = amovadaCancelBubble;
    titleIconElement.ondblclick = amovadaCancelBubble;
    
}

function changeDrillDownWindowToolTip(radWindow, tooltip) {

    radWindow._titlebarElement.title = tooltip;

}


function pageWidth() {

    // Get the current RadWindow, this will be null if we are not currently within a RadWindow
    var currentRadWindow = GetCurrentRadWindow();

    var windowToUse;
    var pageWidthToReturn;

    if (currentRadWindow == null) {
        // We are not in a radWindow, use the normal window
        windowToUse = window;
    }
    else {
        // We are in a radWindow so use the BrowserWindow
        windowToUse = currentRadWindow.BrowserWindow;
    }

    if (currentRadWindow == null) {

        // We are not in a radWindow...
        if (windowToUse.innerWidth != null) {
            pageWidthToReturn = windowToUse.innerWidth;
        }
        else if (windowToUse.document.documentElement && windowToUse.document.documentElement.clientWidth) {
            pageWidthToReturn = windowToUse.document.documentElement.clientWidth;
        }
        else if (windowToUse.document.body != null) {
            pageWidthToReturn = windowToUse.document.body.clientWidth;
        }
        else {
            pageWidthToReturn = null;
        }
    }

    return pageWidthToReturn;

}

function pageHeight() {

    // Get the current RadWindow, this will be null if we are not currently within a RadWindow
    var currentRadWindow = GetCurrentRadWindow();
    
    var pageHeightToReturn;
    var windowToUse;

    if (currentRadWindow == null) {
        // We are not in a radWindow, use the normal window
        windowToUse = window;
    }
    else {
        // We are in a radWindow so use the BrowserWindow
        windowToUse = currentRadWindow.BrowserWindow;
    }

    if (windowToUse.innerHeight != null) {
        pageHeightToReturn = windowToUse.innerHeight;
    }
    else if (windowToUse.document.documentElement && windowToUse.document.documentElement.clientHeight) {
        pageHeightToReturn = windowToUse.document.documentElement.clientHeight;
    }
    else if (windowToUse.document.body != null) {
        pageHeightToReturn = windowToUse.document.body.clientHeight;
    }
    else {
        pageHeightToReturn = null;
    }

    return pageHeightToReturn;

}

function createMarkerClickHandler(marker, popUpText) {
    return function() {
        marker.openInfoWindowHtml(popUpText);
        return false;
    };
}

function createMarker(pointData) {
    var latlng = new GLatLng(pointData.Lat, pointData.Long);

    var icon = new GIcon();
    icon.image = pointData.MapIcon;
    icon.iconSize = new GSize(24, 24);
    icon.iconAnchor = new GPoint(12, 12);
    icon.infoWindowAnchor = new GPoint(25, 7);

    opts = {
        "icon": icon,
        "clickable": true,
        "labelText": pointData.MapIconText,
        "labelOffset": new GSize(-10, 10)
    };

    var marker = new LabeledMarker(latlng, opts);
    var handler = createMarkerClickHandler(marker, pointData.PopUpText);

    GEvent.addListener(marker, "click", handler);

    var listItem = document.createElement('li');
    // listItem.innerHTML = '<div class="label">' + pointData.MapIconText + '</div><a href="#">' + pointData.SideBarText + '</a>';
    listItem.innerHTML = '<a href="#">' + pointData.SideBarText + '</a>';
    listItem.getElementsByTagName('a')[0].onclick = handler;

    document.getElementById('sidebar-list').appendChild(listItem);

    return marker;
}

function windowHeight() {
    // Standard browsers (Mozilla, Safari, etc.)
    if (self.innerHeight) {
        return self.innerHeight;
    }
    // IE 6
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    // IE 5
    if (document.body) {
        return document.body.clientHeight;
    }
    // Just in case. 
    return 0;
}

function resizeMap() {
    var googleMap = document.getElementById('GoogleMapDiv');
    
    if (googleMap == null) {
        alert('Google map div could not be found');
        return;
    }

    var googleMapPane = googleMap.parentNode;
    if (googleMapPane == null) {
        alert('Google map pane could not be found');
        return;
    }

    var height = googleMapPane.clientHeight;
    var width = googleMapPane.clientWidth;
 
    googleMap.style.height = height + 'px';
    googleMap.style.width = width + 'px';
}


function LoadGoogleMap(markers, minLat, minLong, maxLat, maxLong) {
    
    resizeMap();

    map = new GMap(document.getElementById("GoogleMapDiv"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());

    // Define the two corners of the bounding box
    var sw = new GLatLng(minLat, minLong);
    var ne = new GLatLng(maxLat, maxLong);

    // Create a bounding box
    var bounds = new GLatLngBounds(sw, ne);

    // Center map in the center of the bounding box   
    // and calculate the appropriate zoom level   
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

    manager = new MarkerManager(map);

    // This is a sorting trick, don't worry too much about it.
    markers.sort(function(a, b) { return (a.MapIconText > b.MapIconText) ? +1 : -1; });

    batch = [];
    for (id in markers) {
        batch.push(createMarker(markers[id]));
    }
    manager.addMarkers(batch, 0);
    manager.refresh();
}

function get_LeftPaneFavouriteTree() {
    var leftPaneFavouriteTree = $find("LeftPaneFavouriteTree");
    if (leftPaneFavouriteTree == null) {
        alert("Cannot find LeftPaneFavouriteTree");
    }
    return leftPaneFavouriteTree;
}

function get_LeftPaneItemTree() {
    var leftPaneFavouriteTree = $find("LeftPaneItemTree");
    if (leftPaneFavouriteTree == null) {
        alert("Cannot find LeftPaneItemTree");
    }
    return leftPaneFavouriteTree;
}

function get_ItemNameRadTextBox() {
    var itemNameRadTextBox = $find("CurrentItemNameRadTextBox");
    if (itemNameRadTextBox == null) {
        alert("Cannot find CurrentItemNameRadTextBox");
    }
    return itemNameRadTextBox;

}

function treeExpandAllNodes(treeview) {

    if (treeview != null) {

        var nodes = treeview.get_allNodes();

        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].get_nodes() != null) {
                nodes[i].expand();
            }
        }
    }
}

function treeCollapseAllNodes(treeview) {

    if (treeview != null) {

        var nodes = treeview.get_allNodes();

        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].get_nodes() != null) {
                nodes[i].collapse();
            }
        }
    }
}

function titanSelectedItemToolbarClicking(sender, args) {

    var button = args.get_item();

    var currentItemNameRadTextBox = get_ItemNameRadTextBox();
    if (currentItemNameRadTextBox == null) return;
    
    switch (button.get_commandName()) {

        case "SetItemAsDefaultForThisGroup":
        case "SetItemAsDefaultForLogin":
        case "ToggleCriteria": 
            /* N/A for clicking... */
            break;
            
        case "SaveAsCurrent":
            if (currentItemNameRadTextBox.isEmpty()) {
                alert("You must enter a name.");
                args.set_cancel(true);
                currentItemNameRadTextBox.focus();
            }
            break;   
            
        case "Delete":
            if (currentItemNameRadTextBox.isEmpty()) {
                alert("There is no item selected to delete.");
                args.set_cancel(true);
            }
            else {
                var answer = confirm("This will delete the current item, are you sure ?");
                if (!answer) {
                    args.set_cancel(true);
                }
            }
            break;

        default:
            alert("Command " + button.get_commandName() + " not coded for in titanSelectedItemToolbarClicking");
            break;

    }
}

function titanSelectedItemToolbarButtonClicked(sender, args) {

    var button = args.get_item();
    var commandName;

    switch (button.get_commandName()) {

        case "SetItemAsDefaultForThisGroup":
            if (button.get_checked()) {
                commandName = "SetItemAsDefaultForThisGroup";
            }
            else {
                commandName = "UnSetItemAsDefaultForThisGroup";
            }
            executeToolbarCommandAndUpdateJustTheTreeAreaViaAjax(commandName);
            break;

        case "SetItemAsDefaultForLogin":
            if (button.get_checked()) {
                commandName = "SetItemAsDefaultForLogin";
            }
            else {
                commandName = "UnSetItemAsDefaultForLogin";
            }
            executeToolbarCommandAndUpdateJustTheTreeAreaViaAjax(commandName);
            break;

        case "SaveAsCurrent":
        case "Delete":
            executeToolbarCommandAndUpdateTreeAndGroupsAndContentAreaViaAjax(button.get_commandName());
            break;

        case "ToggleCriteria":
            set_CriteriaPanelIsVisible(button.get_checked());
            break;

        default:
            alert("Command " + button.get_commandName() + " not coded for in titanSelectedItemToolbarButtonClicked");
            break;
    }
}


function LeftPaneItemsTree_OnClientContextMenuItemClicking(sender, eventArgs) {
    var node = eventArgs.get_node();
    var item = eventArgs.get_menuItem();
    var menu = item.get_menu();

    switch (item.get_value()) {
        case "GroupHome":
        case "LogonHome":
            break;


        case "DeleteItem":
            var answer = confirm("You are about to delete this item, are you sure ?");
            if (!answer) {
                args.set_cancel(true);
            }
            break;

        default:
            alert("Command " + item.get_value() + " not coded for in LeftPaneItemsTree_OnClientContextMenuItemClicking");
            break;
    }


}

function LeftPaneItemsTree_OnClientContextMenuItemClicked(sender, eventArgs) {
    var node = eventArgs.get_node();
    var item = eventArgs.get_menuItem();
    var menu = item.get_menu();

    switch (item.get_value()) {
        case "GroupHome":
            commandName = "SetItemAsDefaultForThisGroup#" + node.get_value();
            executeToolbarCommandAndUpdateJustTheTreeAreaViaAjax(commandName) ;
            break;

        case "LogonHome":
            commandName = "SetItemAsDefaultForLogin#" + node.get_value();
            executeToolbarCommandAndUpdateJustTheTreeAreaViaAjax(commandName);
            break;

        case "DeleteItem":
            commandName = "DeleteItem#" + node.get_value();
            executeToolbarCommandAndUpdateJustTheTreeAreaViaAjax(commandName);
            break;

        
        default:
            alert("Command " + item.get_value() + " not coded for in LeftPaneItemsTree_OnClientContextMenuItemClicked");
            break;
    }


}


function titanNewItemToolbarButtonClicked(sender, args) {
    var button = args.get_item();

    switch (button.get_commandName()) {

        case "AddFolder":
        case "AddDashboard":
        case "AddFavourite":
            /* Handled server side */
            break;

        default:
            alert("Command " + button.get_commandName() + " not coded for in titanNewItemToolbarButtonClicked");
            break;
    }
}

function set_CriteriaPanelIsVisible(isVisible)
{

    var PlaceHolder1 = document.getElementById('PlaceHolder1');
    if (PlaceHolder1 == null) {
        alert('Cannot find PlaceHolder1');
        return;
    }
    var splitterID = PlaceHolder1.getElementsByTagName('div')[0].id;
    if (splitterID == null) {
        alert('Cannot find splitter');
        return;
    }
    var paneID = PlaceHolder1.getElementsByTagName('div')[0].getElementsByTagName('td')[0].id;
    if (paneID == null) {
        alert('Cannot find pane');
        return;
    }

    var splitter = $find(splitterID);
    if (splitter == null) {
        alert('Cannot find splitter');
        return;
    }

    var pane = splitter.getPaneById(paneID);
    if (pane == null) {
        alert('Cannot find pane');
        return;
    }

    if (isVisible) {
        // Expand criteria panel and size it's contents correctly
        pane.expand();
        sizeTheCriteriaPanelCorrectly(splitter);
    }
    else {
        // Collapse the criteia pane
        pane.collapse();

    }
}

function toggleCriteria() {

    var PlaceHolder1 = document.getElementById('PlaceHolder1');
    if (PlaceHolder1 == null) {
        alert('Cannot find PlaceHolder1');
        return;
    }
    var splitterID = PlaceHolder1.getElementsByTagName('div')[0].id;
    if (splitterID == null) {
        alert('Cannot find splitter');
        return;
    }
    var paneID = PlaceHolder1.getElementsByTagName('div')[0].getElementsByTagName('td')[0].id;
    if (paneID == null) {
        alert('Cannot find pane');
        return;
    }

    var splitter = $find(splitterID);
    if (splitter == null) {
        alert('Cannot find splitter');
        return;
    }

    var pane = splitter.getPaneById(paneID);
    if (pane == null) {
        alert('Cannot find pane');
        return;
    }

    if (pane.get_collapsed()) {
        // Expand criteria panel and size it's contents correctly
        pane.expand();
        sizeTheCriteriaPanelCorrectly(splitter);
    }
    else {
        // Collapse the criteia pane
        pane.collapse();

    }
}
    

function _CriteriaRadPane_ToggleToolButton() {
    // Must leave here to prevent javascript error
}

function sizeTheCriteriaPanelCorrectly(splitter)
{
    var criteriaRadPane = splitter.getPaneByIndex(0);
    if (criteriaRadPane == null) {
        alert("Could not find the criteria rad pane");
        return;
    }
    
    var resultsRadPane = splitter.getPaneByIndex(1);
    if (resultsRadPane == null) {
        alert("Could not find the results rad pane");
        return;
    }

    // If the criteria pane is not collapsed then we need to size the criteria
    // pane to be the size of the FilterRegion and the size of the results pane to be the
    // remainding space
    if (!criteriaRadPane.get_collapsed()) {

        // The criteria pane is collapsed.
        var filterRegion = document.getElementById('FilterRegion');
        if (filterRegion == null) {
            alert("Could not find the FilterRegion");
            return;
        }

        // Get the current sizes BEFORE we do any resizing
        var resultsRadPaneCurrentHeight = resultsRadPane.get_height();
        var criteriaRadPaneCurrentHeight = criteriaRadPane.get_height();
        
        // Set the criteria pane to be the size of the filter region
        criteriaRadPane.setVarSize(filterRegion.clientHeight);

        // Set the results to be the remaining size.
        // Need to do this because we want reports that would not fill the whole area to fill the whole area
        resultsRadPane.setVarSize(criteriaRadPaneCurrentHeight - filterRegion.clientHeight + resultsRadPaneCurrentHeight);

    }

}

function _ReportRadSplitter_OnClientLoaded(splitter, arg) {

    sizeTheCriteriaPanelCorrectly(splitter);
   
}

function splitterLoadedOnDashboard(radSplitterForTheReport, arg) {
      
    // Get a handle on the RadDock that the radSplitter for the report is in
    var radDockElement = radSplitterForTheReport._element.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
    var radDockForTheReport = $find(radDockElement.id);
    if (radDockForTheReport == null) {
        alert("$find on " + radDockIdForTheReport.id + " failed");
        return;
    }
   
    // Find the content Element
    var amovadaContentArray = getElementsByClassName("AmovadaContent", "div", radSplitterForTheReport._element);
    // Make sure we found 1 and only 1.
    if (amovadaContentArray.length != 1) {
        alert("Failed to find the Amovada Content correctly, looking for a div class='AmvovadaContent' - looking for 1 instance and found " + amovadaContentArray.length);
        return;
    }

    // Get the amovada content element
    var amovadaContentElement = amovadaContentArray[0];

    // Set the size of the splitter for the report
    radSplitterForTheReport.set_height(amovadaContentElement.clientHeight + 2);
    radSplitterForTheReport.set_width(amovadaContentElement.clientWidth + 2);

       
    // Get the current size of the dock
    var dockHeight = radDockForTheReport.get_height();
    var dockWidth = radDockForTheReport.get_width();
    
    // If the dock is brand new then set the dock size
    if (dockHeight == '100px' && dockWidth == '100px') {
        radDockForTheReport.set_height(amovadaContentElement.clientHeight + 30);
        radDockForTheReport.set_width(amovadaContentElement.clientWidth + 10);

        // if the dock is off the right of the screen, shrink it
        if (radDockForTheReport._element.offsetLeft + radDockForTheReport._element.offsetWidth > radDockForTheReport._element.offsetParent.offsetWidth) {
            radDockForTheReport.set_width(radDockForTheReport.get_width() + radDockForTheReport._element.offsetParent.offsetWidth - radDockForTheReport._element.offsetLeft - radDockForTheReport._element.offsetWidth);
        }
        // if the dock is off the bottom of the screen, shrink it
        if (radDockForTheReport._element.offsetTop + radDockForTheReport._element.offsetHeight > radDockForTheReport._element.offsetParent.offsetHeight) {
            radDockForTheReport.set_height(radDockForTheReport.get_height() + radDockForTheReport._element.offsetParent.offsetHeight - radDockForTheReport._element.offsetTop - radDockForTheReport._element.offsetHeight);
        }

    }
}

function ContentOnClientLoaded(splitter, args) {

    
    var leftPane = splitter.getPaneById("LeftPane");
    var contentSplitBar = splitter.getSplitBarById("ContentSplitBar");
//    ShiftDocks(leftPane.get_width() + contentSplitBar.getWidth());
    ShiftDocks(leftPane.get_width());
}

function LeftPaneOnClientResized(splitter, args) {
    ShiftDocks(splitter.get_width()- args.get_oldWidth());
}

function ShiftDocks(ShiftBy) {

    var dockArray = getElementsByClassName("raddock", "div");
    for (var x = 0; x < dockArray.length; x++) {
        // find the dock
        var dock = $find(dockArray[x].id);
        // shift it
        dock.set_left(dock.get_left() + ShiftBy);
    }
}

function resizePanelBar() {
    var splitter = $find("LeftPaneSplitter");

    if (splitter != null) {
        resizePanelBarSplitterItems(splitter);
    }
}
  
//resize the group panel bar splitter to the height of the group panel bar
function LeftPaneSplitter_OnClientLoaded(splitter, arg) {
    resizePanelBarSplitterItems(splitter);
}

function resizePanelBarSplitterItems(splitter) {
    var LeftPaneBottomSplitBar = splitter.getSplitBarById('LeftPaneBottomSplitBar');
    LeftPaneBottomSplitBar.set_enableResize(true);

    var LeftPaneBottom = splitter.getPaneById('LeftPaneBottom');
    var LeftPaneBottomCurrentHeight = LeftPaneBottom.get_height();
    if (LeftPaneBottomCurrentHeight != '') {
        var GroupPanelBar = document.getElementById("GroupPanelBar")
        var LeftPaneBottomTargetHeight = GroupPanelBar.clientHeight

        if (LeftPaneBottomTargetHeight != null) {

            var leftPaneItemsPane = splitter.getPaneById('LeftPaneItemsPane');
            var leftPaneItemsPaneCurrentHeight = leftPaneItemsPane.get_height();

            if (leftPaneItemsPaneCurrentHeight != null) {
                LeftPaneBottom.setVarSize(LeftPaneBottomTargetHeight);

                leftPaneItemsPane.setVarSize(leftPaneItemsPaneCurrentHeight - LeftPaneBottomTargetHeight + LeftPaneBottomCurrentHeight);
            }
        }
    }
}


function resizeSplitter(obj)
{

    var splitter = $find("TitanRecordUserControl_EditSplitter");  
    if (splitter != null)
    {
        var pane1 = splitter.getPaneById("TitanRecordUserControl_RadPane1");
        var CurrentHeight = pane1.get_height();

        if (pane1.getContentElement().firstChild != null) {
            var TargetHeight = pane1.getContentElement().firstChild.clientHeight;
        }
        if (TargetHeight == null) {
            var TargetHeight = pane1.getContentElement().firstElementChild.clientHeight;
        }

        if (CurrentHeight != null) {
            pane1.setVarSize(TargetHeight); 
            var pane2 = splitter.getPaneById("TitanRecordUserControl_RadPane2");
            pane2.setVarSize(pane2.get_height() - TargetHeight + CurrentHeight); 
        }
    }
}


function loadContactList(splitter, arg)
{
    sizeTheCriteriaPanelCorrectly(splitter);
    resizeContactList(splitter);
}

function resizeContactList(splitter)
{
    var contactList = document.getElementById('contactList');
    var divTitanUserTitanUserContactListascx__PagingPanel=document.getElementById('TitanUserTitanUserContactListascx__PagingPanel');
    
    var col1 = document.getElementById('col1')
    var col2 = document.getElementById('col2')
    var col3 = document.getElementById('col3')

    var divContactHolder = document.getElementById('contactHolder');
    var intContacts = divContactHolder.childElementCount;
    
    // first - rename the class to an ordered list
    for (var i = 0; i < intContacts; i++) {
        var contact = divContactHolder.children[i];
        contact.id='contact' + i;
    }    

    // next, put them all back in the holder
    intContacts = document.getElementsByClassName('contact').length;
    
    var divContactHolder = document.getElementById('contactHolder');
    for (var j = 0; j < intContacts; j++) {
        divContactHolder.appendChild(document.getElementById('contact' + j));
    }

    var intPanelHeight = contactList.parentNode.parentNode.clientHeight - divTitanUserTitanUserContactListascx__PagingPanel.clientHeight;
    
    // now, cycle through them again...
    var k=1;
    for (j = 0; j < intContacts; j++) {
        var contactToMove = document.getElementById('contact' + j);

        var col = document.getElementById('col'+k);
        col.appendChild(contactToMove);

        while (10+contactToMove.offsetTop+contactToMove.offsetHeight>intPanelHeight)
        {
            k++; 
            col = document.getElementById('col'+k);
            if (col == null) {
                var contactListTR = document.getElementById('contactListTR');
                var col = document.createElement('TD');
                col.id = 'col'+k;
                col.valign='top';
                contactListTR.appendChild(col);
            }
            col.appendChild(contactToMove);
        }
    }    
}


