
var cache_professions = {};
var cache_cities      = {'': [], '-1': []};

var reg_dialog_title = 'Серьезные порталы, как серьезные девушки - для получения дополнительных функций нужна регистрация :)';
var charset = document.charset || document.characterSet;
if (charset=="windows-1251") {
    reg_dialog_title = ' ,    -       :)';
}


function AstericsHide()
{
    /*  asterics hide */
    $(".necessary").keyup(function()
    {
        var value =  $(this)[0].value;
        if (value!="") {
            var  css_id = $(this).attr('id'); 
            var labelr =  'label[for="'+css_id +'"]   span.red' ;
            $(labelr).css({
                color:'white'
            });
        }
    });

    $(".necessary").change(function()
    {
        var value =  $(this)[0].value;
        if (value=="") {
            var  css_id = $(this).attr('id'); 
            var labelr =  'label[for="'+css_id +'"]   span.red' ;
            $(labelr).css({
                color:'red'
            });
        }
    });

    $(".necessary_select").change(function()
    {
        var css_id = $(this).attr('id');
        var labelr = 'label[for="'+css_id +'"]   span.red' ;
            
        var value =  $(this)[0].value;
        
        if (value=="-1") {
            $(labelr).css({
                color:'red'
            });
        } else {
            $(labelr).css({
                color:'white'
            });
        }
    });
}


