
//The Id of user control that is being loaded into Customers Central
var ucSubscriberDetailId = 'ctl00_eContent_ucSubscriberDetail';
var ucModelHistory = 'ctl00_eContent_tabHandsetHistory_tabHandsetHistoryPanel2_ucModelHistory';

/***************************************************************
Tab Changed Event
****************************************************************/
function tabHandsetHistory_ActiveTabChanged(sender, e) {
    var manageRecordingURL = window.location.href.split('WebSite')[0] + "WebSite/ManageRecording.aspx";
    var url = manageRecordingURL + "?TabIndex=" + sender.get_activeTabIndex() + "&PageUrl=" + window.location.href.split('?')[0] + "&TabId=tabHandsetHistory";
    $.ajax({ url: url, cache: false });
}

function tabNotes_ActiveTabChanged(sender, e) {
    var manageRecordingURL = window.location.href.split('WebSite')[0] + "WebSite/ManageRecording.aspx";
    var url = manageRecordingURL + "?TabIndex=" + sender.get_activeTabIndex() + "&PageUrl=" + window.location.href.split('?')[0] + "&TabId=tabNotes";
    $.ajax({ url: url, cache: false });
}

function tabClaimHistory_ActiveTabChanged(sender, e) {
    var manageRecordingURL = window.location.href.split('WebSite')[0] + "WebSite/ManageRecording.aspx";
    var url = manageRecordingURL + "?TabIndex=" + sender.get_activeTabIndex() + "&PageUrl=" + window.location.href.split('?')[0] + "&TabId=tabClaimHistory";
    $.ajax({ url: url, cache: false });
}

function tabEscalationHistory_ActiveTabChanged(sender, e) {
    var manageRecordingURL = window.location.href.split('WebSite')[0] + "WebSite/ManageRecording.aspx";
    var url = manageRecordingURL + "?TabIndex=" + sender.get_activeTabIndex() + "&PageUrl=" + window.location.href.split('?')[0] + "&TabId=tabEscalationHistory";
    $.ajax({ url: url, cache: false });
}

/***************************************************************
Function ClaimDetail.ascx ConfirmCancel
****************************************************************/
function ConfirmCancel() {
    return confirm($('[id$=_hdAlertCancelThisClaimQuestion]').val());
}

/***************************************************************
Function CustomerCentral.DisplayMessage
****************************************************************/
CustomerCentral.DisplayMessage = function (headerText, bodyText) {
    var header = $('[id$=_lblHeaderText]')[0];
    var body = $('[id$=_lblBodyText]')[0];

    header.innerHTML = headerText;
    body.innerHTML = bodyText;

    $find('DisplayMessage').show();
}

/***************************************************************
Function CustomerCentral.HideCreateLinks
****************************************************************/
CustomerCentral.HideCreateLinks = function () {
    var allElementsToHide = CustomerCentral.getElementsByClass('ModelHistoryToHide');
    for (var i = 0; i < allElementsToHide.length; i++) {
        allElementsToHide[i].style.display = 'none';
    }
    var modelNotListedButton = $('[id$=_btnModelNotListed]')[0];
    if (modelNotListedButton != null) {
        modelNotListedButton.style.display = 'none';
    }
}

/***************************************************************
Function CustomerCentral.IsClaimInProgress
****************************************************************/
CustomerCentral.IsClaimInProgress = function (toForwardTo) {
    function OnSuccess(result) {
        if (!result) {
            CustomerCentral.OpenWindow(toForwardTo);
        } else {
            CustomerCentral.DisplayMessage($('[id$=_hdClaimInProgres]').val(), $('[id$=_hdThereisalreadyaclaiminprogressforthissubscriber]').val());
        }

        CustomerCentral.HideCreateLinks();
    }


    /***************************************************************
    Function OnFailure
    ****************************************************************/
    // I'm doing this because we always want to at least open the claim wizard,
    // if this doesn't work then we would be screwed.  This check is fairly redundant
    // anyways
    function OnFailure(e) {
        CustomerCentral.OpenWindow(toForwardTo);

        var allElementsToHide = CustomerCentral.getElementsByClass('ModelHistoryToHide');
        for (var i = 0; i < allElementsToHide.length; i++) {
            allElementsToHide[i].style.display = 'none';
        }
        var modelNotListedButton = $('[id$=_btnModelNotListed]')[0];
        if (modelNotListedButton != null) {
            modelNotListedButton.style.display = 'none';
        }

    }

    PageMethods.set_path('CustomerCentral.aspx');
    PageMethods.IsClaimInProgess(OnSuccess, OnFailure);
}

