function insertLoader() {
    return '<div class="ajax-loader"><img src="/static/images/ajax-loader.gif" /></div>'
}

window.registry = {};

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}

function isIframe(){
    return !!(window.location != window.top.location);
}

function clean_placeholders(form){
    $(':input', form).each(function(index, element){
        if ($(this).val() == $(this).attr('placeholder')) {
            $(this).val('');
        }
    });
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

/**
 * Wrappers for calling from iframe
 */
function close_day_popup(){
    $('#popup-holidays-container').data('overlay').close();
};

function open_login_popup(){
    /*$('#login').click();*/
}

//function click_copy(id){
//    $('#copy-idea' + id).click();
//    $.cookie('copy_event', null, {'path': '/'});
//}

/**
 * end Wrappers for calling from iframe
 */

$(document).ready(function(){
    /**
     * Init
     */
    $('input[placeholder]').placeholder();
    $('.scrollable').jScrollPane({
        verticalDragMinHeight: 51,
        verticalDragMaxHeight: 51
    });

    /**
     * end Init
     */

    /**
     * Accounts
     */
    
    function show_login_popup(){
        var popup = $('#popup-login');
        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
                , onClose: function(){
                    $('#constructor').show();
                }
            });
        }
        else {
            overlay.load();
        }
    }
    
    function tos_check(){
        if ($('#id_agreement').attr('checked')){
            $('#registration_submit').removeAttr('disabled');
        }
        else {
            $('#registration_submit').attr('disabled', 'disabled');
        }
    }
    
    $('#nice_id_agreement').live('click', function(e){
        e.preventDefault();
        
        tos_check();
    });

    function show_registration_popup(){
        var popup = $('#popup-registration');
        $('input[type="checkbox"]', popup).niceCb();
        tos_check();

        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
                , onClose: function(){
                    $('#constructor').show();
                }
            });
        }
        else {
            overlay.load();
        }
    }

    function show_reset_popup(){
        var popup = $('#popup-reset');

        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
                , onClose: function(){
                    $('#constructor').show();
                }
            });
        }
        else {
            overlay.load();
        }
    }
    
    /*$('#login').click(function(e){
        e.preventDefault();
        
        $('#constructor').hide();
        
        $.get('/accounts/login/', function(data){
            $('#popup-login-inner').html(data);
            show_login_popup();
        });
    });*/
    
    $('#login-form').live('submit', function(e){
        e.preventDefault();

        clean_placeholders(this);
        
        $.post('/accounts/login/', $(this).serialize(), function(data){
            if (data == 'ok'){
//                if ($.cookie('redirect_to_event') !== null) {
//                    window.location = '/';
//                }
//                else {
//                    window.location = window.location;
//                }
                var next = getQueryVariable('next');
                if (next) {
                    window.location = next;
                }
                else {
                    window.location = window.location;
                }
            }
            else {
                $('#popup-login-inner').html(data);
            }
        });
    });

    /*$('#registration').click(function(e){
        e.preventDefault();

        $('#constructor').hide();

        $.get('/accounts/register/', function(data){
            $('#popup-registration-inner').html(data);
            show_registration_popup();
        });
    });*/

    $('#registration-form').live('submit', function(e){
        e.preventDefault();

        clean_placeholders(this);

        $.post('/accounts/register/', $(this).serialize(), function(data){
            if (data == 'ok'){
                window.location = window.location;
            }
            else {
                $('#popup-registration-inner').html(data);
                $('input[type="checkbox"]', '#popup-registration').niceCb();
                tos_check();
            }
        });
    });
    
    $('#registration-link').live('click', function(e){
        e.preventDefault();

        $('#popup-login').data('overlay').close();
        /*$('#registration').click();*/
    });

    $('#reset').live('click', function(e){
        e.preventDefault();

        $('#constructor').hide();

        $('#popup-login').data('overlay').close();

        $.get('/accounts/password/reset/', function(data){
            $('#popup-reset-inner').html(data);
            show_reset_popup();
        });
    });

    $('#reset-form').live('submit', function(e){
        e.preventDefault();

        $.post('/accounts/password/reset/', $(this).serialize(), function(data){
            $('#popup-reset-inner').html(data);
        });
    });

    if (getQueryVariable('next')){
        /*$('#login').click();*/
    }

    /**
     * end Accounts
     */


    /**
     * Feedback
     */
    
    function show_feedback_popup(){
        var popup = $('#popup-feedback');
        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
                , onClose: function(){
                    $('#constructor').show();
                }
            });
        }
        else {
            overlay.load();
        }
    }
    
    $('#feedback').click(function(e){
        e.preventDefault();

        $('#constructor').hide();
        
        $.get('/feedback/', function(data){
            $('#popup-feedback-inner').html(data);
            show_feedback_popup();
        });
    });
    
    $('#feedback-form').live('submit', function(e){
        e.preventDefault();

        clean_placeholders(this);
        
        $.post('/feedback/', $(this).serialize(), function(data){
            if (data == 'ok'){
                $('#popup-feedback-inner').html('<div id="popup-feedback-inner-done">Ваше письмо отправлено, спасибо!</div>');
            }
            else {
                $('#popup-feedback-inner').html(data);
            }
        });
    });

    /**
     * end Feedback
     */


    /**
     * Constructor
     */
    $('#send-postcard-form').live('submit', function(e){
        e.preventDefault();

        var book_id = $('input[name=book_id]', this).val();
        var book_key = $('input[name=book_key]', this).val();

        var $sender = $('#id_sender');

        clean_placeholders(this);
        var post_url = '/send-book/'; 

        if ($(this).hasClass('f23')) {
            post_url = '/23/send/';
        }

        post_url += book_id + '/' + book_key + '/';

        $.post(post_url, $(this).serialize(), function(data){
            if (data == 'ok') {
                window.location = window.location.pathname + '?send=1';
            }
            else {
                $('#send-postcard-form-container').html(data);
            }
        });
    });
    $('#popup-send-card .btn-participate').click(function(e){
        e.preventDefault();
        var form = $('#send-participate-form');

        if ( $('input[name="agreement"]:checked').length > 0 ) {

            var book_id = $('input[name=book_id]', form).val();
            var book_key = $('input[name=book_key]', form).val();

            clean_placeholders(form);
            var post_url = '/participate/'; 

            if ($(form).hasClass('myhero')) {
                post_url = '/myhero' + post_url ;
            }

            post_url += book_id + '/' + book_key + '/';

            $.post(post_url, $(form).serialize(), function(data){
                if (data == 'ok') {
                    window.location = window.location.pathname + '?send=1';
                    var show_list = $('#popup-send-card .options').has('.off');
                    $('#popup-send-card .options').addClass('off');
                    show_list.removeClass('off');
                }
                else {
                    $('#send-participate-form-container').html(data);
                    $('#lbl05').niceCb();
                }
            });
        }
        else {
            alert('Для продолжения необходимо дать согласие на обработку персональных данных и принять условия акции.');
        }
    });
    /**
     * end Constructor
     */


    /**
     * Calendar
     */

    function show_day_popup(){
        var popup = $('#popup-holidays-container');
        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
                , onBeforeLoad: function(){
                }
            });
        }
        else {
            overlay.load();
        }
    }

    function day_link(calendar_id, day_idx, section){
        if (!section) {
            section = 'my';
        }
        return '/meetings/' + calendar_id + '/' + day_idx + '/' + section + '/';
    }

    function add_event_link(calendar_id, day_idx){
        return '/meetings/' + calendar_id + '/' + day_idx + '/add-event/';
    }

    function copy_event_link(calendar_id, day_idx, event_id){
        return '/meetings/' + calendar_id + '/' + day_idx + '/copy-event/' + event_id + '/';
    }

    function delete_event_link(calendar_id, day_idx, event_id){
        return '/meetings/' + calendar_id + '/' + day_idx + '/delete-event/' + event_id + '/';
    }

    function bind_char_counter(){
        $("#id_description", "#add-event-form").charCount({
            allowed: 140,
            warning: 20,
            counterText: 'Символов: ',
            counterElement: 'span',
            wrapperElement: 'div'
        });
    }

    bind_char_counter();

    function check_search_length(search_form_id, checked_element, disabled_element){
        var input = $(checked_element, search_form_id);
        if (input.length) {
            var disabled = input.val().length;
            //console.log('check_search_length ', disabled);
            if (disabled < 3) {
                $(disabled_element, search_form_id).attr('disabled', 'disabled');
            }
            else {
                $(disabled_element, search_form_id).removeAttr('disabled');
            }
        }
    }

    check_search_length('#rating-search', ':text', ':submit');
    check_search_length('#change-city', ':text', ':submit');
    check_search_length('#add-event-form', '#id_description', ':button');

    $("#id_description", "#add-event-form").keyup(function(){check_search_length('#add-event-form', '#id_description', ':button');});
    $("#id_description", "#add-event-form").keydown(function(){check_search_length('#add-event-form', '#id_description', ':button');});
    $("#id_description", "#add-event-form").change(function(){check_search_length('#add-event-form', '#id_description', ':button');});
    $("#id_description", "#add-event-form").bind('input paste', function(){check_search_length('#add-event-form', '#id_description', ':button');});

    function show_day_on_init(){
        //debugger;
        var add_event = $.cookie('redirect_to_event');
        var redirect_event = $.cookie('redirect_to_my_event');
        var day_from_get = getQueryVariable('day');
        var tab_from_get = getQueryVariable('tab');

        //open popup based on cookie or GET params
        if (add_event !== null || (day_from_get !== null && tab_from_get !== null)) {
            //calendar_page
            if (window.registry['calendar_id'] !== undefined) {
                //open based on cookie
                if (add_event) {
                    var data = add_event.split(':');
                    //right calendar
                    if (data[0] == window.registry['calendar_id']) {
                        //console.log('open popup');
                        var class_name = '';
                        if (data[1] == '1') {
                            class_name = 'd31'
                        }
                        else {
                            class_name = 'j' + (parseInt(data[1]));
                        }
                        $('#popup-holidays-container').removeClass().addClass('popup p' + class_name);
                        $('#day-iframe').attr('src', day_link(data[0], data[1], data[2]));
                        show_day_popup();
                        //console.log('delete cookie');
                        $.cookie('redirect_to_event', null, {'path': '/'});
                    }
                    else {
                        //console.log('different calendar id');
                        window.location = '/meetings/' + data[0] + '/';
                    }
                }
                //open based on get params
                else {
                    var class_name = '';
                    if (day_from_get == '1') {
                        class_name = 'd31'
                    }
                    else {
                        class_name = 'j' + (parseInt(day_from_get));
                    }
                    $('#popup-holidays-container').removeClass().addClass('popup p' + class_name);
                    $('#day-iframe').attr('src', window.location.pathname + day_from_get + '/' + tab_from_get + '/');
                    show_day_popup();
                }
            }
            //if main page, redirect after login
            else {
                //console.log('other page');
                if (add_event){
                    var data = add_event.split(':');
                    window.location = '/meetings/' + data[0] + '/';
                }
            }
        }
        //workaround for switching from jacobs events to my events tab
        else if (redirect_event) {
            var class_name = '';
            if (redirect_event == '1') {
                class_name = 'd31'
            }
            else {
                class_name = 'j' + (parseInt(redirect_event));
            }
            $('#popup-holidays-container').removeClass().addClass('popup p' + class_name);
            $('#day-iframe').attr('src', day_link(window.registry['calendar_id'], redirect_event, 'my'));
            show_day_popup();
            //console.log('delete cookie');
            $.cookie('redirect_to_my_event', null, {'path': '/'});
        }
        else {
            //console.log('no calendar id');
        }
    }

    show_day_on_init();
    
