var hash = '', currentHash, ajaxExchangeJson;
var randomDate = new Date();
randomDate = randomDate.getTime() + '';
var randomSession = Math.ceil(Math.random() * 100000) + '';
randomSession = randomDate + randomSession;
var checkUrlInterval;
var ajaxLoader = [];
var displayItems = 'block-line', currency = 'RUR', rate = {}, allFilter = false;

function parseUrl(href){
    var url;
    var array1 = href.split('?');
    if(array1[1]){
        var array2 = array1[1].split('&');
        if(array2[1]){
            var json = new Object();
            var i;
            for(i = 0; i < array2.length; i++){
                var array3 = array2[i].split('=');
                json[array3[0]] = array3[1];
            }
            url = window.location.pathname + '#' + Base64.encode('{"url":"' + array1[0] + '","parameters":' + JSON.stringify(json) + ',"method":"get"}');
        } else {
            var array4 = array2[0].split('=');
            if(array4[1]){
                url = window.location.pathname + '#' + Base64.encode('{"url":"' + array1[0] + '","parameters":{"' + array4[0] + '":"'+array4[1]+'"},"method":"get"}');
            } else {
                url = window.location.pathname + '#' + Base64.encode('{"url":"' + array1[0] + '","parameters":{"' + array4[0] + '":""},"method":"get"}');
            }
        }
    } else {
        url = window.location.pathname + '#' + Base64.encode('{"url":"' + array1[0] + '","parameters":{},"method":"get"}');
    }
    return url;
}

function ajaxExchange(url, parameters, method) {
    if (method.toLowerCase() === 'get') {
        $('#content .text').empty();
        $('#head .search form[action="shop"] .filter').css('display','none');
        generateUrl(url, parameters, method);
    }
    if($('.panda').length === 0){
        $('#content .text').append('<div class="panda"><img src="img/ajax-loader.gif" /></div>');
        ajaxLoader.push('');
    } else {
        ajaxLoader.push('');
    }
    $.ajax({
        url: randomSession + '/AJAX/' + url,
        type: method,
        data: parameters,
        dataType: 'json',
        cache: false,
        success: function(data) {
            ajaxLoader.splice(ajaxLoader.length - 1,1);
            if(ajaxLoader.length === 0){
                $('.panda').remove();
            }
            var element = actions[data.action](data.data);
            if(element){
                element.find('a:not([href^="#"]):not([href^="/"]):not([href^="http://"])').each(function(){
                    $(this).attr('href',parseUrl($(this).attr('href')));
                });
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            $('#content .text').html('<div class="title">Ошибка!</div><div class="block"><span class="error">Произошла ошибка на сервере, попробуйте повторить позже!</span></div>');
            if(console){
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        }
    });
}

function generateUrl(url, parameters, method) {
    hash = '#' + Base64.encode('{"url":"' + url + '","parameters":' + JSON.stringify(parameters) + ',"method":"' + method + '"}');
    ajaxExchangeJson = JSON.parse('{"url":"' + url + '","parameters":' + JSON.stringify(parameters) + ',"method":"' + method + '"}');
    window.location.hash = hash;
}

function checkUrl() {
    currentHash = window.location.hash;
    if (currentHash !== hash) {
        if (currentHash === '') {
            window.location.reload(true);
        } else {
            currentHash = currentHash.slice(1);
            ajaxExchangeJson = JSON.parse(Base64.decode(currentHash));
            ajaxExchange(ajaxExchangeJson.url, ajaxExchangeJson.parameters, ajaxExchangeJson.method);
            if(ajaxExchangeJson.url === 'shop'){
                if ($('input[name="text"]').val() === '' && ajaxExchangeJson.parameters.text !== '') {
                    $('input[name="text"]').val(ajaxExchangeJson.parameters.text);
                }
                if (ajaxExchangeJson.parameters.shop !== '' && $('#head .search form[action="shop"] div select[name="shop"]').val() !== ajaxExchangeJson.parameters.shop) {
                    $('#head .search form[action="shop"] div select[name="shop"] option[value="' + ajaxExchangeJson.parameters.shop + '"]').attr('selected', 'selected').change();
                }
                if (ajaxExchangeJson.parameters.categorys !== '' && $('select[name="categorys"]').val() !== ajaxExchangeJson.parameters.categorys) {
                    $('select[name="categorys"] option[value="' + ajaxExchangeJson.parameters.categorys + '"]').attr('selected', 'selected');
                }
                if (ajaxExchangeJson.parameters.order !== '' && $('select[name="order"]').val() !== ajaxExchangeJson.parameters.order) {
                    $('select[name="order"] option[value="' + ajaxExchangeJson.parameters.order + '"]').attr('selected', 'selected');
                }
                if (ajaxExchangeJson.parameters.bids !== undefined) {
                    $('input[name="bids"]').attr('checked', 'checked');
                }
                if (ajaxExchangeJson.parameters.bin !== undefined) {
                    $('input[name="bin"]').attr('checked', 'checked');
                }
                if (ajaxExchangeJson.parameters.item_new !== undefined) {
                    $('input[name="item_new"]').attr('checked', 'checked');
                }
                if (ajaxExchangeJson.parameters.item_used !== undefined) {
                    $('input[name="item_used"]').attr('checked', 'checked');
                }
                if ($('input[name="min_price"]').val() === '' && ajaxExchangeJson.parameters.min_price !== '') {
                    $('input[name="min_price"]').val(ajaxExchangeJson.parameters.min_price);
                }
                if ($('input[name="max_price"]').val() === '' && ajaxExchangeJson.parameters.max_price !== '') {
                    $('input[name="max_price"]').val(ajaxExchangeJson.parameters.max_price);
                }
            }
            if(ajaxExchangeJson.url === 'item'){
                if ($('input[name="lot"]').val() === '' && ajaxExchangeJson.parameters.lot !== '') {
                    $('input[name="lot"]').val(ajaxExchangeJson.parameters.lot);
                }
                if (ajaxExchangeJson.parameters.shop !== '' && $('#head .search form[action="item"] div select[name="shop"]').val() !== ajaxExchangeJson.parameters.shop) {
                    $('#head .search form[action="item"] div select[name="shop"] option[value="' + ajaxExchangeJson.parameters.shop + '"]').attr('selected', 'selected').change();
                }
            }
        }
    }
    hash = window.location.hash;
}

jQuery(function($) {

    $('form').live('submit', function() {
        if ($(this).attr('action') === 'shop' && $(this).find('div input[name=text]').val() === '' || $(this).attr('action') === 'item' && $(this).find('div input[name=lot]').val() === '') {
            return false;
        }
        var method;
        if($(this).attr('method') !== ''){
            method = $(this).attr('method');
        } else {
            method = 'post';
        }
        ajaxExchange($(this).attr('action'), $(this).serializeJson(), method);
        return false;
    });

    $('a:not([href^="#"]):not([href^="/"]):not([href^="http://"])').each(function() {
        $(this).attr('href',parseUrl($(this).attr('href')));
    });

    $('a:not([href^="#"]):not([href^="/"]):not([href^="http://"])').each(function() {
        $(this).attr('href',parseUrl($(this).attr('href')));
    });

});