/***************************************************************
Function CustomerCentral.SaveSubscriberContactInfo
****************************************************************/
CustomerCentral.SaveSubscriberContactInfo = function (altPhone, email, alternateUser, initialSubscriber, OnSuccess, OnFailure) {
    // subscriberID injected from code-behind
    PageMethods.set_path('CustomerCentral.aspx');
    PageMethods.UpdateSubscriberContactInformation(altPhone, email, alternateUser, initialSubscriber, OnSuccess, OnFailure);
}

/***************************************************************
Function CustomerCentral.AddAutoNote
****************************************************************/
CustomerCentral.AddAutoNote = function (note) {
    CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnLookup]').attr('id'), false);
    try {
        var txtHiddenNoteToAdd = $('[id$=_hidHiddenNote]')[0];
        var addHiddenNoteButton = $('[id$=_btnAfterNoteUpdate]')[0];

        txtHiddenNoteToAdd.value = note;

        addHiddenNoteButton.click();
    }
    catch (e) {
        // maybe need to log this...
    }
}

/***************************************************************
Function CustomerCentral.disableAnchor
****************************************************************/
CustomerCentral.disableAnchor = function (obj, disable) {
    if (disable) {
        var href = obj.getAttribute('href');
        if (href && href != '' && href != null) {
            obj.setAttribute('href_bak', href);
        }
        obj.removeAttribute('href');
        obj.style.color = 'gray';
    }
    else {
        if (obj.attributes['href_bak'] != 'undefined'
            && obj.attributes['href_bak'] != null) {
            if (typeof (obj.href) != 'undefined') {
                obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
            }
        }
        obj.style.color = 'blue';
    }
}

/***************************************************************
Function CustomerCentral.SetPanelsEnabled
****************************************************************/
CustomerCentral.SetPanelsEnabled = function (toSet) {
    var claimHistory = $('[id$=_pnlClaimHistory]')[0];
    var escalationHistory = $('[id$=_pnlEscalationHistory]')[0];
    //var noteHistory = $('[id$=_pnlNoteHistory]')[0];
    var handsetHistory = $('[id$=_pnlHandsetHistory]')[0];

    claimHistory.disabled = !toSet;


    escalationHistory.disabled = !toSet;
    handsetHistory.disabled = !toSet;
    //noteHistory.disabled = !toSet;

    var anchorsToDisable = document.getElementsByTagName('a');

    for (var i = 0; i < anchorsToDisable.length; i++) {
        if (anchorsToDisable[i].href.endsWith('/esecuritel/HITS/WebSite/site/HITS/Claims/Default.aspx'))
            CustomerCentral.disableAnchor(anchorsToDisable[i], true);
        else if (anchorsToDisable[i].className != 'DoNotDisable') {
            CustomerCentral.disableAnchor(anchorsToDisable[i], !toSet);
        }
    }

    var toDisable = CustomerCentral.getElementsByClass('ToDisable');

    for (var i = 0; i < toDisable.length; i++) {

        toDisable[i].disabled = !toSet;
    }

    var toArchivedHandsetHistoryButtonCustomerCentralDisable = CustomerCentral.getElementsByClass('ArchivedHandsetHistoryButtonCustomerCentral');

    if ((toArchivedHandsetHistoryButtonCustomerCentralDisable != null) && (toArchivedHandsetHistoryButtonCustomerCentralDisable.length > 0)) {

        for (var i = 0; i < toArchivedHandsetHistoryButtonCustomerCentralDisable.length; i++) {

            toArchivedHandsetHistoryButtonCustomerCentralDisable[i].disabled = !toSet;
        }
    }

}

/***************************************************************
Function CustomerCentral.SetAllChildrenDisabled
****************************************************************/
CustomerCentral.SetAllChildrenDisabled = function (control, toSet) {

    if (typeof (control.disabled) != 'undefined') {
        try {
            control.disabled = !toSet;
        }
        catch (e) {
        }
    }

    if (typeof (control.href) != 'undefined') {
        CustomerCentral.disableAnchor(control, !toSet);
    }

    if ((control.childNodes == null) || (control.childNodes.length == 0)) {
        return;
    }

    for (var i = 0; i < control.childNodes.length; i++) {
        CustomerCentral.SetAllChildrenDisabled(control.childNodes[i], toSet)
    }
}