//    function copy_idea_on_init(){
//        if (window.location != window.top.location){
//            //copy event to our list
//            var event_to_copy = $.cookie('copy_event');
//            if (event_to_copy) {
//                window.top.click_copy(event_to_copy);
//            }
//        }
//    }
//
//    copy_idea_on_init();
    
    $('#tt-mi').click(function(e){
        //debugger;
        if (window.top.registry['is_default_calendar'] === 1) {
            e.preventDefault();
            if (window.top.registry['logged_in'] === 1){
                $.cookie('redirect_to_my_event', window.top.registry['last_accessed_day'], {'path': '/'});
                window.top.location = '/meetings/'
            }
            else {
                window.top.open_login_popup();
            }
        }
    });
    
    $('#create-calendar').click(function(e){
        //debugger;
        var auth = $(this).data('authenticated');
        var my = $(this).data('my');
        
        if (!auth){
            e.preventDefault();
            /*$('#login').click();*/
        }
        else {
            if (my){
                e.preventDefault();
            }
        }
    });

    $('.day-details').click(function(e){
        e.preventDefault();

        var calendar_id = $(this).data('calendar');
        var day_idx = $(this).data('day');
        
        window.registry['last_accessed_day'] = day_idx;

        $('#popup-holidays-container').removeClass().addClass('popup p' + $(this).parent().attr('class') );

        //initial tab
        var tab = 'my';
        //tab for anonymous user
        if (window.top.registry['is_default_calendar'] === 1){
            tab = 'recommended';
        }
        $('#day-iframe').attr('src', day_link(calendar_id, day_idx, tab));
        show_day_popup();
    });

    $('#add-event').live('click', function(e){
        e.preventDefault();

        var loggedin = $(this).data('loggedin');
        var calendar_id = $(this).data('calendar');
        var day_idx = $(this).data('day');
        var tab = window.location.pathname.split('/')[4];

        if (!loggedin) {
            $.cookie('redirect_to_event', calendar_id + ':' + day_idx + ':' + tab, {'path': '/'});
            var popup = $('#popup-holidays-container', window.top.document);
            var login = $('#login', window.top.document);
            window.top.close_day_popup();
            window.top.open_login_popup();
        }
        else {
            $('#add-event-form').submit();
        }
    });

    $('#add-event-form').live('submit', function(e){
        e.preventDefault();

        var calendar_id = $('#add-event').data('calendar');
        var day_idx = $('#add-event').data('day');

        if ($('#id_description').val().length > 140){
            return;
        }

        clean_placeholders(this);

        $.post(add_event_link(calendar_id, day_idx), $(this).serialize(), function(data){
            if (data == 'ok') {
                window.location = window.location;
            }
            else {
                $('#add-event-form-container').html(data);
                bind_char_counter();
            }
        });
    });

    $('.copy-event').live('click', function(e){
        e.preventDefault();

        var loggedin = $(this).data('loggedin');
        var calendar_id = $(this).data('calendar');
        var day_idx = $(this).data('day');
        var event_id = $(this).data('event');
        var tab = $(this).data('tab');
        var $this = $(this);
        //debugger;
        if (!loggedin) {
            $.cookie('redirect_to_event', calendar_id + ':' + day_idx + ':' + tab, {'path': '/'});
            $.cookie('copy_event', event_id, {'path': '/'});
            var popup = $('#popup-holidays-container', window.top.document);
            var login = $('#login', window.top.document);
            window.top.close_day_popup();
            window.top.open_login_popup();
        }
        else {
            $.get(copy_event_link(calendar_id, day_idx, event_id), function(data){
                if (data.status == 'ok') {
                    $this.replaceWith('<span class="idea-action idea-added">Добавлено</span>');
                }
                else {
                    alert('Ошибка');//TODO
                }
            }, 'json');
        }
    });

    $('.delete-event').live('click', function(e){
        e.preventDefault();

        var calendar_id = $(this).data('calendar');
        var day_idx = $(this).data('day');
        var event_id = $(this).data('event');
        var parent_container = $(this).parents('.idea');

        $.get(delete_event_link(calendar_id, day_idx, event_id), function(data){
            if (data.status == 'ok') {
                parent_container.remove();
            }
            else {
                alert('Ошибка');//TODO
            }
        }, 'json');
    });

    function init_city_select(){
        //debugger;
        var $city_select = $('#city-selected');
        var location = $city_select.data('location');
        var suggested_location = $city_select.data('suggested_location');
        if (location === 0) {
            $('span', '#city-selected').text('...');
        }
        else if (location){
            $('span', '#city-selected').text(location);
        }
        else if (suggested_location){
            $('span', '#city-selected').text(suggested_location);
        }
    }

    init_city_select();

    $('#city-selected').click(function(){
        $('#city-list').toggle();
    });

    $('li', '#city-list').click(function(e){
        var text = $(this).text();
        $('span', '#city-selected').text(text);
        if (text == '...'){
            text = '0';
        }
        $.post('/set-city/', {city: text}, function(){
            window.location = window.location;
        }, 'json');
    });

    $(':text', '#rating-search').keyup(function(){
        check_search_length('#rating-search', ':text', ':submit');
    });

    /**
     * end Calendar
     */

    /**
     * Gallery
     */

    function show_photo_popup(){
        var popup = $('#popup-photo');

        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
            });
        }
        else {
            overlay.load();
        }
    }
    
    function load_rink_photo(id){
        $.get('/photos/' + id + '/', function(data){
            $('#popup-photo').html(data);
            if (window.addthis) {
                window.addthis.ost = 0;
                window.addthis.ready();
            }
            show_photo_popup();
        });
    }
    
    function show_photo_on_init(){
        var photo = getQueryVariable('photo');

        if (photo && parseInt(photo) != NaN){
            load_rink_photo(photo);
        }
        else {
            var path = window.location.pathname.split('/');
            if (path[1] == 'photos' && path[2] == 'photo' && parseInt(path[3]) != NaN){
                load_rink_photo(path[3]);
            }
        }
    }

    show_photo_on_init();

    $('.photos li a').click(function(e){
        e.preventDefault();

        load_rink_photo($(this).data('id'));
    });

    $('.photos-filter-city .combobox').click(function(){
        $('.combobox-list', $(this)).toggle();
    });

    $('.photos-filter-date .combobox span').click(function(){
        $(this).siblings('.combobox-list').toggleClass('off');
    });

    $('.combobox-list li').click(function(e){
        var self = $(this);
        var text = self.text();
        
        var $span = $('span', self.parents('.combobox'));
        $span.text(text);
        $span.trigger('combobox.changed', [text]);
    });

    $('.photos-filter-date .combobox-list').each(function(){
        var self = $(this);
        if ( $('li', self).length > 13 ) {
            self.height('273px').jScrollPane(
                {
                    verticalDragMinHeight: 20
                    , verticalGutter: 0
                    , horizontalGutter: 5
                }
            );
            var jsp = self.data('jsp');
            if (jsp !== undefined) {
                jsp.scrollToBottom();
            }
        }
    });

    $('.photos-filter-city .combobox-list li').click(function(e){
        var text = $(this).text();
        if (text == '...'){
            text = '';
        }
        $('#id_city').val(text);
        $('#promo-photos-filter-form').submit();
    });

    $('.photos-filter-date .combobox-list li').click(function(e){
        var text = $(this).text();
        $('#id_date').val($(this).data('date'));
        $('#promo-photos-filter-form').submit();
    });

    $('.vote').click(function(e){
        e.preventDefault();

        $.post($(this).attr('href'), function(data){
            if (data.success) {
                window.location = window.location;
            }
            else {
                alert(data.message);//TODO
            }
        }, 'json');
    });
    
    $('.send-to-contest').live('click', function(e){
        e.preventDefault();
        
        var $this = $(this);
        
        $.get($this.attr('href'), function(data){
            window.location = window.location;
        });
    });
    
    function show_rinks_popup(){
        var popup = $('#popup-rinks-container');

        var overlay = popup.data('overlay');
        if ( undefined === overlay ) {
            popup.overlay({
                mask: {
                    color: '#001a06'
                    , loadSpeed: 200
                    , opacity: 0.8
                }
                //, closeOnClick: false
                , top: 'center'
                , load: true
            });
        }
        else {
            overlay.load();
        }
    }

    $('.link-rinks').click(function(e){
        e.preventDefault();

        $('#rinks-iframe').attr('src', '/places/1/');
        show_rinks_popup();
    });
    
    $('.link-contest-photo').click(function(e){
        var loggedin = $(this).data('loggedin');

        if (!loggedin) {
            e.preventDefault();
            /*$('#login').click();*/
        }
    });

    /**
     * end Gallery
     */
});



