﻿/// <reference path="jquery-vsdoc.js" />

var animSpeed = "fast";

jQuery.fn.delay = function(duration, callback)
{
    return this.animate({ opacity: 1.0 }, duration, callback);
};

function pageLoad()
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (!prm.get_isInAsyncPostBack())
    {
        fnSetActiveTab();
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(fnBeginRequestHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(fnPageLoadingHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(fnEndRequestHandler);
    }

}

jQuery(function($)
{
    $(".round").corner('10px');

    fnSetNavVisilility();

    $.event.special.hover.delay = 300;
    fnBindQuickSearchControl();
    fnBindRecentCustomersControl();

    if ($("#searchBoxContainer").length > 0)
    {
        //fnRestoreSearchBox($('#searchBoxContainer input'));

        $("input[id$='tbSearchBox']").bind('keypress', fnSearchKeyPress);
        $("div#searchBoxContainer a.bigsrchbutton").click(fnSearchClick);
    }

    $("#tdspCharges").dialog({
        title: $('#tdspCharges div.holder')
        , autoOpen: false
        , modal: true
        , width: '900'
        , height: '580'
        //, show: 'slide'
        //, hide: 'drop'
        , overlay: {
            opacity: 0.5
            ,background: "black"
        }
    })

    //$("#header").fadeIn(500, function() { $("#workarea").fadeIn(500); });
    //$("#ttt").animate({ opacity: 'show' }, 1200);
});

function fnJQueryAJAXCall(url, dataJson, successFunction, errorFunction)
{

    fnHideErrorMessage();
    fnBusyBarShow();
    
    $.ajax({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: dataJson,
        success: successFunction,
        error: function(xhr, msg, e) { errorFunction(xhr) }
    });
}

function fnSetNavVisilility()
{
    // Pages with disabled navigation
    var pages = new Array(
                        {"url":"login.aspx", "hideCrum": true, "hideNav": true}
                        , {"url": "changepassword.aspx", "hideCrum": true, "hideNav": true}
                        , {"url": "logout.aspx", "hideCrum": true, "hideNav": true }
                        , {"url": "accountsearch.aspx", "hideCrum": false, "hideNav": true}
                        );
    for (var i = 0; i < pages.length; i++)
    {
        if (fnGetCurrentPageName().toLowerCase().indexOf(pages[i].url) != -1)
        {
            if (pages[i].hideCrum) $("#crumb ul").hide();
            if (pages[i].hideNav) $("#customernav ul").hide();
            return;
        }
    }
}

function fnSetActiveTab()
{
    if ($("#customernav ul:visible").length < 1) return;
    $("#customernav a[class='active']").removeClass('active');
    $("#customernav a[href$='" + fnGetCurrentPageName() + "']").addClass('active').attr("href","javascript:void(0);").css("cursor","normal");
}

function fnGetCurrentPageName() {return fnGetPageName(window.location.href, 'aspx'); } 
function fnGetPageName(url, ext)
{
    var page = unescape(url);
    page = page.substr(page.lastIndexOf('.com/') + 1);
    page = page.substr(4, page.indexOf('.' + ext) + 1);
    return page;
}

function fnPageLoadingHandler(sender, args)
{
    var dataItems = args.get_dataItems();
    //alert("PageLoadingHandler: " + dataItems.length)
}

function fnBeginRequestHandler(sender, args)
{
    fnHideErrorMessage();
    fnBusyBarShow();
}

function fnEndRequestHandler(sender, args)
{
    fnBusyBarHide();
    //alert("EndRequestHandler: " +sender)
    if (args.get_error() != null)
    {
        var error = args.get_error();
        if (error.name.length > 0)
        {
            args.set_errorHandled(true);
            fnShowErrorMessage(error.description.split('\n')[0], error.description);
        }
    }

}

function fnBusyBarShow() { $('#busybar').slideDown(animSpeed); }
function fnBusyBarHide() { $('#busybar').slideUp(animSpeed); }

function fnHideErrorMessage() { if ($('#errorbar').is(':visible')) $('#errorbar span').text('').parent().slideToggle(100); }
function fnShowErrorMessage(msg) { fnShowErrorMessage(msg, ""); }
function fnShowErrorMessage(msg, desc) { $("#failurebar:visible, #sucbar:visible").hide(); $('#errorbar span').text(msg).parent().slideDown(100).attr("title", desc); }

function fnBindQuickSearchControl()
{
    $('a#anchorCustSearch').hover(fnShowSearchCustomerContainer, function() { $('div#navsearch').delay(50, function() { $(this).hide().css('visibility', 'hidden'); }); });
    $('div#navsearch').bind('mouseenter', fnShowSearchCustomerContainer);
    //$('a#anchorCustSearch').bind('mouseleave', function() { $('div#navsearch').delay(50, function() { $(this).hide().css('visibility', 'hidden'); }); });
    $('div#navsearch').bind('mouseleave', fnHideSearchCustomerContainer);
    $("input#bQuickSearch").click(fnQuickSearchClick);
    $("input#txtQuickSearch").bind("keypress", fnQuickSearchKeyPress);
    $('input#bSearch').click(function() { $('div#navsearch').hide() });
    $('#crumb li').children('a[id!="anchorCustSearch"]').bind('mouseenter', function() { $('div#navsearch').stop().hide(); });
}

function fnShowSearchCustomerContainer(e) { $('div#navsearch').stop(); $('div#navsearch').show().css('visibility', 'visible').animate({ opacity: 1.0 }, 1); }
function fnHideSearchCustomerContainer(e) { if ($('div#navsearch').is(":visible")) $('div#navsearch').fadeOut(10000); }  

function fnQuickSearchKeyPress(event)
{
    if (event.which != 13) return;
    fnQuickSearchClick();
    return false;
}

function fnSearchKeyPress(event)
{
    if (event.which != 13) return;
    fnSearchClick();
    return false;
}

function fnSearchClick()
{
    //var rg = new RegExp("((\s*[0-9a-zA-Z]{2,}:[0-9a-zA-Z]{3,})|(\s*[0-9a-zA-Z]{3,}))*", "g");
    //debugger;
    if ($("input[id$='tbSearchBox']").val().length < 3) fnShowErrorMessage("Enter at least 3 characters to search.");
    else $("input[id$='bSearch']").click();
    
    return false;
}

function fnQuickSearchClick()
{
    var val = $("input#txtQuickSearch").val();
    if (val == "") return;

    //$.blockUI();
    window.location.href = '/AccountSearch.aspx?qst=' + $("select[id$=ddQuickSearch]").val() + '&qsv=' + escape(val);
    return false;
}

function fnBindRecentCustomersControl() {
//    $('a#anchorrecentcust').bind('mouseenter', fhOnMouseOverRecentCustomerAnchor);
//    $('a#anchorrecentcust').bind('mouseleave', );
    //$('div#navrecentcust').bind('mouseleave', function() { $('div#navrecentcust').data("close", 0); fhHideRecentCustomerContainer(); })
    $('div#navrecentcust').bind('mouseleave', function() { $('div#navrecentcust').data("close", 0).delay(300, fhHideRecentCustomerContainer); })
    $('div#navrecentcust').bind('mouseenter', fhShowRecentCustomerContainer)
    $('a#anchorrecentcust').hover(fhOnMouseOverRecentCustomerAnchor, function() { $('div#navrecentcust').data("close", 0).delay(50, fhHideRecentCustomerContainer); });
   // $('div#navrecentcust').hover(function() { }, function() { $('div#navrecentcust').data("close", 0); fhHideRecentCustomerContainer(); })

}

function fhOnMouseOverRecentCustomerAnchor()
{
    fhShowRecentCustomerContainer();
}

function fhShowRecentCustomerContainer()
{
    $('div#navsearch').hide();
    $('div#navrecentcust').data("close", 1).slideDown(150);
}

function fhHideRecentCustomerContainer()
{    //alert($('div#navrecentcust').data("close"))
    //$("#mm").html($('div#navrecentcust').data("close") + "=" + $('div#navrecentcust').is(":visible"));
    if ($('div#navrecentcust').data("close") != 1 && $('div#navrecentcust').is(":visible")) $('div#navrecentcust').slideUp(150);
}

function fnGoToCustomer(custid) { document.location.href = "/GeneralInformation.aspx?CustID=" + custid; }

var searchBoxText = 'Enter name, account #, ESI or Premise address';
function fnClearSearchBox(o) { if ($(o).val() == searchBoxText) $(o).val('') }
function fnRestoreSearchBox(o) { if ($(o).val() == '') $(o).val(searchBoxText).blur() }


function fnRegisterToggle(src, key, tr)
{

    //alert(src + '\n' + key);return;
    tr = $(tr).next();
    if (tr.is(':visible'))
    {
        fnSlideUpTr(tr);
    }
    else if (tr.find('div.root').length > 0) fnSlideDownTr(tr);
    else fnLoadView(src, key, tr);
}

function fnLoadView(src, key, tr)
{
    var methodName = "";
    var paramName = "";
    if (src == 0)
    {
        methodName = "LoadInvoiceView";
        paramName = "invoiceId";
    }
    else if (src == 1)
    {
        methodName = "LoadPaymentView";
        paramName = "paymentDetailId";
    }
    else if (src == 2)
    {
        methodName = "LoadAdjustmentView";
        paramName = "adjustmentId";
    }
    else return;
        
    fnJQueryAJAXCall(
        "WebServices/B2BWebService.asmx/" + methodName
        , "{'" + paramName + "':'" + key + "'}"
        , function(result) { fnSucceededLoadView(result, tr); }
        , fnFailedLoadView
    )
}


function fnSlideDownTr(tr) { tr.show().find('div.root').hide().animate({ height: 'show' }, 800, 'easeOutBounce', function() { tr.next().children("td:eq(1)").focus() }); }  //slideDown(animSpeed, 'easeOutElastic'); }
function fnSlideUpTr(tr) { tr.find('div.root').animate({ height: 'hide' }, 800,  'easeOutBounce', function() { tr.hide(); }); }//slideUp(animSpeed, function() { tr.hide(); }); }

function fnSucceededLoadView(result, tr)
{
    fnBusyBarHide();
    if (tr == null) return;
    tr.children("td").html(result.d);
    fnSlideDownTr(tr);
}

function fnFailedLoadView(xhr)
{
    fnBusyBarHide();
    var errorMessage = "";
    try
    {
        var error = new Function("return " + xhr.responseText)(); // parsing json message to object
        errorMessage = error.Message;
    }
    catch (e)
    {
        errorMessage = xhr.responseText;
    }
    fnShowErrorMessage(errorMessage);
}

function fnChargeSummaryViewDetailsToggle(o)
{
    var elements = $(o).parent().find('div.condetails');
    if ($(o).parent().find('div.condetails:visible').length > 0) elements.slideUp(animSpeed);
    else elements.slideDown(animSpeed);
    //alert($(o).parent().find('div.condetails:visible').length)
}

function fnViewUtilityCharges(invoiceId)
{

    if (!invoiceId) return;
    
    fnJQueryAJAXCall(
        "WebServices/B2BWebService.asmx/LoadUtilityChargesView"
        , "{'invoiceId':'" + invoiceId + "'}"
        , function(result) { fnSucceededLoadUtilityChargesView(result); }
        , fnFailedLoadView
    )
    
    // $.blockUI({ message: $('#tdspcharge'), css: { cursor: 'normail', width: 'auto' } });
   
}


function fnSucceededLoadUtilityChargesView(result)
{
    fnBusyBarHide();
    $("#tdspCharges div.content").html(result.d); //.dialog("open");
    $("#tdspCharges").dialog("open");
}

function fnCloseUtilityCharges() {
    // $.blockUI({ message: $('#tdspcharge'), css: { cursor: 'normail', width: 'auto' } });
    $("#tdspCharges").dialog("close");
}