/***************************************************************
Function CustomerCentral.OpenWindow
****************************************************************/
CustomerCentral.OpenWindow = function (url) {
    var newWindow = window.open(url, '_blank');
    newWindow.opener = window;
    return false;
}


/***************************************************************
Function CustomerCentral.BtnModelNotListed_Click
****************************************************************/
CustomerCentral.BtnModelNotListed_Click =
    function (CANTakeClaimOnTermedSubs, CANTakeHotLine, status) {
        //5.5 moved these auto notes to the server side code

        //Don't permit creating claim if hotlined and override switch is off.
        if (CANTakeHotLine == 'False') {
            CustomerCentral.DisplayMessage($('[id$=_hdHeaderMessageHotlined]').val(),
                $('[id$=_hdCANTakeClaimOnHotlinedSubscriberWarningBody]').val());
        }
        else if (status == 'Pending') {
            CustomerCentral.DisplayMessage($('[id$=_hdCANTakeClaimOnTermedSubscriberWarningHeader]').val(),
                $('[id$=_hdCANTakeClaimOnPendingSubscriberWarningBody]').val());
        }
        else if (CANTakeClaimOnTermedSubs == 'False') {
            CustomerCentral.DisplayMessage($('[id$=_hdCANTakeClaimOnTermedSubscriberWarningHeader]').val(),
                $('[id$=_hdCANTakeClaimOnTermedSubscriberWarningBody]').val());
        }
        else {
            //test
            var test = $('[id$=_tabHandsetHistoryPanel2_ucModelHistory]').val();
            var toForwardTo = CustomerCentral[ucModelHistory].Forward_URL
                + 'CC=1&'
                + CustomerCentral[ucModelHistory].SubscriberIDQueryString
                + '='
                + subscriberID;

            CustomerCentral.IsClaimInProgress(toForwardTo);
        }

        //Refresh history
        CustomerCentral.EnableExceptionPanels();
    }


/***************************************************************
Function CustomerCentral.getElementsByClass
****************************************************************/
CustomerCentral.getElementsByClass = function (searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

/***************************************************************
Function CustomerCentral.RefreshSubscriberID
****************************************************************/
CustomerCentral.RefreshSubscriberID = function () {
    subscriberID = $('[id$=_hidSubscriberID]').val(); // subscriberID injected from code behind

    if (subscriberID == 0 || subscriberID == '') {
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnRefresh]').attr('id'), false);
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnEndCall]').attr('id'), false);
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnLookup]').attr('id'), true);
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnTerminateCC]').attr('id'), false);
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnUpdateCC]').attr('id'), false);
    }
    else {
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnRefresh]').attr('id'), true);
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnEndCall]').attr('id'), true);        
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnTerminateCC]').attr('id'), true);
        CustomerCentral[ucSubscriberDetailId].ToggleButton($('[id$=_ibtnUpdateCC]').attr('id'), true);
    }
}

/***************************************************************
Function CustomerCentral.EnableExceptionPanels
****************************************************************/
CustomerCentral.EnableExceptionPanels = function () {
    //var panelNoteHistory = $('[id$=_pnlNoteHistory]')[0];
    var panelEscalationHistory = $('[id$=_pnlEscalationHistory]')[0];
    //var userControlNoteHistoryTop = $('[id$=_ucNoteHistoryTop_txtNotes]')[0];
    //var userControlNoteHistoryAll = $('[id$=_ucNoteHistoryAll_txtNotes]')[0];

    if (subscriberID == 0 || subscriberID == '') {
        //   panelNoteHistory.disabled = true;
        panelEscalationHistory.disabled = true;
    } else {
        //  panelNoteHistory.disabled = false;
        panelEscalationHistory.disabled = false;
    }
}


/***************************************************************
???
****************************************************************/
CustomerCentral['IsValidated'] = false;
CustomerCentral['PreviousSubscriberID'] = 0;

