﻿var emptyGuid = "00000000-0000-0000-0000-000000000000";
var isServerProccess = false, isSearchTry = false, currentId = emptyGuid;

function replaceAll(txt, replace, with_this) { return txt.replace(new RegExp(replace, 'g'), with_this); }

//ToPersia
function ToPersia(n) {
    n = n.toString();
    var result = "";
    for (var i = 0; i < n.length; i++) {
        var code = n.charCodeAt(i);
        switch (code) {
            case 48: result += '۰'; break;
            case 49: result += '۱'; break;
            case 50: result += '۲'; break;
            case 51: result += '۳'; break;
            case 52: result += '۴'; break;
            case 53: result += '۵'; break;
            case 54: result += '۶'; break;
            case 55: result += '۷'; break;
            case 56: result += '۸'; break;
            case 57: result += '۹'; break;
            default: result += n[i];
        }
    }
    return result;
}

function ToInt(n) {
    return parseInt(parseFloat(n));
}

//ToEnglish
function ToEnglish(n) {
    n = n.toString();
    var result = "";
    for (var i = 0; i < n.length; i++) {
        var code = n[i];
        switch (code) {
            case '۰': result += '0'; break;
            case '۱': result += '1'; break;
            case '۲': result += '2'; break;
            case '۳': result += '3'; break;
            case '۴': result += '4'; break;
            case '۵': result += '5'; break;
            case '۶': result += '6'; break;
            case '۷': result += '7'; break;
            case '۸': result += '8'; break;
            case '۹': result += '9'; break;
            default: result += n[i];
        }
    }
    return result;
}

//باز و بسته شدن پنل
$(function () {
    $('#imgSearchPanel').toggle(function () {
        $('#dataentrywrap').hide();
        $('#pnlPaging').hide();
        $get('imgSearchPanel').src = "../Images/Down.png";
        RefreshGridSize();
        $('#gridContainer table tr:gt(0)').show();
    }, function () {
        $('#dataentrywrap').show();
        $('#pnlPaging').show();
        $get('imgSearchPanel').src = "../Images/Up.png";
        RefreshGridSize();
        GotoPage(currentPage);
    });
});

//SortGrid
function SortGrid() {
    var rows = $('#gridContainer tr td:first-child');
    var i = 1;
    $.each(rows, function () { $(this).html(ToPersia(i++)); });
}

//ShowMessage
var msgTimeOut;
function ShowMessage(isSuccess, message) {
    var color = isSuccess ? "green" : "red";
    clearTimeout(msgTimeOut);
    $('#tdMsg > span').remove();
    $('#tdMsg').append('<span style=\"color:' + color + '\;font-weight:bold;">' + message + '</span>');
    msgTimeOut = setTimeout(function () { $('#tdMsg > span').remove(); }, 3000);
}

function RefreshGridSize() {
    var top = ($('div.content').offset().top + $('div.content').height() + 1);
    var documentHeight = $(document).height();
    var divPaging = $('div.gridPaging');
    if (divPaging.length > 0) {
        divPaging[0].style.top = top + "px";
        var gridStyle = $('div.gridPaging > div')[0].style;
        gridStyle.height = gridStyle.maxHeight = (documentHeight - top - 50) + "px";
        gridStyle.width = $(document).width(); // - 140;
    } 
}

//Paging
function CreatePagingPanel() {
    RefreshGridSize();
    $(window).resize(RefreshGridSize);

    GotoPage(1);

    var htmlPanel = "<div id=\"pnlPaging\" style=\"display:table;float:left;direction:ltr;padding-left:20px\">";
    htmlPanel += "<div id=\"butPageFirst\" style=\"width: 25px; height: 25px; float: left;display:table-cell;cursor:pointer;\" title=\"اولین\">";
    htmlPanel += "<<";
    htmlPanel += "</div>";
    htmlPanel += "<div id=\"butPagePrevious\" style=\"width: 25px; height: 25px; float: left;display:table-cell;cursor:pointer\" title=\"قبلی\">";
    htmlPanel += "<";
    htmlPanel += "</div>";
    htmlPanel += "<div id=\"txtPageNumber\" style=\"text-align:center; width: 100px; height: 25px; float: left;display:table-cell;\">";
    htmlPanel += "صفحه 1 از 20";
    htmlPanel += "</div>";
    htmlPanel += "<div id=\"butPageNext\" style=\"width: 25px; height: 25px; float: left;display:table-cell;cursor:pointer\" title=\"بعدی\">";
    htmlPanel += ">";
    htmlPanel += "</div>";
    htmlPanel += "<div id=\"butPageLast\" style=\"width: 25px; height: 25px; float: left;display:table-cell;cursor:pointer\" title=\"آخرین\">";
    htmlPanel += ">>";
    htmlPanel += "</div>";
    htmlPanel += "</div>";

    $('.gridPaging > span > div').append(htmlPanel);

    RefreshPagingButtons(1);
}

