﻿/// <reference path="~/Scripts/jquery-1.4.1.min.js" />

var flg = false, ajaxCount = 0;
var timer = setInterval(function () { $('#lblRequestCount').text(ajaxCount) }, 100);
$(function () {
    $(window).bind('hashchange', function () {
        if (flg == false) {
            var hash = window.location.hash || '#firstpage';
            if (hash.split('.').length == 1)
                PageContent_Load('#content', hash.substring(1, hash.length));
            else
                AjaxLoadPage(hash.substring(1, hash.length), function (page) { $('#content').html(page); }, true);
        }
    });
});

function AjaxMethod(url, data, successAction, WithWaiting, type) {
    if (WithWaiting == null) WithWaiting = true;
    if (type == null) type = "POST";
    Waiting(WithWaiting);
    ajaxCount++;
    $.ajax({
        type: type,
        url: 'default.aspx/' + url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: data,
        success: successAction,
        complete: function () {
            Waiting(false);
            ajaxCount--;
        }
    });
    //    console.clear();
}

function AjaxLoadPage(page, action, WithWaiting) {
    if (WithWaiting == null) WithWaiting = true;
    Waiting(WithWaiting);
    flg = true;
    location.href = '#' + page;
    ajaxCount++;
    $.ajax({
        url: page,
        success: action,
        complete: function () {
            $('#pPage input').addClass('CtrlBorder');
            $('#pPage input[type=radio] ,#pPage input[type=checkbox]').removeClass('CtrlBorder').css('border', '0');
            $('#pPage td[align=]').attr('align', 'right');
            Waiting(false);
            flg = false;
            ajaxCount--;
        }
    });
    $('#content').attr('Page', '');
}

function MsgDialog_Show(text, title) {
    Dialog_Show(text, title, { 'بستن': function () { $(this).dialog('close'); } });
}

function MsgDialogError_Show(text, title) {
    Dialog_Show(text, title, { 'بستن': function () { $(this).dialog('close'); } },null,null,300,250);
}

function Dialog_Show(content, title, button, control, opening, width, height) {
    ///<summary>
    ///     نمایش دیالوگ
    ///</summary>
    ///<param name="content">
    ///     محتوای دیالوگ
    ///</param>
    ///<param name="title">
    ///     عنوان
    ///</param>
    ///<param name="button">
    ///     دکمه های موردنیاز برای دیالوگ
    ///</param>
    ///<param name="control">
    ///     دیالوگ تحت کدام کنترل باز شود
    ///</param>
    if (control == null) control = '#dialog';
    if (button == null) button = { 'بستن': function () { $(this).dialog('close'); } }
    if (opening == null) opening = true;
    if (width == null) width = 300;
    if (height == null) height = 150;
    if (content != null) $(control).html(content);
    $(control).dialog({
        modal: true,
        title: title,
        show: 'fade',
        width: width,
        height: height,
        buttons: button,
        draggable: false,
        resizable: false,
        autoOpen: opening
    });

}

function Waiting(isShow) {
    if (isShow)
        $('#waiting').show();
    else
        $('#waiting').hide();
}

function Login_Check() {
    AjaxMethod('Member_Get', '{Name:-1,Password:-1}', function (ret) {
        Member = ret.d;
        if (Member.ItemID > -1) {
            $('#tdUserInfo').text('کاربرگرامی ' + Member.FirstName + ' ' + Member.LastName + ' خوش آمدید');
            $('#tdConShopping').html('');
            $('#tbLogin').hide();
            $('#tbLogout').show();
        }
        Login_SetClick();
    }, false);
}

