/// <reference name="MicrosoftAjax.js"/>
/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="Telerik.Web.UI.Common.Animation.AnimationScripts.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Common.Core.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Common.jQuery.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Common.Navigation.NavigationScripts.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Common.Scrolling.ScrollingScripts.js" assembly="Telerik.Web.UI" />
/// <reference path="jquery-telerik.js" />

var GMC_Common_MasterName = "CheckAll"; //the master checkbox must always have "CheckAll" in its ID

function selAll(_v, obj) {
    allElements = document.forms[0].elements;
    for (i = 0; i < allElements.length; i++) {
        if (allElements[i].type == "checkbox" && allElements[i].name.substr(0, obj.length) == obj) {
            allElements[i].checked = _v
        }
    }
}

function toggleChecks(toggle, id, container) {
    /// <summary>this method toggles a list of checkboxes </summary>
    /// <param name="toggle" mayBeNull="false">the value of which to toggle</param>
    /// <param name="id"> id of the item being checked </param>
    /// <param name="container">container to search within </param> 

    if (!container) {
        throw new Error("When using the toggleChecks function, the container parameter cannot be null!");
    }

    var elements = container.getElementsByTagName("INPUT"); //get all the items
    var masterCheckIndex = -1;
    var totalCheckBoxes = 0; //To account for select all check box
    var totalChecked = 0;
    var allChecked = false;

    //loop through all elements
    for (i = 0; i < elements.length; i++) {
        if (elements[i].type == "checkbox") {
            //if the item clicked is the "master"
            if (id.indexOf(GMC_Common_MasterName) != -1) {
                //toggle the checkboxes
                elements[i].checked = toggle;
                allChecked = toggle;
            } //process the "other" checkboxes
            else {
                //check if any of the checkboxes are not checked, and then uncheck top select all checkbox
                if (elements[i].id.indexOf(GMC_Common_MasterName) != -1) {
                    masterCheckIndex = i;
                }
                else {
                    totalCheckBoxes++;
                    if (elements[i].checked == true)
                        totalChecked++;
                }
            }
        }
    }

    //only run if the request is from a non CheckAll checkbox
    if (masterCheckIndex > -1) {
        if (totalChecked > 0 && totalChecked == totalCheckBoxes) {
            elements[masterCheckIndex].checked = true;
            allChecked = true;
        } else {
            elements[masterCheckIndex].checked = false;
        }
    }

    return allChecked;
}

function isFirstChecked(container) {
    /// <summary>this method toggles a list of checkboxes </summary>    
    /// <param name="container">container to search within </param> 

    if (!container) {
        throw new Error("When using the isFirstChecked function, the container parameter cannot be null!");
    }

    var elements = container.getElementsByTagName("INPUT"); //get all the items
    var index = 0;
    var returnVal = false;

    //loop through all elements
    for (i = 0; i < elements.length; i++) {
        if (elements[i].type == "checkbox") {
            //check if any of the checkboxes are not checked, and then uncheck top select all checkbox
            if (elements[i].id.indexOf(GMC_Common_MasterName) != -1) {
                //ignore any Check All boxes
            }
            else {
                //only check the items enabled
                if (elements[i].disabled == false) {
                    if (elements[i].checked && index == 0)
                        returnVal = true
                    else if (elements[i].checked && index > 0)
                        returnVal = false;

                    //increment the count
                    index++
                }
            }
        }
    }
    return returnVal;
}

