 var currentState = 'start';
 var lodingImg = '/templates/img/ajax-loader.gif';

 function pageRefresh() {
     if (document.location.hash != currentState) {

         if(document.location.hash == "#undefined" || document.location.hash == "" || document.location.hash == "#start") {
             //loadContent($("a[href^='#main']").attr('data-post'), $("a[href^='#main']").attr('href'));
         }else if(currentState == "start" && (document.location.hash == "#undefined" || document.location.hash == "")){
             //window.history.pushState(null, null, "/cabinet");
             //loadContent($("a[href^='#main']").attr('data-post'), $("a[href^='#main']").attr('href'));
         }else
             loadContent($("a[href^='"+document.location.hash+"']").attr('data-post'),$("a[href^='"+document.location.hash+"']").attr('href'));
     }
 }


 Number.prototype.convert = String.prototype.convert = function (outRadix, inRadix) {

     var val = this,
         outRadix = parseInt(outRadix),
         inRadix = parseInt(inRadix || 10),
         retVal;

     if (typeof val == 'string') {
         val = val.replace(/(^ *| *$)/g, '');
     }

     function dec2x(val) {
         var val = (typeof val != 'number') ? parseInt(val) : val,
             retVal = parseInt(val).toString(outRadix);

         return retVal;
     }

     function x2dec(val) {
         var val = String(val),
             retVal = parseInt(val, inRadix);

         return retVal;
     }

     if (inRadix == 10) { //10->x
         retVal = dec2x(val);
         if (outRadix == 16) {
             retVal = retVal.toUpperCase();
         }
     } else if (outRadix == 10) { //x->10
         retVal = x2dec(val);
     } else { //x->10->x
         retVal = x2dec(val);
         retVal = dec2x(retVal);
     }

     return (retVal == 'NaN' || retVal === false) ? false : retVal;
 };

 var colorNumber = function (color) {
     color = parseInt(color, 16);
     return (color & 0xFF) << 16 | (color & 0xFF00) | (color >> 16) & 0xFF;
 };
 $('body').on('click', '.title', function (e) {
     $(this).after('<div class="change-form"><input class="form-control" type="text" value="'+$(this).html()+'" class="change-name" maxlength="12"><div class="actions-btns"><div class="change-apply btn btn-sm btn-danger">Ок</div><div class="change-cancel btn btn-sm btn-default">Отменить</div></div></div>');
     $(this).hide();
 });


 $('body').on('click', '.key-hwid', function (e) {
     $(this).after('<div class="change-form"><input name="keyHWID" class="form-control" type="text" placeholder="Ввод Key" value="" class="change-name" ><div class="actions-btns"> <div class=" btn btn-sm  btn-primary submit-btn">Send</div> <div class="change-cancel btn btn-sm btn-default">Отменить</div></div></div>');
     $(this).hide();
 });

 $('body').on('click', '.refresh-tiket', function (e) {
     table_tiket.ajax.reload();
 });

 $('body').on('click','.change-apply',function(e) {
     $('.title').html($('.change-name').val()).show();
     $('.change-form').remove();
 });

 $('body').on('click','.change-cancel',function(e) {
     $('.title').show();
     $('.key').show();
     $('.change-form').remove();
 });

 $('body').on('click', '[teleport]', function () {
     arr = $(this).attr('teleport').split('::');
     $.ajax({
         type: 'POST',
         data: "moduleID=" + arr[1] + "&char_id="+arr[0],
         url: '/',

         success: function (data) {
             if(data == 'exit'){

                 clearInterval(1);
                 clearInterval(2);
                 setTimeout("document.location.href='/'", 1);
                 //window.history.pushState(null, null, "/login");

             }else if(data == 'block') {
                 $(".close").click();
                 $("#protection").click();
             }else if(data == 'banned') {
                 $(".close").click();
                 $("#banned").click();
             }else {
                 var object = jQuery.parseJSON(data);
                 if (object.code == 0) {
                     $.notij(object.message, {'type': 'info'});

                 } else
                     $.notij(object.message, {'type': 'error'});
             }
         }
     });
 });



 $('body').on('click', '.editor-btn', function () {
     $('.section_view').addClass( 'widget-container' );
     $('.widget header h4').append( '<i class=\'fa fa-arrows\' style=\"float: right;padding-right: 7px;\"></i>  &nbsp;' );
     $('.widget header h4').append( '<i class=\'fa fa-check-square-o editor-ok\' style=\"float: right;;padding-right: 7px\"></i> &nbsp;' );


     $('.widget-container').sortable({
         connectWith: '.widget-container',
         iframeFix: false,
         items: '.widget',
         opacity: 0.8,
         helper: 'original',
         revert: true,
         forceHelperSize: true,
         placeholder: 'widget widget-placeholder',
         forcePlaceholderSize: true,
         tolerance: 'pointer'
         //handle: ".fa-arrows",
     });
 });

 $('body').on('click','.editor-ok',function() {
     //$('.widget-container').sortable( "destroy" );
 });


 $(function () {

     var $nickname = $('#align').find('.nickname'),
         $hex = $(document).find('#hex'),
         $r = $('#r'),
         $g = $('#g'),
         $b = $('#b'),
         $access = $('#access'),
         $fulltext = $('#fulltext'),
         $link = $('#link'),
         $colors = $('#colors').children('i'),
         valid_hash = window.location.hash !== '' && window.location.hash.search(/\w{6}\|\w{1,16}/) > 0,
         hash = valid_hash ? window.location.hash.split('|') : false,
         nickname = valid_hash ? hash[1] : 'Name';

     $fulltext.add($link).add($hex).add($r).add($g).add($b).add($access).on('mouseover click', function () {
         $(this).focus().select();
     });



     var clbk = function (t) {
         var hex = $(t).attr('style').match(/#\w{6}/) + '',
             r = hex.substr(1, 2).convert(10, 16),
             g = hex.substr(3, 2).convert(10, 16),
             b = hex.substr(5, 2).convert(10, 16),
             access = colorNumber(hex.substr(1, 6)),
             $hex = $('#hex'),
             $access = $('#access');
             $('#align').find('.nickname').css('color', hex),
             $('#align').find('.title').css('color', hex);

         $('#color').val(access);

         $hex.val(hex);
         $r.val(r);
         $g.val(g);
         $b.val(b);
         $access.val(access);
     };

     $(document).on('change', '#char_id', function () {

         var $char = $(this).find('option:selected'),
             $align = $('#align');
         if ($char.text() !== "Выбор персонажа") {
             $align.find('.nickname').css('color', $char.attr('cname')).html($char.text());
             $align.find('.title').css('color', $char.attr('ctitle')).html($char.attr('title'));
             //$('#preview').css("background-image", "url(/templates/img/" + $char.attr('img') + ".png)");
         }
         else {
             $align.find('.nickname').css('color', '#ffffff').html('');
             $align.find('.title').css('color', '#BBDDF5').html('');
             //$('#preview').css("background-image", "url(/templates/img/all.png)");
         }
     });


     $(document).on('click', "#colors i", function () {
         clbk(this);
         $('#colors').find('i').removeClass('selected');
         $(this).addClass('selected');
     }).on('mouseout', "#colors i", function () {
         var $selected = $('#colors').find('i.selected');
         if ($selected.length) {
             clbk($selected);
         }
     });

 });




function balanceRefresh() {
    $.ajax({
        type: 'POST',
        data: 'refresh=1',
        url: '/',
        success: function (data) {
            if(data == 'exit'){

                clearInterval(1);
                clearInterval(2);
                setTimeout("document.location.href='/'", 1);
                //window.history.pushState(null, null, "/login");

            }else if(data == 'block') {
                $(".close").click();
                $("#protection").click();
            }else if(data == 'banned') {
                $(".close").click();
                $("#banned").click();
            }else {
                arr = data.split('::');
                setTimeout(function () {
                    $('#balance').html(arr[0]);
                    $('#vote').html(arr[1]);
                    $('#referal').html(arr[2]);
                    $('#auction').html(arr[3]);

                }, 200);
            }
        }
    });
}


 function loadContent(data) {

     $.ajax({
         url: data,
         beforeSend: function () {
             $('.ajaxContent').fadeOut(200);
             setTimeout(function () {$('.loader-wrap').fadeIn(200);}, 200);

         }, success: function (data) {

                 setTimeout(function () {$('.loader-wrap').fadeOut(0);}, 200);

                 setTimeout(function () {

                     $('.ajaxContent').html(data);

                     $('.ajaxContent').fadeIn(200);

                     //$('.preLoader').fadeOut(250);
                 }, 200);}

         });
 }
/*function loadContent(datepost){
        console.log(datepost);
    $.ajax({
        url: datepost,
    }).done(function( html ) {
        $(".ajaxContent").html(html);
    });
/!*    $.ajax({
        url: "http://fiddle.jshell.net/favicon.png",

    })
        .done(function( data ) {
            $('.ajaxContent').html(data);
        });*!/
}*/

$(document).ready(function(){
    pageRefresh();
/*
    $('body').on('click', '.panel a', function () {
        console.log($(this).data-post);
        return false;
    });
*/


    function buildURL(anchor) {
        return document.location.toString().substr(0, document.location.toString().indexOf('#')) +
            anchor.substr(1);
    }



    var client1 = new ZeroClipboard($("#copy-button"), {
        moviePath: "/templates/js/ZeroClipboard.swf"
    });
    client1.on("load", function(client1) {
        client1.on("complete", function(client1, args) {
            //$('#copy-button').hide();
            $(this).css('background','black');


        });
    });

 /*   $('body').on('click', '.submit-btn', function () {
        sendForm($(this));
        return false;
    });
*/
    //lang
    $('body').on('click', '[lang]', function () {
        $.cookie('lang', $(this).attr('lang'), {
            expires: 5,
            path: '/'

        });
        location.reload();
    });

    $('body').on('click', '[data-post]', function () {
        $('#side-nav li').removeClass('active').addClass('panel');
        loadContent($(this).attr('data-post'));
        $(this).closest("li").removeClass('panel').addClass('active');
    });

    $('body').on('click', '[data-clan]', function () {
        arr = $(this).attr('data-clan').split('::');

        $.ajax({
            url: "/cabinet/clan",
            data: "plagin=" + arr[1] + "&clan="+arr[0],
            type: "POST",
            cache: false,
            beforeSend: function () {
                $('.clanShow').html("<img scr='"+lodingImg+"'/>");

            },
            success: function (data) {
                $('.clanShow').html(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log("Result : " + xhr.responseText);
            }
        });

    });
    $('body').on('click', '[data-char]', function () {
        char = $(this).attr('data-char');

        $.ajax({
            url: "/cabinet/char",
            data: "char="+char,
            type: "POST",
            cache: false,
            beforeSend: function () {
                $('.charShow').html("<img scr='"+lodingImg+"'/>");

            },
            success: function (data) {
                $('.charShow').html(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log("Result : " + xhr.responseText);
            }
        });

    });


  

  
    $(document).on('change', '#balance_coin', function () {
        var balance = $('#balance_coin').val();
        var price = $('#price').val();
        var discount = $('#discount').val();
        price = price - (price * discount);
        var coin_balance_v = Math.floor(balance / price);
        $('#coin_balance').val(coin_balance_v);
    });

    $(document).on('change', ' #coin_balance', function () {
        var coin_balance = $('#coin_balance').val();
        var price = $('#price').val();
        var discount = $('#discount').val();
        price = price - (price * discount);
        var balance_v = Math.floor(coin_balance * price);
        $('#balance_coin').val(balance_v);


    });
	


    $('body').on('click', '.loud-inv', function (e) {
        $.ajax({
            url: "/",
            data: 'plagin=inventoryChar',
            type: "POST",
            cache: false,
            dataType: 'json',
            beforeSend: function () {
                $(this).attr("disabled","disabled");
                $(this).html("<img scr='"+lodingImg+"'/>");
            },success: function (object) {
                $('.loud-inv').hide();
                $('.table-inv').hide();
                jQuery.each(object, function(i, value) {
                    jQuery.each(value, function (d, val ){
                        if(d != 0) {

                            var enchant = val.item_enchant > 0 ? '<span style=\'color: #c3b488\'>+' + val.item_enchant + '</span> ' : '';
                            var add = val.add != null ? '<span style=\'color: yellow\'>' + val.add + '</span>' : '';
                            var count = val.item_count > 1 ? ' x' + val.item_count + ' ' : '';
                            var augmentation = val.augmentation != null ? '<br>' + val.augmentation : '';

                            var on = false;
                            on = $.map(value[0], function (item, c) {
                                if (item == val.uid) {
                                    $("#" + c + "_" + i).attr("src", '/templates/Lineage/items/' + val.icon + '.png')
                                        .attr("data-placement", 'bottom')
                                        .attr("data-html", 'true')
                                        .attr("data-original-title", enchant + val.name + ' ' + add + ' ' + count + augmentation)
                                        .attr("class", "item-inv");
                                    return true;
                                }

                            })[0];
                            if(!on) {

                                $("#inv_" + i).append(
                                    '<div class="item-inv" data-placement="bottom" data-html="true" data-original-title="' + enchant + val.name + ' ' + add + ' ' + count +
                                    augmentation + '">' +
                                    '<img src="/templates/Lineage/items/' + val.icon + '.png">' +
                                    '</div>'
                                );
                            }
                        }
                    });
                });
                $(".item-inv").tooltip();

            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log("Result : " + xhr.responseText);
            }
        });

    });

    $('body').on('click', '[auc-char]', function () {
        $.ajax({
            type: 'POST',
            data: $(this).attr('auc-char'),
            url: '/',
            success: function (data) {
                if(data == 'exit'){

                    clearInterval(1);
                    clearInterval(2);
                    setTimeout("document.location.href='/'", 1);
                    //window.history.pushState(null, null, "/login");

                }else if(data == 'block') {
                    $(".close").click();
                    $("#protection").click();
                }else if(data == 'banned') {
                    $(".close").click();
                    $("#banned").click();
                    el.removeAttr("disabled");
                }else {
                    setTimeout(function () {

                        $('.auc-char-content').html(data);
                        $(".item-inv").tooltip();
                    }, 200);
                }
            }
        });
    });

});

 function BuyGoods() {
     if ($('#char_id').val()=='Selection of character' || $('#char_id').val()=='You have no characters' || $('#char_id').val()=='У вас нет персонажей' || $('#char_id').val()=='У вас нет персонажей'){
         $.notij('Select character!' ,{'type':'error'});
     } else {
         var count=0;
         var countGoods = $('input[type="checkbox"]:checked').length;

         $('.btn').hide();
         //$('#shop_msg_load').fadeIn(500);
         //$('.message').html('Data processing <img src="'+TPL+'/images/ajax-loader.gif" alt="">').show().css('color', '#ee4646');


         $('input[type="checkbox"]').each(function(i, element){
             if($(this).is(':checked')){
                 $('.item-price'+parseInt(i+1)).html('<span style="color:#ff9600">Wait...</span>');
                 $.post('/', {itemID : $(this).attr('itemID'), char_id : $('#char_id').val(), shopID : $('#shopID').val()}, function(data){
                     count++;


                     if (data=='online'){
                         $('.item-price'+parseInt(i+1)).html('<span style="color:#ee4646">Character online!</span>');
                     }
                     else if (data.match(/^[-\+]?\d+/) != null){
                         $('.item-price'+parseInt(i+1)).html('<span style="color:#56ee46">You get the item</span>');
                     }
                     else if (data=='balance'){
                         $('.item-price'+parseInt(i+1)).html('<span style="color:#ee4646">Not enough money on your balance</span>');
                     }else if(data == 'block') {
                         $(".close").click();
                         $("#protection").click();
                         $('.item-price'+parseInt(i+1)).html('<span style="color:#ee4646">Access error!</span>');
                     } else if(data == 'banned') {
                         $(".close").click();
                         $("#banned").click();
                         $('.item-price'+parseInt(i+1)).html('<span style="color:#ee4646">Banned account!</span>');
                     }
                     else{
                         $('.item-price'+parseInt(i+1)).html('<span style="color:#ee4646">Error!</span>');
                     }
                     $('.btn').show();
                     if(count==countGoods) {
                         $('.message').fadeOut(300);
                         $('input').iCheck('uncheck');
                         //$('input[type="checkbox"]').attr('checked', false);


                     }
                 });
             }
         });
         if (countGoods==0) {
             $.notij('Select the item!' ,{'type':'error'});
             $('.btn').show();
         }
     }
 }