var TIMEOUT_STD = 1000; //таймауты
var TIMEOUT_SHORT = 300;
var TIMEOUT_LONG = 3000;

function update_captcha(el){
    /*
    if (el == undefined){
        $.getJSON('/captcha/update/?nocache='+(new Date()).getTime(), function(data){
            $('.captcha').attr({'src': '/captcha/image/'+data.key+'/'});
            $('#id_captcha_0').val(data.key);
        });
    }else{
        $.getJSON('/captcha/update/?nocache='+(new Date()).getTime(), function(data){
            el.find('.captcha').attr({'src': '/captcha/image/'+data.key+'/'});
            el.find('.captchatextinput[name=captcha_0]').val(data.key);
        });
    }
    */
};


var CRM_ERRORS = {
    /*
    1: "отсутствует обязательный параметр",
    2: "длина строки меньше допустимой",
    3: "длина строки больше допустимой",
    4: "в указанном поле присутствуют запрещённые для данного поля символы",
    5: "некорректный формат",
    6: "участнику не исполнилось 18-ти лет на текущий момент",
    7: "пароли не совпадают"
    */
    1: "Отсутствует обязательный параметр",
    2: "Длина строки меньше допустимой",
    3: "Длина строки больше допустимой",
    4: "Присутствуют запрещённые символы",
    5: "Некорректный формат",
    6: "Указанный e-mail уже используется"
};