//TODO Remove old function
//this function is now obsolete, but some areas may refer to it
function select_deselectAll(chkVal, idVal, grpChkBoxName, masterChkBoxName) { //WARNING Checkboxes need very different names no abc and abc1.
    var frm = document.getElementsByTagName("INPUT");
    var chkallidx = 0;
    var noGrpChks = -1; //To account for select all check box
    var noGrpChecked = 0;
    // Loop through all elements
    for (i = 0; i < frm.length; i++) {
        if (frm[i].type == "checkbox" && (frm[i].name.indexOf(grpChkBoxName) != -1 || frm[i].name.indexOf(masterChkBoxName) != -1)) {
            // Look for our Header Template's Checkbox
            if (idVal.indexOf(masterChkBoxName) != -1) {

                // Check if main checkbox in grid1 is checked, then select or deselect datagrid checkboxes 
                if (chkVal == true) {
                    frm[i].checked = true;
                } else {
                    frm[i].checked = false;
                }
            } // Work here with the Item Template's multiple checkboxes
            else if (idVal.indexOf(grpChkBoxName) != -1) {
                noGrpChks++;
                // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
                if (frm[i].type == "checkbox" && frm[i].name.indexOf(masterChkBoxName) != -1) {
                    chkallidx = i;
                }
                else if (frm[i].type == "checkbox" && frm[i].checked == false) {
                    frm[chkallidx].checked = false;
                }
                else if (frm[i].type == "checkbox" && frm[i].checked == true) {
                    noGrpChecked++;
                }
            }

        }
    }
    if (chkallidx > 0 && noGrpChecked == noGrpChks) {
        frm[chkallidx].checked = true;
    }
}

function disableSort(disable) {
    var m_lstSortBy = $find(lstSortBy);
    var m_lstSortDirection = null;
    if (typeof (lstSortDirection) != "undefined") {
        m_lstSortDirection = $find(lstSortDirection);
    }

    if (disable) {
        m_lstSortBy.disable();
        if (m_lstSortDirection != null) {
            m_lstSortDirection.disable();
        }
    } else {
        m_lstSortBy.enable();
        if (m_lstSortDirection != null) {
            m_lstSortDirection.enable();
        }
    }
}

function disablePercent(disable) {
    lstPerc.disabled = disable;
}

function setDefaultSortOrder(sender, eventArgs) {
    var m_lstSortDirection = $find(lstSortDirection);
    if (sender.get_selectedIndex() == 0) {
        m_lstSortDirection.findItemByValue('ASC').select();
    } else {
        m_lstSortDirection.findItemByValue('DESC').select();
    }
}

function countYears() {
    var chkYearsControl = $find(chkYears).get_dropDownElement();
    return countCheckBoxes(chkYearsControl);
    //return countCheckBoxes(chkYears);
}

function countCheckBoxes(Parent) {
    var cnt = 0;
    if (Parent != null) {
        //get all the input elements in the parent control
        allElements = Parent.getElementsByTagName("input");

        //loop through checkboxes counting those checked
        for (i = 0; i < allElements.length; i++) {
            if (allElements[i].type == "checkbox") {
                if (allElements[i].checked) {
                    cnt++;
                }
            }
        }
    }
    return cnt;
}

function phoneNumberOnly(i) {
    var key;
    var keychar;

    if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) {
        key = i.keyCode;
    } else {
        key = i.which;
    }
    if (parseInt(key) == 32) return true;

    keychar = String.fromCharCode(key);
    var regTest = /[0-9\(\)]/;
    return regTest.test(keychar);
}

function stopPropagation(e) {
    e.cancelBubble = true;

    if (e.stopPropagation) {
        e.stopPropagation();
    }
}

var GMC_ajaxIgnoreControls = new Array();
function requestStart(sender, eventArgs) {
    //this is needed because the buttons keeps getting ajaxified and need to do a normal postback
    //seems to be a Telerik but that we have to do this but it is... it works.. for now.
    for (i = 0; i < GMC_ajaxIgnoreControls.length; i++) {
        if (GMC_ajaxIgnoreControls[i] == eventArgs.EventTarget) {
            eventArgs.set_enableAjax(false);
            return;
        }
    }
    set_busy(true);
}

function responseEnd(sender, eventArgs) {
    set_busy(false);
}