function Login_SetClick() {
    $('#txtUserName ,#txtPassword').keypress(function (key) {
        if (key.keyCode == 13) $('#butLogin').click();
    });

    $('#butLogin').unbind('click').button().click(function () {
        AjaxMethod('Member_Get', '{Name:"' + $('#txtUserName').val() + '",Password:"' + $('#txtPassword').val() + '"}', function (ret) {
            Member = ret.d;
            if (Member.ItemID == -1) {
                MsgDialog_Show('نام کاربری و کلمه عبور اشتباه است', 'خطا');
            }
            else {

                if (Member.IsAdmin) {
                    //                    AjaxLoadPage('admin/default.htm', function (page) {
                    //                        $('#pPage').html(page);
                    //                    });
                    location.href = "admin/default.aspx";
                    return;
                }
                if (Member.IsIsfahan) {
                    $('#cmbDeliveryMode option:first').attr('selected', true).change();
                    $('#rRecive ,label[for=rRecive]').show();
                }
                else {
                    $('#cmbDeliveryMode option:last').attr('selected', true).change();
                    $('#rRecive ,label[for=rRecive]').hide();
                }
                $('#tdUserInfo').text('کاربرگرامی ' + Member.FirstName + ' ' + Member.LastName + ' خوش آمدید');
                $('#tdConShopping').html('');
                $('#tbLogin').hide();
                $('#tbLogout').show();
            }
        });
    });

    $('#butLogOut').unbind('click').button().click(function () {
        AjaxMethod('Member_Logout', '', function () {
            if ($('#content').attr('page') == 'salesfactor' || $('[rol=member]').length > 0) {
                $('#butFPage').click();
            }

            if ($('#butShopContinue').length > 0) {
                AjaxLoadPage('member/register.htm', function (html) {
                    $('#tdConShopping').html(html).find('button').remove();
                    $('#butSave ,#butClear').remove();
                });
                Member.IsIsfahan = true;
                $('#rRecive ,label[for=rRecive]').show();
                $('#cmbDeliveryMode option:first').attr('selected', true).change();
            }
            $('#tbLogin').show();
            $('#tbLogout').hide();
            Member.ItemID = -1;
        });
    });

    $('#butDetail').unbind('click').button().click(function () {
        AjaxLoadPage('member/memberinfo.htm', function (page) {
            $('#content').html(page).attr('page', 'memberinfo');
            $('#butInfo').click(function () {
                AjaxLoadPage('member/Register.htm', function (reg) {
                    $('#content').attr('page', 'memberinfo');
                    $('#tdContent').html(reg);
                    $('#txtRegUserName').remove();
                    $('#lblRegUserName').text(Member.UserName);
                    $('#txtFirstName').val(Member.FirstName);
                    $('#txtLastName').val(Member.LastName);
                    $('#txtEmail').val(Member.Email);
                    $('#rIsIsfahan').attr('checked', Member.IsIsfahan);
                    $('#rNoIsfahan').attr('checked', !Member.IsIsfahan);
                    $('#txtAddress').val(Member.Address);
                    $('#txtPostalCode').val(Member.PostalCode);
                    $('#txtTel').val(Member.Tel);
                    $('#txtFax').val(Member.Fax);
                    $('#txtRegMobile').val(Member.Mobile);
                    $('#chkRecieveEmail').attr('checked', Member.RecieveEmail);
                    $('#chkRecieveSMS').attr('checked', Member.RecieveSMS);

                    AjaxMethod('BaseInfo_forSelect_Get', '{State:7}', function (ret) {
                        $('#cmbProvince').html(ret.d).change(function () {
                            AjaxMethod('BaseInfo_forSelect_GetByPID', '{ParentID:' + $('#cmbProvince option:selected').attr('itemid') + '}', function (towns) {
                                $('#cmbCity').html(towns.d);
                            });
                        }).change();
                    }, false);

                    $('#butSave').button({ icons: { secondary: 'ui-icon-disk'} }).click(function () {
                        $('#txtRegPassword ,#txtConfirmPass').removeClass('ui-state-error');
                        Member.FirstName = $('#txtFirstName').val();
                        Member.LastName = $('#txtLastName').val();
                        Member.Email = $('#txtEmail').val();
                        Member.IsIsfahan = $('#rIsIsfahan').attr('checked');
                        Member.Address = $('#txtAddress').val();
                        Member.PostalCode = $('#txtPostalCode').val();
                        Member.Tel = $('#txtTel').val();
                        Member.Fax = $('#txtFax').val();
                        Member.Mobile = $('#txtRegMobile').val();
                        Member.RecieveEmail = $('#chkRecieveEmail').attr('checked');
                        Member.RecieveSMS = $('#chkRecieveSMS').attr('checked');
                        Member.Password = $('#txtRegPassword').val();

                        if ($('#txtRegPassword').val().length > 0 || $('#txtConfirmPass').val().length > 0) {
                            if ($('#txtRegPassword').val().length == 0) {
                                $('#txtRegPassword').addClass('ui-state-error');
                                return;
                            }
                            if ($('#txtConfirmPass').val().length == 0) {
                                $('#txtConfirmPass').addClass('ui-state-error');
                                return;
                            }

                            if ($('#txtRegPassword').val() != $('#txtConfirmPass').val()) {
                                MsgDialog_Show('رمزعبور و تکرار آن باید یکسان باشند', 'خطا');
                                return;
                            }
                        }

                        AjaxMethod('Member_Add', "{Data:'" + $.json.encode(Member) + "'}", function (ret) {
                            var temp = ret.d;
                            if (temp.ItemID != -1) {
                                MsgDialog_Show('اطلاعات ذخیره شد', 'پیام');
                                Member = temp;
                            }
                            else
                                MsgDialog_Show('خطا در ذخیره اطلاعات', 'خطا');
                        });

                    });

                    $('#butClear').button().click(function () {
                        $('#tdContent input').val('');
                    });
                });
            });

            $('#butShopping').click(function () {
                AjaxLoadPage('member/membershopping.htm', function (page) {
                    $('#content').attr('page', 'memberinfo');
                    AjaxMethod('Shopping_GetByMemberID', '', function (ret) {
                        $('#tdContent').html(page);
                        $('#tbMSInfo').html(ret.d).find('tr').hover(function () { $(this).addClass('ui-state-hover'); }, function () { $(this).removeClass('ui-state-hover'); });
                        $('#tbMSInfo img[rel=detail]').css('cursor', 'pointer').click(function () {
                            var ItemID = $(this).attr('ItemID');
                            AjaxLoadPage('member/SalesFactor.htm', function (page) {
                                $('#dialog').html(page);
                                $('#tbInfo tr').eq(1).remove();
                                $('#tbInfo tr').eq(1).remove();
                                $('#tbInfo tr').eq(1).remove();
                                $('#tbInfo tr').eq(1).remove();
                                $('#dialog button').remove();
                                AjaxMethod('Shoppings_Get', '{ShoppingID:"' + ItemID + '"}', function (ret) {
                                    $('#tbFactorInfo').html(ret.d[0]);
                                    $('#lblTotalPrice').text(ret.d[1]);
                                    $('#lblSendCost').text(ret.d[2]);
                                    $('#lblTotalFinalPrice').text(ret.d[3]);
                                    $('#lblDate').text(ret.d[4]);
                                    $('#lblRefCode').text(ret.d[5]);
                                    $('#lblDiscount').text(ret.d[6] + "%");
                                    Dialog_Show(null, 'جزئیات فاکتور', { 'بستن': function () { $(this).dialog('close'); } }, null, true, 500, 400);
                                });
                            });
                        });

                        $('#tbMSInfo img[rel=cancel]').css('cursor', 'pointer').click(function () {
                            var button, thisObject = $(this);
                            $('#txtCancel').val(thisObject.attr('des'));
                            if (thisObject.attr('ItemID') != undefined) {
                                $('#txtCancel').removeAttr('readonly');
                                button = { 'تایید': function () {
                                    if ($('#txtCancel').val().length == 0) {
                                        $('#txtCancel').addClass('ui-state-error');
                                        return;
                                    }
                                    AjaxMethod('Shopping_Cancel', '{ItemID:' + thisObject.attr('ItemID') + ',Description:"' + $('#txtCancel').val() + '"}', function (ret) {
                                        if (ret.d == '1') {
                                            thisObject.attr('src', '../pictures/check.png').removeAttr('ItemID').attr('des', $('#txtCancel').val());
                                            $('#pCancel').dialog('close');
                                        }
                                    });
                                }, 'انصراف': function () {
                                    $(this).dialog('close');
                                }
                                }
                            }
                            else {
                                $('#txtCancel').attr('readonly', true);
                            }
                            Dialog_Show(null, 'لغو درخواست', button, '#pCancel', true, 300, 200);
                        });
                    });
                });
            });
        });
    });
}

function digit_grouping(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function postRefId(refIdValue, address) {
    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("action", address);
    form.setAttribute("target", "");
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("name", "RefId");
    hiddenField.setAttribute("value", refIdValue);
    form.appendChild(hiddenField);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function ValidateEMail(email) {
    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    return filter.test(email);
}

var BaseInfo = { ItemID: -1, Name: '', State: -1, Value: '', ParentID: -1 }
var Bank = { RefId: -1, ResCode: '', SaleOrderId: '', SaleReferenceId: '', ResCodeStr: '' }
var Settings = { ConnStr: '', SendCost: 0, BannerPath: '' }
var BankMellat = { TerminalID: '', UserName: '', Password: '' }
var Member = { LastName: '', FirstName: '', Email: '', IsIsfahan: true, CityName: '', Address: '', PostalCode: '', Tel: '', Mobile: '', Fax: '', UserName: '', Password: '', ItemID: -1, IsAdmin: false, RecieveEmail: false };