/***************************************************************
Function CustomerCentral.ShowOrHideThirdTab
****************************************************************/
CustomerCentral.ShowOrHideThirdTab = function () {

    //            var tabSubscriberDetails = $find('<%= ucSubscriberDetail.TabSubscriberDetailsClientID %>');
    //            var showOrHideThirdTab = $('#<%= ucSubscriberDetail.HidThirdTabEnabledClientID %>');
    //            var tabSubscriberDetailsPanel3 = $find('<%= ucSubscriberDetail.TabSubscriberDetailsPanel3ClientID %>');

    /**
    if (showOrHideThirdTab.val() == 'true') {
    tabSubscriberDetails.get_tabs()[2].get_headerTab().setAttribute('display', 'none');
    } else {
    tabSubscriberDetails.get_tabs()[2].get_headerTab().setAttribute('display', 'inline');
    }
    **/

    //            if (tabSubscriberDetails !== null) {
    //                if (tabSubscriberDetails.get_activeTab().get_tabIndex() > 1) {
    //                    tabSubscriberDetails.set_activeTab(tabSubscriberDetails.getFirstTab());
    //                }
    //            }
}


/***************************************************************
Function CustomerCentral.BeginRequestHandler
****************************************************************/
CustomerCentral.BeginRequestHandler = function (sender, args) {
    CustomerCentral['IsValidated'] = CustomerCentral[ucSubscriberDetailId].IsValidated();
    CustomerCentral['PreviousSubscriberID'] = $('[id$=_hidSubscriberID]').val();
    CustomerCentral.ShowOrHideThirdTab();
}

/***************************************************************
Function CustomerCentral.EndRequestHandler
****************************************************************/
CustomerCentral.EndRequestHandler = function (sender, args) {
    if (args.get_error() != undefined) {
        //                debugger;
        alert(args.get_error().description);
        args.set_errorHandled(true);
    }

    try {

        CustomerCentral[ucSubscriberDetailId].CollapseSearch();

        CustomerCentral.RefreshSubscriberID();

        if (CustomerCentral['PreviousSubscriberID'] != subscriberID) {
            CustomerCentral[ucSubscriberDetailId].SetEnabled(false, false);
            $('[id$=_pnlCarrierMessage]')[0].scrollTop = 0;
        }
            //	            else if (sender._postBackSettings.sourceElement.id.indexOf(ucSubscriberDetailId) == -1) {
            //	                // Do Nothing

            //	                //CustomerCentral.EnableExceptionPanels();
            //	                //return;
            //	            } 
        else {

            if (CustomerCentral['IsValidated']) {
                CustomerCentral[ucSubscriberDetailId].SetEnabled(true, false);
            } else {
                CustomerCentral[ucSubscriberDetailId].SetEnabled(false, false);
            }
        }

        //                CustomerCentral.ShowOrHideThirdTab();
    }
    catch (e) {
    }
    finally {
        CustomerCentral.EnableExceptionPanels();
    }
}