//uses javascript to overlay a division on top of the documents body so we can get the working
//cursor to show
function set_busy(wait) {
    if (wait) {
        document.body.className = 'wait';
    } else {
        document.body.className = '';
    }
}

function showDataViewWindow(id) {
    //we open a new radwindow the id of the window must be that of the GUID as it is used in the close
    var oManager = GetRadWindowManager();
    var oWnd = oManager.open("ViewData.aspx?DataID=" + id, id);
    oWnd.setSize(700, 700);
    oWnd.center();
    oWnd.add_close(onDataWindowClose);
}

function onDataWindowClose(sender, eventArgs) {
    //this called the Page Method defined in GMC.Paxsmart.Page that all pages inherit from
    var id = sender.get_id();
    PageMethods.RemoveDataView(id, OnCallComplete, OnCallError);
}

function OnCallComplete(result, txtresult, methodName) {
    //ignore the call complete
}


function OnCallError(error, userContext, methodName) {
    if (error !== null) {
        alert(error.get_message());
    }
}

function getCheckboxValues(checkedCombo, wrapInQuotes) {
    var items = checkedCombo.get_items();

    var returnValue = "";
    for (itemIndex = 0; itemIndex < items.get_count(); itemIndex++) {
        var item = items.getItem(itemIndex);

        var checkbox = getItemCheckBox(item);
        if (checkbox) {
            //Check whether the Item's CheckBox) is checked.
            if (checkbox.checked) {
                if (wrapInQuotes)
                    returnValue += "\'" + item.get_value() + "\',";
                else
                    returnValue += item.get_value() + ",";
            }
        }
    }

    return returnValue;
}

//gets the checkbox in a combo item
function getItemCheckBox(item) {
    //Get the 'div' representing the current RadComboBox Item. 
    var itemDiv = item.get_element();

    //Get the collection of all 'input' elements in the 'div' (which are contained in the Item). 
    var inputs = itemDiv.getElementsByTagName("input");
    for (var inputIndex = 0; inputIndex < inputs.length; inputIndex++) {
        var input = inputs[inputIndex];

        //Check the type of the current 'input' element. 
        if (input.type == "checkbox") {
            return input;
        }
    }

    return null;
}

var buttonText = new Array();

var timeoutAddition = 0;
function disableSkinnedButton(clientID) {
    /// <summary>this method disables a button that has been skinned by the form decorator</summary>
    /// <param name="clientID" mayBeNull="false">the client id of the button</param>

    //remember text for enableButton
    var realButton = $get(clientID);
    buttonText[clientID] = realButton.value;
   // buttonText = realButton.value;

    var loadingMessage = "Please wait...";
    var button = "_radfd_Skinned" + clientID;
    
    //disable the decorated button
    $get(button).className += " radfdInputDisabled";
    //disable the real button
    if (clientID) {
        realButton.disabled = 'disabled'
        $get(button).childNodes[0].childNodes[0].innerHTML = loadingMessage;
    }

    set_busy(true);
}

function enableSkinnedButton(clientId) {
    /// <summary>this method re-enableds  a button that has been skinned by the form decorator as disabled by disableSkinnedButton</summary>
    /// <param name="clientID" mayBeNull="false">the client id of the button</param>    

    var button = $get("_radfd_Skinned" + clientId);

    //reenable the button and set back its properties
    $get(clientId).disabled = false;
    button.className =  button.className.replace(" radfdInputDisabled","");
    button.childNodes[0].childNodes[0].innerHTML = buttonText[clientId];    
    set_busy(false);
}

function disableDataButtons() {
    /// <summary>this method disables the Data View Buttons</summary>
    disableSkinnedButton(btnViewTable.id);
    disableSkinnedButton(btnViewChart.id);
}

function enableDataButtons() {
    /// <summary>this method re-enableds the Data View Buttons</summary>
    enableSkinnedButton(btnViewTable.id);
    enableSkinnedButton(btnViewChart.id);
}