var MAP_FIELDS = {
    'name': 'first_name',
    'surname': 'last_name',
    'patronymic': 'patronymic',
    'post_index': 'zip',
    'id_region': 'region',
    'id_district': 'district',
    'id_city': 'place',
    'update_email': 'update_email',
    'region': 'region_text',
    'district': 'district_text',
    'city': 'place_text',
    'build': 'building',
    'msisdn': 'phone_mobile',
    'password': 'password',
    'birthday': 'birthday',
    'house': 'house',
    'part': 'part',
    'street': 'street',
    'flat': 'flat'
};

var MAP_FIELDS_VERBOSE = {
    'name': 'Имя',
    'surname': 'Фамилия',
    'patronymic': 'Отчество',
    'post_index': 'Индекс',
    'id_region': 'Регион',
    'id_district': 'Район',
    'id_city': 'Населенный пункт',
    'city': 'Населенный пункт',
    'address_note': 'Доп. данные',
    'build': 'Строение',
    'phone': 'Дом. телефон',
    'msisdn': 'Мобильный телефон',
    'password': 'Пароль',
    'birthday': 'Дата рождения',
    'flat': 'Квартира'
};

function popup_message(message, close_clb, error, add_class) {
    error = error || false;
    add_class = add_class || ''

    var popup = $('#popup-message');

    if (add_class.length > 0) {
        popup.addClass(add_class);
    }

    var overlay = popup.data('overlay');

    if (error) {
        popup.addClass('popup-error');
    }
    else {
        popup.removeClass('popup-error');
    }

    $('.popup-content', popup).empty().append(
        $(error ? '#popup-error-tpl' : '#popup-message-tpl').children().clone()
    );
    $('h2', popup).after('<p>' + message + '</p>');

    if (undefined === overlay) {
        var params = {
            mask: {
                color: '#001a06'
                , loadSpeed: 200
                , opcaity: 0.8
            }
            , top: 'center'
            , load: true
        };

        if ($.isFunction(close_clb)) {
            $.extend(params, {'onClose': close_clb});
        }
        popup.overlay(params);
    }
    else {
        if ($.isFunction(close_clb)) {
            popup.unbind('onClose').bind('onClose', close_clb);
        }
        $('.popup-content a.close', popup).unbind('click').bind(
            'click'
            , (function(overlay_obj){
                return function(e) {
                    overlay_obj.close();
                    return false;
                };
            })(overlay)
        );
        overlay.load();
    }
}