function doGetCaretPosition(ctrl)
{
    var CaretPos = 0;	// IE Support
    if (document.selection) {
        ctrl.focus ();
        var Sel = document.selection.createRange ();
        Sel.moveStart ('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        CaretPos = ctrl.selectionStart;
    }
    return (CaretPos);
}


function setCaretPosition(ctrl, pos)
{
    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}


function ComplCity()
{
    $('#sfApplyApply_country_id').change(function()
    {
        if ($('#sfApplyApply_country_id').find('option:selected').val() == 1)
        {
            $('#sfApplyApply_region_id').removeAttr('disabled');
            $('#sfApplyApply_city').trigger('focus').trigger('blur');
            $('#sfApplyApply_country_id').focus();
        }
        else
        {
            $('#sfApplyApply_city').trigger('focus').trigger('blur');
            $('#sfApplyApply_region_id').attr('disabled', 'disabled');
            $('#sfApplyApply_region_id').val('').trigger('change');
            $('#sfApplyApply_country_id').focus();
        }
    });

    $('#sfApplyApply_region_id').change(function()
    {
        $('#sfApplyApply_city').trigger('focus').trigger('blur');
        var region = $('#sfApplyApply_region_id').find('option:selected').val();
        if (!cache_cities[region]) {
            $.ajax({
                url: '/autocomplete',
                data: {
                    section: region,
                    type : 'city'
                },
                dataType: "json",
                success: function(data) {
                    cache_cities[region] = data;
                }
            });
        }
    });

    $("#sfApplyApply_city").autocomplete(
    {
        minLength: 0,
        source: function(request, response)
        {
            var region = $('#sfApplyApply_region_id').find('option:selected').val();
            if (cache_cities[region])
            {
                var res = [];
                for (var i in cache_cities[region])
                {
                    if (i == parseInt(i))
                    {
                        if (request.term.toLowerCase() == cache_cities[region][i].toLowerCase().substr(0, request.term.length))
                        {
                            res.push(cache_cities[region][i]);
                        }
                    }
                }
                response(res);
            }
            else
            {
                response([]);
            }
        },
        open: function(event, ui)
        {
            $(this).data('autocomplete', true);
        },
        close: function(event, ui)
        {
            $(this).data('autocomplete', false);
        }
    });
    
    $('#sfApplyApply_activity_id').change(function()
    {
        $('#sfApplyApply_profession').val('');
        var  activity = $(this).find('option:selected').val();
        if (!cache_professions[activity]) {
            $.ajax({
                url: '/autocomplete',
                data: {
                    section: activity,
                    type : 'occupation'
                },
                dataType: "json",
                success: function(data) {
                    cache_professions[activity] = data;
                }
            });
        }
    });

    $("#sfApplyApply_profession").autocomplete(
    {
        minLength: 0,
        source: function(request, response)
        {
            var activity = $('#sfApplyApply_activity_id').find('option:selected').val();
            if (cache_professions[activity])
            {
                var res = [];
                for (var i in cache_professions[activity])
                {
                    if (request.term.toLowerCase() == cache_professions[activity][i].toLowerCase().substr(0, request.term.length))
                    {
                        res.push(cache_professions[activity][i]);
                    }
                }
                response(res);
            }
            else
            {
                response([]);
            }
        },
        open: function(event, ui)
        {
            $(this).data('autocomplete', true);
        },
        close: function(event, ui)
        {
            $(this).data('autocomplete', false);
        }
    });
}


function cleanupModals()
{
    $(".ui-dialog").remove();
    $('#formphysic').remove();
    $('#urlico').remove();
}


function addErrorHighlight()
{
    //    $('.error_block').unbind('keyup');
    //    $('.error_block').unbind('change');
    $('.error_block').keyup(function()
    {
        $(this).removeClass('error_block');
    });
    $('.error_block').change(function()
    {
        $(this).removeClass('error_block');
    });
}


$(document).ready(function()
{
    addPlaceholderProcessing();
});


function addPlaceholderProcessing()
{
    $('.placeholder').live('focus', function()
    {
        if ($.trim($(this).val()) != '' && $.trim($(this).attr('placeholder')) == '')
        {
            $(this).attr('placeholder', $.trim($(this).val()));
            $(this).addClass('placehol');
        }
        
        $(this).removeClass('placeholder');
        if ($.trim($(this).val()) == $.trim($(this).attr('placeholder')))
        {
            $(this).val('');
        }
    });
    
    $('.placehol').live('blur', function()
    {
        if ($.trim($(this).val()) == $(this).attr('placeholder') || $.trim($(this).val()) == '')
        {
            $(this).addClass('placeholder');
            $(this).val($(this).attr('placeholder'));
        }
    });
}


function isEmpty(object)
{
    var result = true;

    $.each(object, function(name, value)
    {
        result = false;
    });
    return result;
}

$('#login-url, #site_sections div.profile:not(.profile-enabled) a').live('click', function()
{
    one_load_flag = 1;
    var url = this.href;
    var st = document.createElement("link");
    st.setAttribute("rel","stylesheet");
    st.setAttribute("href","/web/css/apply.css");
    document.body.appendChild(st);
    var ms;
    Today = new Date();
    ms = Today.getMilliseconds();
    $.post(
        url,
        {
            randm_kod: ms
        },
        function(data, textStatus) {

            modal = $(data).dialog({
                modal: true,
                title: '',
                dialogClass :'login-window ui-state-hover',
                width  : '25.5em',
                resizable: false,
                draggable: false,
                close: function(event, ui) {
                    $("#modal-div").remove();
                    $(this).dialog('destroy');
                    cleanupModals();
					$(".login-window").remove();
                },
				open: function(event, ui) {$("#auth_username").focus();}
            });
            AstericsHide();
        }
        );
    return false;
});


$('#login-form').live('submit', function()
{
    var url = this.action;
    var data = $(this).serializeArray();
    $.post(
        url,
        data,
        function(json_data)
        {
            if (json_data=="202")
            {
                var user = $('#auth_username').val();
                var host = window.location.host.replace(/[a-z0-9_-]+\.(est.+|bm\d*\.thotal.+)/gi, '$1');
                var url = 'http://' + host + '/cabinet/profile';
                
                $(".ui-dialog").remove();
                top.location.href = url;
            }
            else
            {
                $ (".error_block").html (json_data);
            }
        },
        "json"
        );
    return false;
});


$('#registration-url').live('click', function()
{
    var url = this.href;
    $.get(
        url,
        function(data) {
            $(".ui-dialog").remove();
            cleanupModals();
            modal = $(data).dialog({
                modal: true,
                title: reg_dialog_title,
                position: 'center',
                dialogClass :'registration-window',
                width: 880,
                resizable: false,
                draggable: false,
                close: function(event, ui) {
                    $("#modal-div").remove();
                    $(this).dialog('destroy');
                    cleanupModals();
                }
            });
        }
        );
    return false;
});


$('.certain-registration-url').live('click', function()
{
    var url = this.href;
    $.get(
        url,
        function(data) {
            $(".ui-dialog").remove();
            cleanupModals();
            modal = $(data).dialog({
                modal: true,
                title: reg_dialog_title,
                position: 'center',
                dialogClass :'registration-window',
                width: 880,
                resizable: false,
                draggable: true,
                open: function(event, ui) {
                    ComplCity();
                    AstericsHide();
                },
                close: function(event, ui) {
                    $("#modal-div").remove();
                    $(this).dialog('destroy');
                    cleanupModals();
                }
            });
            addPlaceholderProcessing();
        }
        );
    return false;
});


$('#sf_apply_apply_form').live('submit', function()
{
    var url = this.action;
    var data = $(this).serializeArray();
    $.post(
        url,
        data,
        function(json_data)
        {
            if (isEmpty(json_data))
            {
                top.location.href='/cabinet/profile?from=reg';
            }
            else
            {
                $(".errorblock").empty();
                $('.error_block').removeClass('error_block');
                var focused = false;
                $.each(json_data, function(name, value) {
                    if (!focused) {
                        $("#sfApplyApply_" + name).focus();
                        focused = true;
                    }
                    var td = $("#sfApplyApply_" + name).addClass('error_block');
                    td = $("#autocomplete_" + name).addClass('error_block');
                });
                addErrorHighlight();
            }
        },
        "json"
        );
    return false;
});
