﻿var collapsed = 0;
var infosTitle = "ارائه شماره رمز از طریق: ";
var opList;
var opIndex = 0;
var closeOff;
var closeOn;

$(document).ready(function () {
    var pos;
    $(window).resize(function () {
        $('.main1024').css('height', Math.max(610, $(window).height()) + 'px');
        $('#mainFrame').css("top", Math.max(0, $(window).height() - 569) / 2 + 'px');
        pos = $('#mainFrame').position();

        $('.festivalWrapper').css('left', pos.left + 400 + 'px');
    });
    $('.main1024').css('height', Math.max(610, $(window).height()) + 'px');
    $('#mainFrame').css("top", Math.max(0, $(window).height() - 569) / 2 + 'px');
    pos = $('#mainFrame').position();
    $('.festivalWrapper').css('left', pos.left + 400 + 'px');
    closeOff = new Image();
    closeOn = new Image();
    closeOff.src = 'image/close-off.gif';
    closeOn.src = 'image/close-on.gif';
    $("#buy").attr('disabled', 'disabled');
    $("#buy").addClass('PointerCursor');
    $("#buy .buttonImg").attr('src', 'Image/buyOff.png');
    $.get('asp/SwitchStatusHandler.ashx', CheckStatus);
    $.get("asp/ChargeHandler.ashx?id=65lmk4586opluh524896", catalog);
    $('.festivalClose').click(function () {
        $('.festivalPanel').slideUp('slow');

        $('.festivalClose').removeClass('on');
        $('.festivalClose').addClass('off');
        $('.festivalClosedText').fadeIn('slow');
        $('.fesrivalOver').hide();
    });

    $('.festivaltab').mousemove(function () {

        if ($('.festivalClose').hasClass('off') && !$('.festivalPanel').is(':visible') && $('.festivalWrapper').height() > 35) {

            $('.festivalClose').removeClass('off');
            $('.festivalClose').addClass('on');

            $('.festivalPanel').slideDown('slow');
            $('.festivalPanel').removeClass('off');

            $('.festivalClosedText').fadeOut('fast');
        }
    });
});