function popup_error(message, close_clb) {
    //console.log('Popup error');
    popup_message(message, close_clb, true)
}


function init_bc_tip(field) {
    var tips = {
        'street': 'Поле «Улица» может содержать только символы кириллицы, цифры, тире, <br />пробел, дефис, "/" и "\\".',
        'house': 'Номер «Дом» может содержать только цифры, символы кириллицы, <br />пробел, "/" и "\\".',
        'part': 'Поле «Корпус» может содержать только цифры, символы кириллицы, <br />пробел, "/" и "\\".',
        'building': 'Поле «Строение» может содержать только цифры, символы кириллицы, <br />пробел, "/" и "\\".',
        'flat': 'Поле «Квартира» может содержать только цифры, символы кириллицы, <br />пробел, "/" и "\\".',
        'first_name': 'Поле «Фамилия» может содержать только символы кириллицы, пробел и тире.',
        'last_name': 'Поле «Имя» может содержать только символы кириллицы, пробел и тире.',
        'patronymic': 'Поле «Отчество» может содержать только символы кириллицы, пробел и тире.',
        'district_text': 'Поле «Ваш район» может содержать только цифры, символы кириллицы, пробел, дефис, "/" и "\\".',
        'place_text': 'Поле «Ваш город» может содержать только цифры, символы кириллицы, пробел, дефис, "/" и "\\".',
    };

    field = field || '';
    if (field in tips) {
        var tip_link = $('<a href="#" class="char-tip">Подробнее</a>');
        $('#id_' + field + '_row p.err-message').append('. ').append(tip_link);
        $('#id_' + field + '_row .char-tip').click(function(e){
            e.preventDefault();
            popup_message(tips[field],undefined, false, 'h-tip');
        });
    }
};


