﻿// Fő javascript file, minden oldal alapja!
var ajaxCounter = 0;
function InitForm() {


    //AjaxCallStart();
    
    // Minden oldalnak implementalni kell egy sajat javascript filet, oda lehet betenni az oldal specifikus hívasokat
    // Fontos az elnevezes is
    InitFormSpec();
    // Session timeout
    if (Utils.CheckSession == true)
    {
        if ($.timeout)
            $.timeout(Utils.TimeoutInterval);
    }
    // Bejelentkezett felhasznalo
    Utils.loggedUser();
    // Informacios ablak becsukasa
    Utils.closeInformation();

    $(document).ajaxStart(AjaxCallStart);
    $(document).ajaxComplete(AjaxCallStop);
//    $(document).ajaxStop(UnBlockUI);

    //AjaxCallStop();
}
function AjaxCallStart()
{
    ajaxCounter++;
    BlockUserInterface();
}
function AjaxCallStop()
{
    ajaxCounter--;
    if (ajaxCounter <= 0)
    {
        UnBlockUI();
        ajaxCounter = 0;
    }
}

function UnBlockUI(fadeCallBack)
{
    $.unblockUI({ onUnblock: fadeCallBack });
}
function BlockUserInterface(fadeCallBack)
{
    $.blockUI(
            {
                message: '<span id="ajaxBlockProgress">Kérem várjon...</span>',
                css: {cursor:'default', centerY: 0, color: 'white', backgroundColor: '#AAAAAA', opacity: 0.8, border: '0', bottom: '10px',right:'10px',left:'', top:''},
                overlayCSS: {cursor:'default', backgroundColor: 'transparent'},
                onBlock:fadeCallBack
                
            });
}
// Utility függvények, az egész alkalmazásban elérhetőek
// Hívás statikus függvényenként: Utils.formatJSONDate(...);
var Utils = {
    PageSize: 50,
    CheckSession: true,
    TimeoutInterval: 3600 * 1000, // Seconds * 1000
    LoginType: 0,

    // JSON datatime átalakítása
    formatFromJSONDate: function(jsonDate)
    {
        if (jsonDate == null) return "";
        if (jsonDate == "") return "";
        var DateString = parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10);
        var JsDate = new Date(DateString);
        var newDate = dateFormat(JsDate, "yyyy.mm.dd");
        return newDate;
    },

    // JSON datatime átalakítása
    formatFromJSONDateTime: function(jsonDate)
    {
        if (jsonDate == "") return "";
        if (jsonDate == null) return "";
        var DateString = parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10);
        var JsDate = new Date(DateString);
        var newDate = dateFormat(JsDate, "yyyy.mm.dd HH:MM:ss");
        return newDate;
    },

    // Dátum átalakítása JSON dátummá
    formatToJSONDate: function(jsonDate)
    {
        if (jsonDate == "") return "";
        if (jsonDate == null) return "";
        var DateString = parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10);
        var JsDate = new Date(DateString);
        var newDate = dateFormat(JsDate, "yyyy.mm.dd");
        return newDate;
    },

    // Breadcrumb beállítása
    ePayBreadCrumb: function()
    {
        $("#breadCrumb").jBreadCrumb();
    },

    // ToolTip
    ePayToolTip: function()
    {
        $("#question").tooltip({
            position: "bottom left"
        });
    },

    // Loader inditas illetve leallitasa
    loader: function(startLoader)
    {
        if (startLoader)
        {
            $('#progressBackgroundFilter').fadeIn();
            $('#loadingbox').fadeIn();
            $('#loader').fadeIn();
        } else
        {
            $('#progressBackgroundFilter').fadeOut();
            $('#loadingbox').fadeOut();
            $('#loader').fadeOut();
        }
    },

    // Adat lekerdezes eseten amikor nem jnon vissza semmi adat
    noRecord: function(e)
    {
        if (e == "" || e == null)
        {
            $('#nofound').show();
        }
        else
        {
            $('#nofound').hide();
        }
    },

    // Adat lekerdezes eseten amikor nem jnon vissza semmi adat
    noRecordByTagId: function(e, tagid)
    {
        if (e == "" || e == null)
        {
            $(tagid).show();
        }
        else
        {
            $(tagid).hide();
        }
    },

    // Informacios div megjelenitese szoveggel
    showInformation: function(message)
    {
        if (message != "")
        {
            $("#informationMessage").addClass("color-2");
            $("#informationMessage").html(message);
            $("#informationPlaceholder").fadeIn();
        }
    },

    // Informacios div megjelenitese szoveggel
    errorInformation: function(message)
    {
        if (message != "")
        {
            var err = eval("(" + message.responseText + ")");
            if (err.Message == "Authentication failed.")
            {
                window.location = "Login.aspx";
            } else
            {
                $("#informationMessage").addClass("color-1");
                $("#informationMessage").html(err.Message);
                $("#informationPlaceholder").fadeIn();
                document.getElementById('informationMessageStart').scrollIntoView(true);
            }
        }
    },

    // Informacios div megjelenitese szoveggel
    baseErrorInformation: function(message)
    {
        if (message != "")
        {
            $("#informationMessage").addClass("color-1");
            $("#informationMessage").html(message);
            $("#informationPlaceholder").fadeIn();
            document.getElementById('informationMessageStart').scrollIntoView(true);
        }
    },

    // Informacios div bezarasara esemeny kotese
    closeInformation: function()
    {
        $("#closeInformation").click(function()
        {
            $("#informationPlaceholder").addClass("hideInformation");
            $("#informationPlaceholder").fadeOut();
        });
    },

    forceCloseInformationBar: function()
    {
        $("#informationPlaceholder").addClass("hideInformation");
        $("#informationPlaceholder").fadeOut();
    },

    logout: function()
    {
        $.ajax({
            type: "POST",
            //url: "Page/Service/EmployeeService.asmx/LoginUser",
            url: "/AdminPages/Main.asmx/Logout",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg)
            {
                if (msg.d == true)
                {
                    window.location = '/Default.aspx';
                }
                else
                {
                    // Wrong
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                //Error
            }
        });
    },

    loggedUser: function()
    {
        if ($("#logged").get(0))
        {
            $.ajax({
                type: "POST",
                //url: "Page/Service/EmployeeService.asmx/LoginUser",
                url: "/AdminPages/Main.asmx/LoggedUser",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg)
                {
                    if (msg.d != null)
                    {
                        $("#logged").html(msg.d);
                    }
                    else
                    {
                        // Wrong
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                    //Error
                }
            });
        }
    },

    getMainUrl: function()
    {
        //        var path = location.href;
        //        if (document.all) {
        //            path = path.replace(/\\/g, "/");
        //        }
        return location.protocol + '//' + location.host;
    },

    hasCards: function()
    {
        var parameters = "{" + "pageSize:1, pageNumber:1, filter:''}";
        $.ajax({
            url: "PartnerCards.aspx/GetCardCount",
            data: parameters,
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: (function Success(data, status)
            {
                if (data.d == 0)
                    Utils.showInformation("Egyetlen ügyfélkártya sincs hozzárendelve ehhez a partnerhez! Forduljon a 6x6 Taxi ügyfélmenedzseréhez.");
            })
            ,
            error: (function Error(request, status, error)
            {
                Utils.errorInformation(request);
            })
        });
    },

    numberFormat: function(number)
    {
        formatedNumber = $().numberFormat(number, { decimalSeparators: '.', thousandsSeparator: ' ', decimalsLimit: 0 });
        return formatedNumber;
    },

    setDateControl: function(clearbutton)
    {
        Date.format = 'yyyy.mm.dd';
        $('.date-pick').datePicker({
            autoFocusNextInput: true,
            startDate: '1900.01.01',
            showButtonPanel: true,
            createClearButton: clearbutton
        });
        $('.dp-choose-date').css('float', 'left');
    }
}

jQuery.fn.ForceNumericOnly =
function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};