function CheckSwitch(response) {
    if (response == 'ON') {
        $('.dlgConstruction,.dlgMask').fadeOut('slow', function () {
            $('.dlg').remove();
            $('.dlgMask').remove();
        });
    }

}
function CheckStatus(response) {

    if (response == 'OFF') {
        SHshowDlgUnderConstruction("<p style='font-size:22px;color:#aaaaaa; text-align:center;'>سایت شارژ گیت در حال به روز رسانی می باشد و این فرآیند چند ساعت طول خواهد کشید</p>");
    }

}
function catalog(xml, status) {

    opList = new Array();
    $(xml).find("op").each(
        function (i, op) {
            opList[i] = new Operator($(op).attr("id"), $(op).attr("name"), $(op).attr("country"), $(op).attr("pname"));

            var style = '';
            $(op).find("co").each(
                function (j, co) {
                    style += Style(opList[i].name, $(co).attr('type'),
                        $(co).attr('fr'), $(co).attr('to'),
                        $(co).attr('so'), $(co).attr('fo'), $(co).attr('bo'));
                }
            );
            $('head').append(
               "<style type='text/css'>" + style + '</style>'
            );
            $(op).find("ct").each(
                function (j, ct) {
                    cType = new ChargeType($(ct).attr("id"), $(ct).attr("caption"),
                     $(ct).attr("tCap"), $(ct).attr("price"), $(ct).attr("count"), opList[i], $(ct).attr("place"), $(ct).attr("isTopSeller"));
                    opList[i].chargeType[j] = cType;
                }
            );
        }
    );
    showLogos();

    loadCookie();

    if (!($.cookie('remember'))) {

        ShowTopSellers();

    }

}
function ShowTopSellers() {

    $(opList).each(
        function (i, op) {

            $(op.chargeType).each(
        function (j, ct) {
            var cls = op.name;
            if (ct.count > 0)
                cls += 'active';
            else
                cls += 'disabled';

            if (ct.isTopSeller == 'yes') {
                $(".topsellersTable").append(
                                              $("<tr></tr>").append(
                                                                 $('<td></td>').html(
                                                                                 $('<button></button>').addClass('topsellersButton').addClass(cls).data('id', ct.id).text(ct.tCaption)
                                                                                 .click(ExpressBuy)
                                                                                 .mouseover(function myfunctionmouseover() {
                                                                                     $(this).addClass(cls);
                                                                                     $(this).addClass('topsellersButton');
                                                                                     if (!($(this).hasClass(op.name + 'disabled'))) {
                                                                                         $(this).addClass('ButtonMouseOver');
                                                                                     }
                                                                                     else { $(this).attr('disabled', 'disabled'); }


                                                                                 })
                                                                                 .mouseout(function myfunctionmouseout() {

                                                                                     $(this).attr('class', 'NormalButton topsellersButton');
                                                                                     $(this).addClass(cls);


                                                                                 })
                                                                                 .mouseup(function myfunctionmouseup() {
                                                                                     $(this).addClass(cls);
                                                                                     $(this).addClass('topsellersButton');
                                                                                     if (!($(this).hasClass(op.name + 'disabled'))) {
                                                                                         $(this).addClass('ButtonMouseUp');
                                                                                     }
                                                                                     else { $(this).attr('disabled', 'disabled'); }

                                                                                 })
                                                                                 .mousedown(function myfunctionmousedown() {
                                                                                     $(this).addClass(cls);
                                                                                     $(this).addClass('topsellersButton');
                                                                                     if (!($(this).hasClass(op.name + 'disabled'))) {
                                                                                         $(this).addClass('ButtonMouseDown');
                                                                                     }
                                                                                     else { $(this).attr('disabled', 'disabled'); }

                                                                                 })

                                                                               )
                                                               )
                                           );
            }
        });
        });

    $('#topSellers').delay(2000).slideDown('fast');
}
function ExpressBuy() {

    var charges = new Array();

    charges.push($(this).data('id'));
    charges.push(1);
    $.get('asp/BuyHandler.ashx', { 'charges': charges.toString(), 'email': '', 'sms': '' },
            function (response) {
                if (response.substr(0, 3) == 'au=')
                    window.location = "https://www.pec24.com/pecpaymentgateway/default.aspx?" + response.toString();
                else {
                    alert(response);
                    window.location.reload();
                }
            }
        );
    SHshowDlg('در حال اتصال به سرور بانک...');
}
function Style(name, type, from, to, solid, fore, border) {
    var selector;
    selector = '.' + name + type;

    var style = selector + '{';
    if (type == 'disabled' && type == 'tnormal')
        style += 'cursor:default;';
    style += 'color:' + fore + ';';
    style += 'border:solid 1px ' + border + ';';
    style += 'background-color:' + solid + ';';
    style += '}';
    return style;
}
function showLogos() {
    $(opList).each(
        function (i, op) {
            $("#opTable tr").append(
                $('<td>').attr('valign', 'bottom').html(
                   $('<div>').addClass("opwrapper").append(
                    $('<img>').addClass('carousel').addClass('carouselfirst')
                    .attr({ 'alt': op.name, 'src': 'Image/logo/' + op.id + '.jpg' })

                    .attr('title', op.pname)
                    .data('id', i)
                    .click(showCharges)
                    .mouseover(overOperator)
                    .mouseout(outOperator)
                    )
                )
            );
        }
    );
}
function clearTable() {
    for (k = 0; k < 6; k++) {
        var id = "#td" + k;
        $(id).html("");
        $(id).css('background-image', '');
        $(id).removeData();
    }
}
function overOperator(sender, index) {

    if (!$(this).hasClass('carouselSelect') & !$(this).hasClass('carouselfirst')) {

        $(this).animate({ opacity: 0.5 }, 200);

    }
    if ($(this).hasClass('carouselfirst')) {

        $(this).animate({ opacity: 1 }, 200);

    }
}
function outOperator() {

    if (!$(this).hasClass('carouselSelect') & !$(this).hasClass('carouselfirst')) {

        $(this).animate({ opacity: 0.2 }, 200);
    }
    if ($(this).hasClass('carouselfirst')) {

        $(this).animate({ opacity: 0.6 }, 200);
    }
}
function showCharges() {
    $('#chargesMask').hide();

    $('.carousel').removeClass('carouselSelect');
    $('.carousel').removeClass('carouselfirst');
    $(this).addClass('carouselSelect');

    $(this).animate({ opacity: 1 }, 200);
    $('.carousel').each(

        function (i, c) {

            if (!$(c).hasClass('carouselSelect')) {

                $(c).animate({ opacity: 0.2 }, 200);
            }
        });
    chgHtml = "";
    row = "";
    var i = $(this).data('id');
    var country = (opList[i].country);

    clearTable();
    var k = 3;

    if ($(opList[i].chargeType).length == 0) {
        $('#charges').append($('<p class="pcomming">').html('<span class="commingsoonupperline">  ارائه شارژ سیم کارت های ' + (opList[i].pname) + '</span> </br>به زودی در شارژگیت ').addClass('commingsoon'));
    }
    else {
        $('.pcomming').hide();
    }
    $(opList[i].chargeType).each(
        function (j, ct) {


            var id;
            if (ct.place == 'R') {
                id = "#td" + j;

            }
            else {
                id = "#td" + k;
                k++;

            }
            var cls = opList[i].name;
            if (ct.count > 0) {
                cls += 'normal';
                var button = $('<button>').addClass('cbutton').addClass(cls).attr('disabled', '').css('cursor', 'pointer')
                                .html(ct.caption)
                                .data('ct', ct)
                                .click(addItem)
                                .mousedown(mousedown)
                                .mouseup(mouseup)
                                .mouseenter(mouseenter)
                                .mouseleave(mouseleave)
                                .mouseover(mouseover);

                $(id).append(button);
                if ((country != 'Iran')) {

                    button.attr('title', ct.price + ' ریال ');
                }
            }
            else {
                cls += 'disabled';
                var button = $('<button>').addClass('cbutton').addClass(cls).attr('disabled', 'disabled').css('cursor', 'default')
            .html(ct.caption)
            .data('ct', ct)
            .click(addItem)
            .mousedown(mousedown)
            .mouseup(mouseup)
            .mouseenter(mouseenter)
            .mouseleave(mouseleave)
            .mouseover(mouseover);
                $(id).append(button);
            }
        }
    );
}
function mousedown() {
    $('#BasketMask').hide();
    $('#ResultMask').hide();
    //$('#topSellers').hide();
    var ct = $(this).data('ct');
    var cls = 'cbutton ' + ct.operator.name + 'active';
    if (!$(this).hasClass(ct.operator.name + 'disabled'))
        $(this).attr('class', cls);
}
function mouseup() {
    var ct = $(this).data('ct');
    var cls = 'cbutton ' + ct.operator.name + 'normal';
    if (!$(this).hasClass(ct.operator.name + 'disabled')) {
        $(this).attr('class', cls);
        $(this).addClass('cbuttonhover');
    }
}
function mouseover() {
    var ct = $(this).data('ct');
    var cls = 'cbutton ' + ct.operator.name + 'hover';
    if (!$(this).hasClass(ct.operator.name + 'disabled')) {
        $(this).attr('class', cls);
        $(this).addClass('cbuttonhover');
    }

}
function mouseenter() {
    var ct = $(this).data('ct');
    var cls = 'cbutton ' + ct.operator.name + 'hover';
    if (!$(this).hasClass(ct.operator.name + 'disabled'))
        $(this).attr('class', cls);
}
function mouseleave() {
    var ct = $(this).data('ct');
    var cls = 'cbutton ' + ct.operator.name + 'normal';
    if (!$(this).hasClass(ct.operator.name + 'disabled'))
        $(this).attr('class', cls);
}
var total = 0;
function addItem() {
    ct = $(this).data('ct');
    ct.chargeButton = this;
    if (total < 2000000) {
        add2Basket(ct);
        validateBasketValue();
    }

}
function enableBuyButton() {
    $("#buy").attr('disabled', '');
    $("#buy").removeClass('PointerCursor');
    $("#buy .buttonImg").attr('src', 'Image/buy.png');
}
function disableBuyButton() {


    $("#buy").attr('disabled', 'disabled');
    $("#buy").addClass('PointerCursor');
    $("#buy .buttonImg").attr('src', 'Image/buyOff.png');
}
function HideTopSellers() {
    $('#topSellers').slideUp('fast');
}
function add2Basket(ct) {


    enableBuyButton();
    HideTopSellers();

    if ($('#basket .btdc').length >= 5) {
        SHshowDlg('تعداد کارت های سبد حداکثر 5 عدد می تواند باشد.', 'تصحیح');
        return;
    }

    if (ct.count == 1) {

        $(ct.chargeButton).attr('class', 'cbutton ' + ct.operator.name + 'disabled').css('cursor', 'default').attr('disabled', 'disabled');
    }

    if (ct.count == 0)
        return;
    ct.count--;
    changeTotal(ct.price);
    $("#basket").append(
                            $("<tr>").append(
                                              $("<td>").append(
                                                                $('<div>').addClass('btdc').addClass(ct.operator.name + 'tnormal').append($('<span>').text(ct.tCaption))
                                                                .append(
                                                                                                                $("<img>").attr('src', closeOff.src)
                                                                                                                .attr('title', 'حذف از سبد خرید')
                                                                                                                .data('ct', ct)
                                                                                                                .click(removeItem)
                                                                                                                .mouseenter(function () { $(this).attr('src', closeOn.src); })
                                                                                                                .mouseleave(function () { $(this).attr('src', closeOff.src); })
                                                                                                                .addClass('btdb')

                                                                      )
                                                              )
                                                              )
                       );

}
function removeItem() {
    var ct = $(this).data('ct');

    ct.count++;
    if (ct.count == 1)
        $('table#ChargeTable button').each(
            function (index, button) {
                var ctButton = $(button).data('ct');
                if (ctButton.id == ct.id)
                    $(button).attr('class', 'cbutton ' + ct.operator.name + 'normal').css('cursor', 'pointer').attr('disabled', ''); ;
            }
        );

    changeTotal(-ct.price);
    $(this).parent().parent().parent().remove();

    if ($('#basket tr').length == 0) {
        disableBuyButton();
    }

}