function mark_field_bad(el, text){
    $(el).nextAll().remove();
    $(el).after('<div class="clear"></div><p class="txt err-message">' + text + '</p>');
}


function fill_crm_errors(task_status){
    var is_field_error = false;
    if (task_status['result']['response']['fields'] != undefined
        && Object.keys(task_status['result']['response']['fields']).length > 0
        ) {
        $.each(
            task_status['result']['response']['fields'],
            function(field, error_code) {
                var field_name = MAP_FIELDS[field];
                var error_value = CRM_ERRORS[parseInt(error_code)];

                if (field_name == 'phone_mobile') {
                    error_value = 'Введите номер в формате 7XXXXXXXXXX';
                }
                if ( (error_code == 2)  && (field_name == 'password') ) {
                    error_value = 'Пароль должен содержать не менее 6 символов.';
                }
                mark_field_bad($('#id_'+field_name).parent(), error_value);
                if (error_code == 4) {
                    init_bc_tip(field_name);
                }
            }
        );
        is_field_error = true;
    }

    return is_field_error;
};

function check_task_result(task_id, form_obj, interval_name, callbacks, not_update_captcha){
    if (task_id['error'] != undefined){
        if (form_obj != undefined){
            form_obj.fadeform_clear(interval_name);
        }
        clearInterval(window[interval_name]);
        popup_error(task_id['error']);
        return;
    }
    
    $.ajax({
        url: '/crmapi/taskstatus/'+task_id+'/?nocache='+(new Date()).getTime(),
        dataType: 'json',
        success: function(task_status){
            if ((task_status.status == 'SUCCESS') || (task_status.status == 'FAILURE') || (task_status.status == 'REVOKED') || (task_status.cached != undefined)){
                if (form_obj != undefined){
                    form_obj.fadeform_clear(interval_name);
                }else{
                    clearInterval(window[interval_name]);
                }
                
                if (task_status.result.response != undefined){
                    if (((task_status.result.response.result == 0) || (task_status.cached != undefined)) && ((callbacks != undefined) && (callbacks['success_clb']))){
                        callbacks['success_clb'](task_status);
                    }
                    if ((task_status.result.response.result != 0) && (task_status.cached == undefined)){
                        if (!fill_crm_errors(task_status)) {
                            if (callbacks['error_clb']){
                                callbacks['error_clb'](task_status);
                            }
                            else {
                                if (task_status.result.response_error_text != undefined) popup_error(task_status.result.response_error_text);
                                if (task_status.result.global_error_text != undefined) popup_error(task_status.result.global_error_text);
                            }
                        }
                        
                    }
                }else{
                    if (callbacks['crm_failure_clb']){
                        callbacks['crm_failure_clb'](task_status);
                    }
                    popup_error('База данных недоступна, попробуйте позже');
                }
                // success or error message
            }else{
                // polling
            }
        },
        error: function(request, status, error){
            // status 'error' and empty error means that user change location before end of request
            if ((status != 'error' || error) && (status != '' || error != 'error') ) {
                clearInterval(window[interval_name]);
                popup_error('Внутренняя ошибка сервера');
            }
        }
    });
};