/***************************************************************
?????
****************************************************************/
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(CustomerCentral.EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(CustomerCentral.BeginRequestHandler);

/***************************************************************
Function document.RefreshCustomerCentralUpdatePanels
****************************************************************/
document.RefreshCustomerCentralUpdatePanels = function () {
    try {
        var btnRefresh = $('[id$=_ibtnRefresh]')[0];
        btnRefresh.click();
    }
    catch (e) {
        alert('An exception occurred while refreshing the page.');
    }
}

CustomerCentral[ucSubscriberDetailId].SetEnabled(false, false);
CustomerCentral.RefreshSubscriberID();
CustomerCentral.EnableExceptionPanels();

//Second script block from the page

if (typeof (CustomerCentral) != 'undefined') {
    CustomerCentral['__Page'] = new Object();

    CustomerCentral['__Page'].CreateClaim =
    function (subscriberID, handsetHistoryID, subscriberName, handsetModel, CANTakeClaimOnTermedSubs, ESN, isPending) {
        var labelSubscriberStatus = $('[id$=_lblStatus]')[0];

        try {
            if ((typeof (CustomerCentral) != 'undefined') && (typeof (CustomerCentral.AddAutoNote) != 'undefined')) {
                if (labelSubscriberStatus.innerHTML == 'Pending')
                    //if (isPending == "1")
                {
                    CustomerCentral.AddAutoNote($('[id$=_hdCANTakeClaimOnHotlinedSubscriberWarningBody]').val());
                }
                else {
                    CustomerCentral.AddAutoNote($('[id$=_hdCreateClaimLinkClickedfromHandsetHistoryGridSubscriber]').val() + subscriberName + $('[id$=_hdCreateClaimLinkClickedfromHandsetHistoryGridHandsetModel]').val() + handsetModel + ", ESN: " + ESN);
                }
            }
        }
        catch (e) {
        }
        finally {
            try {
                var toForwardTo = CustomerCentral['__Page'].Forward_URL
                            + 'CC=1&'
                            + CustomerCentral['__Page'].SubscriberIDQueryString
                            + '='
                            + subscriberID
                            + '&'
                            + CustomerCentral['__Page'].HandsetHistoryIDQueryString
                            + '='
                            + handsetHistoryID;

                var hiddenAllowClaimHotline = $('[id$=_hdnALLOW_CLAIM_DURING_HOTLINED]')[0];
                var hiddenAllowClaimHotlineMessage = $('[id$=_hdnAllowClaimHotlineMessage]')[0];
                var labelHotline = $('[id$=_lblIsHotlined]')[0];

                //Don't permit creating claim if hotlined and override switch is off.
                if (labelHotline.innerHTML != 'No' && hiddenAllowClaimHotline.value == 'False') {
                    CustomerCentral.DisplayMessage('Hotlined', hiddenAllowClaimHotlineMessage.value);

                    CustomerCentral.AddAutoNote(hiddenAllowClaimHotlineMessage.value);
                    return;
                }

                if (labelSubscriberStatus.innerHTML == 'Pending') {
                    //CustomerCentral.HideCreateLinks();
                    CustomerCentral.DisplayMessage($('[id$=_hdLabelSubscriberPending]').val(), $('[id$=_hdLabelCanNotCreateClaimSubsPending]').val()); //CustomerCentral.DisplayMessage('Subscriber Pending', 'Cannot create claims. Subscriber is in Pending status');
                    return;
                }

                if (CANTakeClaimOnTermedSubs == 'False') {
                    CustomerCentral.AddAutoNote($('[id$=_hdCANTakeClaimOnTermedSubscriberWarningBody]').val());
                    CustomerCentral.DisplayMessage($('[id$=_hdCANTakeClaimOnTermedSubscriberWarningHeader]').val(),
                        $('[id$=_hdCANTakeClaimOnTermedSubscriberWarningBody]').val());
                    return;
                }

                // This will check to see if a claim is in progress before opening the window
                CustomerCentral.IsClaimInProgress(toForwardTo);
            }
            catch (e) {

            }
        }
        //            return false;
    } //end of function CustomerCentral['__Page'].CreateClaim
}

function ResizeObject(height) {
    var host = document.getElementById("silverlightControlHostEnrollHandset");
    if (document.documentElement.clientHeight < height) {
        host.style.height = height + "px";
    }
    else {
        host.style.height = document.documentElement.clientHeight.toString() + "px";
    }
}

$(function () {
    $('[id$=_btnEnrollNewHandsetNew]').click(function () {
        $('#divLoading').css("display", "inline-block");
    });
});

function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }

    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    if (errorType == "ImageError" || errorType == "MediaError") {
        return;
    }

    var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    throw new Error(errMsg);
}

function filerByEsn() {
    if ($("[id$=_ddlEsn] option:selected").index() > 0) {
        var ESN = $("[id$=_ddlEsn] option:selected").text();
        $("[id$=_ucHandsetHistoryAll_m_grdHistoryOfHandsets]").find("tr").each(function (index, ele) {
            if (index > 0 && $(this).children().eq(1).text().trim() != ESN)
                $(this).hide();
            else {
                $(this).show();
            }
        });
    } else {
        $("[id$=_ucHandsetHistoryAll_m_grdHistoryOfHandsets]").find("tr").each(function () {
            $(this).show();
        });
    }
}

function showHIPManagerPOP(event) {
    var modalUrl = "../HIPManager/HIPManagerPOP.aspx";
    var hiddenUrlField = $(event).parent().find("input[id*='hfModal']");
    if (hiddenUrlField.val() != null)
        modalUrl = hiddenUrlField.val();
    $.colorbox({
        iframe: true, href: modalUrl, title: "HIP Manager", width: "480px", height: "310px", retinaImage: true, retinaUrl: true, overlayClose: false, fastIframe: false, scrolling: true
    });
}


CustomerCentral.PreventUpdateCreditCardInfoDuringMRC = function (OnSuccess, OnFailure) {
    PageMethods.set_path('CustomerCentral.aspx');
    PageMethods.PreventUpdateCreditCardInfoDuringMRC(OnSuccess, OnFailure);
}