var totalRows = 0, totalPage = 1;
function RefreshCountOfPage() {
    totalRows = $('#gridContainer table tr:gt(0)').length;
    totalPage = ToInt((totalRows - 1) / pageRows) + 1;
}

var pageRows = 15, currentPage = 1;
function RefreshPagingButtons(page) {
    currentPage = page;
    RefreshCountOfPage();

    $('#butPageFirst').unbind('click');
    $('#butPagePrevious').unbind('click');
    $('#butPageNext').unbind('click');
    $('#butPageLast').unbind('click');

    $('#butPageFirst').bind('click', function () {
        GotoPage(1);
        RefreshPagingButtons(1);
    });

    $('#butPagePrevious').bind('click', function () {
        RefreshCountOfPage();
        var toPage = page > 1 ? page - 1 : 1;
        GotoPage(toPage);
        RefreshPagingButtons(toPage);
    });

    $('#butPageNext').bind('click', function () {
        RefreshCountOfPage();
        var toPage = page < totalPage ? page + 1 : totalPage;
        GotoPage(toPage);
        RefreshPagingButtons(toPage);
    });

    $('#butPageLast').bind('click', function () {
        RefreshCountOfPage();
        GotoPage(totalPage);
        RefreshPagingButtons(totalPage);
    });

    $('#txtPageNumber').html("صفحه " + ToPersia(page) + " از " + ToPersia(totalPage));

}

function GotoPage(pageNumber) {

    $('#gridContainer table tr:gt(0)').hide();
    $('#gridContainer table tr:gt(0)').slice((pageNumber - 1) * pageRows, pageNumber * pageRows).show();

}

function BeginUpdateGridLayout() {
    $('#gridContainer').selectable('destroy');
}

function EndUpdateGridLayout(linkId, attr) {
    var lastSel;
    $('#gridContainer').selectable({ filter: 'tr',
        selected: function (event, ui) {
            if (lastSel == ui.selected) return;
            if (lastSel) $(lastSel).removeClass('ui-selected');
            lastSel = ui.selected;

            if (typeof (linkId) != 'undefined' && typeof (attr) != 'undefined')
                currentId = $("a[id^='" + linkId + "']", ui.selected).attr(attr);
        },
        cancel: 'a'
    });

    RefreshPagingButtons(1);
    SortGrid();
    GotoPage(1);
}

var searchTocken;
function TrySearch(callback) {
    if (isServerProccess == false) {
        clearTimeout(searchTocken);
        searchTocken = setTimeout(callback, 2000);
    }
    else isSearchTry = true;
}

function CheckForTrySearch(callback, callback2) {
    if (isSearchTry == true) {
        isServerProccess = false;
        isSearchTry = false;
        if (callback && $.isFunction(callback)) {
            if (typeof (callback2) != 'undefined' && $.isFunction(callback2)) callback(callback2);
            else callback();
        }
        return true;
    }
    else return false;
}

function StartLoading() {
    isServerProccess = true;
    $('#searchTitle > span').remove();
    $('#searchTitle').append("<span style=\"font-weigth:bold;color:blue\"> لطفا\" صبر کنید </span>");
}

function EndLoading() {
    isServerProccess = false;
    setTimeout(function () { $('#searchTitle > span').remove(); }, 500);
}

function CheckFarsiDate(date) {
    try {
        var splits = date.split("/");

        var year = ToInt(splits[0]);
        var month = ToInt(splits[1]);
        var day = ToInt(splits[2]);

        if (isNaN(year) || isNaN(month) || isNaN(day)) return false;
        if (!(month >= 1 && month <= 12)) return false;
        if (month >= 1 && month <= 6 && !(day >= 1 && day <= 31)) return false;
        if (month >= 7 && month <= 12 && !(day >= 1 && day <= 30)) return false;

        return true;
    }
    catch (ex) { return false; }
}

function CheckTime(date) {
    try {
        var splits = date.split(":");

        var hour = ToInt(splits[0]);
        var minute = ToInt(splits[1]);

        if (isNaN(hour) || isNaN(minute)) return false;
        if (!(hour >= 0 && hour <= 23)) return false;
        if (!(minute >= 0 && minute <= 59)) return false;

        return true;
    } 
    catch (ex) { return false; }
}

function GetTimeString(time) {
    var split = time.split(":");
    var hour = ToInt(split[0]);
    var minute = ToInt(split[1]);

    if (hour == undefined) hour = 0;
    if (minute == undefined) minute = 0;

    return GetTimeStringHM(hour, minute);
}

function GetTimeStringHM(hour, minute) {
    if (hour <= 9) hour = "0" + hour;
    if (minute <= 9) minute = "0" + minute;

    return hour + ":" + minute;
}