function ajax_task(form_selector, callbacks, nobind){
    $('.err-text').removeClass('err-text');
    $('.err-message').remove();
    
    function after_submit(form_selector, callbacks){
        form_obj = $(form_selector);
        form_obj.fadeform();
        
        var interval_name = form_obj.attr('id')+'_interval_id';
        $.post(form_obj.attr('action'), form_obj.serialize(), function(data){
            if (data['form_with_errors'] != undefined){
                form_obj.fadeform_clear(interval_name);
                
                form_obj.parents('.wrapper').html(data['form_with_errors']);
                
                //render_errors();
                //$('#errors_bar').show();
                
                if (callbacks['form_with_errors_clb'] != undefined){
                    callbacks['form_with_errors_clb'](data);
                }
            }else{
                var task_id = data.task_id;
                window[interval_name] = setInterval(function(){
                    check_task_result(
                        task_id,
                        form_obj,
                        interval_name,
                        callbacks
                    )
                }, TIMEOUT_SHORT);
            }
        }).error(function() {
            form_obj.fadeform_clear(interval_name);
            clearInterval(window[interval_name]);
            popup_error('Ошибка сервера, попробуйте позже.');
        })
    }
    
    if((nobind != undefined) && (nobind == true)){
        after_submit(form_selector, callbacks);
    }else{
        $(form_selector).live('submit', function(e){
            e.preventDefault();
            $('.err-message').remove();
            if (callbacks['presubmit_clb'] != undefined){
                if((callbacks['presubmit_clb'](this)) == 'stop'){
		    return;
		}
            }
            after_submit(form_selector, callbacks);
        });
    }
};