function changeTotal(dif) {
    total += dif;
    $("#totalLabel").text(addCommas(total));
    if (total > 2000000) {

        $('#totalLabel').css('color', '#ff0000');
        $('#rial').css('color', '#ff0000');
    }
    else {
        $('#totalLabel').css('color', '#26a0ff');
        $('#rial').css('color', '#26a0ff');

    }
}
function addCommas(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 Operator(id, name, country, pname) {
    this.country = country;
    this.id = id;
    this.name = name;
    this.pname = pname;
    this.chargeType = new Array();
}
function ChargeType(id, caption, tCaption, price, count, operator, place, isTopSeller) {

    this.id = parseInt(id);
    this.caption = caption;
    this.tCaption = tCaption;
    this.price = parseInt(price);
    this.count = count;
    this.operator = operator;
    this.place = place;
    this.isTopSeller = isTopSeller
}
function validate() {

    if (!$('#basket tr').length) {
        SHshowDlg("سبد خرید خالی است.", 'تصحیح');
        return false;
    }

    var email = /\w.+@\w.+\.\w+/;
    var sms = /09\d{9}/;
    if ($('#email').attr('value')) {
        if (!email.test($('#email').attr('value'))) {
            var emailMsg = $('<span>').css('font-size', 'x-large')
            .text(' پست الکترونیکی معتبر نمی باشد.')

            SHshowDlg(emailMsg.html(), 'تصحیح');
            return false;
        }
    }
    if ($('#sms').attr('value') != '09' & $('#sms').attr('value') != '') {
        if (!sms.test($('#sms').attr('value'))) {
            var smsMsg = $('<span>').css('font-size', 'x-large')
            .text('شماره تلفن همراه معتبر نمی باشد.')
            SHshowDlg(smsMsg.html(), 'تصحیح');
            return false;
        }
    }

    return true;
}
function findCharge(id) {
    var item = null;
    $(opList).each(
        function (i, op) {
            $(op.chargeType).each(
                function (j, ct) {
                    if (id == ct.id)
                        item = ct;
                }
            );
        }
    );
    return item;
}
function loadCookie() {

    if ($.cookie('remember')) {
        $('#rememberCheck').attr('checked', 'checked');
        $('#sms').attr('value', $.cookie('sms'));
        $('#email').attr('value', $.cookie('email'));
        var basket = $.cookie('basket');
        if (basket != null) {
            $($.parseJSON(basket)).each(
                function (i, id) {
                    var ct = findCharge(id);
                    if (ct != null && ct.count > 0) {
                        add2Basket(ct);
                    }
                }
            );
            $("#buy").attr('disabled', '');
            $("#buy").removeClass('PointerCursor');
            $("#buy .buttonImg").attr('src', 'Image/buy.png');
        }
        $('#BasketMask').hide();
        $('#ResultMask').hide();
    }
    else {
        $('#sms').attr('value', '09');
        $('#email').attr('value', '');
    }
}

function save2Cookie(exp) {

    if (exp == null) exp = 10 * 366;
    $.cookie('remember', $('#rememberCheck').attr('checked'), { expires: exp });
    $.cookie('sms', $('#sms').attr('value'), { expires: exp });
    $.cookie('email', $('#email').attr('value'), { expires: exp });
    var basket = '[';
    $('#basket .btdb').each(
        function (i, close) {
            basket += $(close).data('ct').id + ',';
        }
    );
    basket = basket.substr(0, basket.length - 1) + ']';
    $.cookie('basket', basket, { expires: exp });
}

function deleteCookie() {
    save2Cookie(-1);

}
function basketItems() {

    var basket = new Array();

    $('#basket .btdb').each(

        function (i, close) {
            var ct = $(close).data('ct');
            var id = ct.id;
            basket[id] = basket[id] ? basket[id] + 1 : 1;
        }
    );
    var charges = new Array();
    for (var id in basket) {
        charges.push(id);
        charges.push(basket[id]);
    }
    return charges;
}

function validateBasketValue() {
    var total;
    total = $('#totalLabel').text();

    total = total.toString();
    total = total.replace(/,/g, '');
    if (parseFloat(total) > 2000000) {
        var message = "خرید شما نیاز به تأیید تلفنی یا حضوری دارد، لطفا" + " " + "<a href='contact.html' style='font-weight:bold;'> با ما تماس بگیرید</a>";
        SHshowDlg(message, 'تصحیح');
        return false;
    }
    return true;
}
function buy() {
    if (validateBasketValue()) {

        if (validate()) {
            if ($('#rememberCheck').attr('checked')) {
                save2Cookie();
            }
            else {

                deleteCookie();
            }
            var charges = basketItems();

            $.get('asp/BuyHandler.ashx', { 'charges': charges.toString(), 'email': $('#email').attr('value'), 'sms': $('#sms').attr('value') },
            function (response) {
                if (response.substr(0, 3) == 'au=')
                    window.location = "https://www.pec24.com/pecpaymentgateway/default.aspx?" + response.toString();
                else {
                    alert(response);
                    window.location.reload();
                }
            }
        );
            SHshowDlg('در حال اتصال به سرور بانک...');
        }
    }
}

