$(document).ready(function(){
    $("#event1").corner("top 3px");
    $('a').focus(function() {
        $(this).blur();
    });

    var menu1 = 0;
    var menu2 = 0;
    $('.my-menu').click(function(){
        if (menu2 == 1) {
            $('.my-conf-menu-ui').toggle('blind', {}, 300);
            menu2 = 0;
        }

        $('.my-menu-ui').toggle('blind', {}, 300);
        menu1 = menu1 == 0 ? 1 : 0;
    });

    $('.my-conf-menu').click(function(){
        if (menu1 == 1) {
            $('.my-menu-ui').toggle('blind', {}, 300);
            menu1 = 0;
        }

        $('.my-conf-menu-ui').toggle('blind', {}, 300);
        menu2 = menu2 == 0 ? 1 : 0;
    });

    $('.fav').click(function(){
        favClick();
    });


    $('.prev-page, .next-page').click(function(){
        document.location.href = this.href;
    });

    $(document).bind('keydown', function(event){
        if (event.ctrlKey == true) {
            switch (event.keyCode) {
                case 13:
                    msg = getSelText();
                    if (msg.toString().length > 0) {
                        $('#syntaxError').toggle('blind', {}, 500);
                        ajax.sendSyntaxErorr(msg);
                    }
                    break;

                case 37:
                    $('.prev-page').click();
                    break;

                case 39:
                    $('.next-page').click();
                    break;
            }
        }
    });

    if ($('#add_title').length > 0 && $('.exists').length > 0) {
        $( "#add_title" ).change(function(){
            $.getJSON("/conference/checkTitle?keyword="+$( "#add_title" ).val(), function(data) {
                if (data.result) {
                    $('.exists a').attr('href', data.url);
                    $('.exists').show();
                };
            });
        });
    }

    $('.body').css({
        'top' : $('.banner').height()
    });
});

var loader = {
    show : function(container) {
        if (typeof(container) == "undefined") {
            container = '.content';
        }
        $(container).html('<div style="width:100%;height:100%;"><br /><br /><br /><br /><center><h3><img src=/images/indicator-small.gif>&nbsp;&nbsp;Подождите, идет загрузка...</h3></center></div>');
    },

    hide : function() {

    }
};
var calendar = {};
var ajax = {
    isGet : 1,
    updater : function (url, container, effect) {
        this.prepare(url, this.isGet == 1 ? "GET" : "POST");
        this._do(container, effect);
        this.isGet = 1;
    },
    _do : function(container, effect) {
        $.ajax({
            complete: function(complete) {
                loader.hide();
                if (container.length > 0) {
                    $(container).html(complete.responseText);
                    if (effect != 1) {
                        $(container).effect('highlight',{},1000);
                    }
                }
            }
        });
    },

    prepare : function(fullUrl, _TYPE) {
        $.ajaxSetup({
            url: fullUrl,
            type: _TYPE
        });
    },
    to : function(url, container) {
        this.prepare(url, this.isGet == 1 ? "GET" : "POST");
        loader.show(container);
        this._do(container);
        this.isGet = 1;
        return false;
    },
    submitForm : function(item, update) {
        $.ajax({
            url: $(item).attr('action'),
            type: 'post',
            data: $(item).serialize(),
            complete: function(complete) {
                loader.hide();
                if (typeof(update) != "undefined" && update.length > 0) {
                    $(update).html(complete.responseText);
                    $(update).effect('highlight',{},1000);
                }
            }
        });

        return false;
    },
    updaterCity : function(url, item) {
        if (!CheckType("#addCountryId", "#othercountry")) {
            this.updater(url, item);
        }
    },
    updateValue : function(url, container) {
        this.prepare(url, this.isGet == 1 ? "GET" : "POST");
        $.ajax({
            complete: function(complete) {
                loader.hide();
                $(container).val(complete.responseText);
            }
        });
    },
    sendSyntaxErorr: function(msg) {
        this.prepare('/application/syntaxError', "POST");
        $.ajax({
            data: 'msg=' + msg + '&url=' + document.location.href,
            complete: function(complete) {
                setTimeout(function() {
                    $('#syntaxError').effect('blind', {}, 500);
                }, 2000);
            }
        });
    }
};

function CheckType(field, nfield) {
    if ($(field).val() == -1) {
        $(nfield).attr('disabled', false);
        $(nfield + '1').removeClass('disabled_tr');
        return true;
    } else {
        $(nfield).attr('disabled', 'disabled');
        $(nfield + '1').addClass('disabled_tr');
        return false;
    }
}

function messageSended() {
    $('#submitBtnMessageTemplate').attr('disabled', 'disabled');
    $('#loadingMessage').show();
    $('#messageTemplate').attr('disabled', 'disabled');
    $('#resultSended').hide();
}

function recieveSuccess() {
    $('#submitBtnMessageTemplate').attr('disabled');
    $('#loadingMessage').hide();
    $('#messageTemplate').attr('disabled');
    $('#resultSended').show();
}

function mouseMove(el) {
    $(el).addClass('marked');
}

function mouseOut(el) {
    $(el).removeClass('marked');
}

function sendRequestForm(form, container) {
    recieveSuccess();
    $.ajax({
        url: $(form).attr('action'),
        data: $(form).serialize(),
        type: 'post',
        success: function(data) {
            $(container).html(data);
        }
    });
}

calendar.updater = function(container, url) {
    ajax.updater(url, container, 1);
}

function goToTopic(item, makeUrl, container)
{
    $('.myTopicClassName').each(function (i){
        $(this).css({
            'font-weight': 'normal'
        });
    });

    loader.show(container);
    ajax.updater(makeUrl, container);

    $(item).css({
        'font-weight': 'bold'
    });
    return false;
}

function UpdaterSelected(url, updater) {
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(data) {
            $(updater+' option').remove();
            $(data).each(function(i){
                $(updater).append('<option value="'+this.id+'">'+this.title+'</option>');
            });
        }
    });
}

function captchaRefresh(url)
{
    url += '?hashCode='+Math.random(999);
    $('#captchaId').attr('src', url);
}

function checkKeywords()
{
    if ($('#search_keywords').val() == 'Найти') {
        $('#search_keywords').val('');
    }
    return true;
}

function checkit()
{
    if ($('#add_domain').val() == '') {
        alert('Введите домен');
        return false;
    }
    if ($('add_width').val() == '') {
        alert('Установите ширину');
        return false;
    }

    if ($('#add_limit').val() == '') {
        alert('Установите количество объявлений');
        return false;
    }

    if ($('#add_titleSize').val() == '') {
        alert('Установите размер шрифта названия мероприятия');
        return false;
    }

    if ($('#add_textSize').val() == '') {
        alert('Установите размер шрифта текста объявления');
        return false;
    }
    return true;
}

function getPrivateKey(request, json)
{
    if (request.responseText != '') {
        $('#informerCode').val(request.responseText);
        $('#informerSource').show();
    }
}

function doSendFeedback(idUpdater, addr, params) {
    isGet = 2;

    url = addr +'?' + params
    ajax.prepare(url, "POST");

    $('#'+idUpdater).html("Идет отправка формы <img src='/images/indicator-small.gif' />");

    $.ajax({
        complete: function(complete) {
            $('#'+idUpdater).html(complete.responseText);
            $("#"+idUpdater).effect('highlight',{},1000);
        }
    });

}

function add(title) {
    insertAtCursor($('#messageTemplate')[0], title);
}

function insertAtCursor(myField, myValue) {
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    } else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

function showRequestInfo(requestId) {
    if ($('#request-info-'+requestId).html() == '') {
        $('#request-info-'+requestId).html('<div style="width:100%;text-align:center">Подождите, загружается <img src="/images/indicator-small.gif" alt="" /></div>');
        ajax.updater('/conference/requestInfo?requestId='+requestId, '#request-info-'+requestId);
    }

    $("#request-"+requestId).toggle('blind',{},500);
    switchValue("request"+requestId);
}

function switchValue(objectId) {
    if ($('#m_'+objectId).attr('src').indexOf('down.png') > -1) {
        ChangeImg('m'+objectId,'/images/up.png');
    } else {
        ChangeImg('m'+objectId,'/images/down.png');
    }
}

function ChangeImg() {
    if(document.images) {
        eval("document."+ChangeImg.arguments[0]+".src=('"+ChangeImg.arguments[1]+"')");
    }
}

var Objects = {};
function doIt(objectId) {
    if (Objects[objectId] != 1) {
        $('#request'+objectId).toggle('blind', {} ,500);
        switchValue('request'+objectId);
    }
}
function block(objectId) {
    Objects[objectId] = 1;
}
function unblock(objectId) {
    Objects[objectId] = -1;
}

var info = '';
function showListInfo() {
    if (info == '') {
        info = $('#tt').html();
    }
    $('#tt').html($('.conf-list').html());
    $('#tt').addClass('conf-list');

    $('.info-add').hide();
}

function showConfInfo() {
    $('#tt').html(info);
    $('#tt').removeClass('conf-list');
    $('.info-add').show();
}

function removeItem(url, item) {
    if (confirm('Вы уверены что хотите удалить элемент? Операция не обратима.')) {
        ajax.prepare(url, 'GET');
        $.ajax({
            complete: function(complete) {
                if (complete.responseText == 'success') {
                    $('.item-'+item).remove();
                }
            }
        });
    }
    return false;
}

function favClick() {
    val = $('.fav-value').text();
    url = '/favorite/toggle?conferenceId=' + val;
    ajax.prepare(url, "POST");

    $('.fav img').attr('src', '/images/indicator-small.gif');
    $.ajax({
        complete: function(complete) {
            if (complete.responseText == 'in-favorite') {
                $('.fav img').attr('src', '/images/favorite_disabled.gif');
                $('.fav-link').hide();
            } else {
                $('.fav img').attr('src', '/images/favorite.gif');
            }

            $('.fav img').effect('highlight',{},1000);
        }
    });
}
function changeDate(obj, id)
{
    var arr = $(obj).val().split('-');
    if (arr[2] && arr[1] && arr[0]) {
        $('#'+id).val(arr[2]+'-'+arr[1]+'-'+arr[0]);
    } else {
        $('#'+id).val('');
    }
}

function getSelText(){
    var txt = '';
    if (window.getSelection){
        txt = window.getSelection();
    }else if (document.getSelection){
        txt = document.getSelection();
    }else if (document.selection){
        txt = document.selection.createRange().text;
    }
    return txt;
}

function checkParticals(obj)
{
    if ($('#' + obj).val() == -1) {
        $('#titles').hide();
    } else {
        $('#titles').show();
    }
}

jQuery.fn.center = function() {
    var w = $(window);
    this.css("left",(w.width()-this.width())/2+w.scrollLeft() + "px");
    return this;
}

jQuery.fn.allCenter = function() {
    var w = $(window);
    this.css("left",(w.width()-this.width())/2+w.scrollLeft() + "px");
    this.css("top",(w.height()-this.height())/2+w.scrollTop() + "px");
    return this;
}

String.prototype.replaceAll = function(search, replace){
    return this.split(search).join(replace);
}

function getRandom(min, max) {
    return Math.random() * (max - min) + min;
}

function feedbackVote(link, vote) {

    if ($(link).parent().attr('disable')) {
        return false;
    }

    $.ajax({
        url: link.href,
        data: 'vote=' + vote + '&id=' + $(link).attr('feedbackId'),
        dataType: 'json',
        success: function(data) {
            feedbackShow(data.result, link);
        }
    });
}

function feedbackShow(result, link) {
    var fId = $(link).attr('feedbackId');
    var itm = $(link).parent().find('span');

    if (result !== false) {
        $.cookie('feedback-' + fId, true);
        $(link).parent().find('img').each(function(){
            var src = $(this).attr('src');
            $(this).attr('src', src.replace('_enable', '_disable'));
        });

        $(link).parent().attr('disable', true);

        if (0 == result) {
            itm.attr('class', 'default');
            itm.text('0');
        } else if (0 < result) {
            itm.attr('class', 'up');
            itm.text('+' + result);
        } else {
            itm.attr('class', 'down');
            itm.text(result);
        }
    }
}

function feedbackList(link) {
    page = parseInt($(link).attr('page')) + 1;
    $.ajax({
        url: link.href + '&page=' + page,
        success: function(data) {
            $('#feedback-list .paginator').hide();
            $('#feedback-list').append(data);
            $('#feedback-list .paginator:last').show();
            $('#feedback-list .paginator:last a').attr('page', page);

        }
    });
    return false;
}

function dateFormat(date, mask) {
    return $.format.date(date, mask);
};

Date.prototype.addDays = function(days) {
    return this.setDate(this.getDate() + days);
}

Math.roundVal = function(num, dec){
  return this.round(num * this.pow(10,dec)) / this.pow(10,dec);;
}

var goldManager = {
    vals : [],

    add: function(id) {
        var el = $('#gold-' + id);
        var config = {
            id        : id,
            startDate : el.attr('startDate'),
            endDate   : el.attr('endDate'),
            position  : el.attr('position')
        };

        this.vals[id] = new gold(config);
    },

    setBundle: function(item) {
        id = $(item).parents('li').attr('id').replace('gold-', '');

        if (this.vals[id].doBundle(item)) {
            $(item).text('Выключить связку');
        } else {
            $(item).text('Включить связку');
        }
    },

    reset: function(item) {
        id = $(item).parents('li').attr('id').replace('gold-', '');
        return this.vals[id].reset(item);
    },

    save: function(item) {
        id = $(item).parents('li').attr('id').replace('gold-', '');
        return this.vals[id].save(item);
    },

    payment: function(item) {
        id = $(item).parents('li').attr('id').replace('gold-', '');
        return this.vals[id].payment(item);
    }
}

function NewDate(str) {
    str=str.split('-');
    var date=new Date();
    date.setUTCFullYear(str[0], str[1]-1, str[2]);
    date.setUTCHours(0, 0, 0, 0);
    return date;
}

function gold(config) {
    var $this   = this;

    this.bundle = true;
    this.save   = false;
    this.tStart = NewDate(config.startDate);
    this.tEnd   = NewDate(config.endDate);
    this.tCurr  = new Date();

    this.daysObject   = $("#gold-" + config.id + ' .slider-body:first');
    this.weightObject = $("#gold-" + config.id + ' .slider-body:last');

    /**
     * количество дней на которые была куплена лента
     */
    var r = 30;

    /**
     * Количество дней которых остлось после покупки ленты
     */
    this.ostatokDays = Math.ceil((this.tEnd - this.tCurr) / (86400 * 1000));

    /**
     * Количество средств, которых осталось на текущий момент
     */
    this.ostatokPost = Math.roundVal((config.position / 30) * this.ostatokDays, 2);

    /**
     * Максимальное количество дней, при связке
     */
    this.maxBundleDays = this.ostatokPost / (3 / 30);

    /**
     * вес за один день
     */
    this.perDay = Math.roundVal(config.position / r, 2);

    this.ostatok = config.position;

    /**
     * установка даты начала и конца
     */
    this.refreshDate = function(tStart, tEnd) {
        $('#gold-' + config.id + ' .startDate').text(dateFormat(tStart, "dd.MM.yyyy"));
        $('#gold-' + config.id + ' .endDate').text(dateFormat(tEnd, "dd.MM.yyyy"));

        $('#gold-' + config.id + ' input[name="priceDate"]').val(
            dateFormat(tEnd, "yyyy-MM-dd")
        );
        $('#gold-' + config.id + ' input[name="position"]').val($('#gold-' + config.id + ' .slider-value:last').val());
    }

    /**
     * инициализация верхнего слайдера со сроками
     */
    this.initDays = function() {
        this.daysObject.slider({
            range: "max",
            min  : 1,
            max  : r,
            value: this.ostatokDays
        });

        this.daysObject.bind('slide slidestop', function(event, ui) {
            v1 = ui.value;
            if ($this.bundle && v1 > $this.maxBundleDays) {
                v1 = $this.maxBundleDays;
            }

            $('#gold-' + config.id + ' input.slider-value:first').val(v1);

            if ($this.bundle) {
                $this.sync(true);
            } else {
                $this.paymentCheck();
            }

            endDate = NewDate(config.endDate);
            endDate.addDays(v1 - $this.ostatokDays);
            $this.refreshDate($this.tStart, endDate);

            $this.doChange();
        });

        $("#gold-" + config.id + ' .slider-body:first .limit').css({
            'left' : $("#gold-" + config.id + ' .slider-body:first .ui-slider-handle').css('left')
        });
        $('#gold-' + config.id + ' input.slider-value:first').val(this.ostatokDays > 30 ? 30 : this.ostatokDays);
    }

    /**
     * инициализация слайдера с весом
     */
    this.initWeight = function() {
        this.weightObject.slider({
            range: "max",
            min  : parseInt(config.position),
            max  : 500,
            value: this.ostatok
        });

        this.weightObject.bind('slide slidestop', function(event, ui) {
            $('#gold-' + config.id + ' input.slider-value:last').val(Math.roundVal(ui.value, 2));
                               
            if ($this.bundle) {
                $this.sync(false);
            } else {
                $this.paymentCheck();
            }

            $this.doChange();  
        });

        $("#gold-" + config.id + ' .slider-body:last .limit').css({
            'left' : $("#gold-" + config.id + ' .slider-body:last .ui-slider-handle').css('left')
        });
        $('#gold-' + config.id + ' input.slider-value:last').val(this.ostatok);//config.position);
    }

    this.sync = function(type) {
        $this.save = true;
        $('.payment-check, .payment-do', '#gold-' + config.id).hide();

        var v1 = $('#gold-' + config.id + ' input.slider-value:first').val();
        var v2 = $('#gold-' + config.id + ' input.slider-value:last').val();

        endDate = NewDate(config.endDate);
        endDate.addDays(v1 - this.ostatokDays);
        $this.refreshDate($this.tStart, endDate);

        if (type) {
            vv = Math.roundVal((config.position / 30) * this.ostatokDays, 2);
            v2 = Math.roundVal((vv / v1) * 30, 2);

            v2 = v2 < config.position
                ? config.position
                : v2;

            this.weightObject.slider('option', 'value', v2);
            $('#gold-' + config.id + ' input.slider-value:last').val(v2);
        } else {
            vv = (config.position / 30) * this.ostatokDays;
            v1 = Math.ceil(vv / (v2 / 30));

            if ($this.bundle && v1 > $this.maxBundleDays) {
                v1 = $this.maxBundleDays;
            }
            if (v1 > 30) {
    		vv = Math.roundVal((config.position / 30) * this.ostatokDays, 2);
    		r = vv - (v2/30) * 30;
                r = Math.roundVal(r * -1 * price, 2);
                
                $('.payment-check', '#gold-' + config.id).show();
                $('#gold-' + config.id + ' .payment-check').text('Потеря ' + r + ' руб.');
                v1 = 30;
            } else if (v1 == 1) {
                vv = Math.roundVal((config.position / 30) * this.ostatokDays, 2);
                r = vv - (v2/30) * v1;

                this.save = false;

                if (r < 0) {
                    r = Math.roundVal(r * -1 * price, 2);

                    $('.payment-check', '#gold-' + config.id).html('Доплатите <span>' + r + '</span> руб.');
                    $('.payment-do, .payment-check', '#gold-' + config.id).show();
                }
            }

            this.daysObject.slider('option', 'value', v1);
            $('#gold-' + config.id + ' input.slider-value:first').val(v1);
        }
    }

    this.paymentCheck = function() {
        var v1 = $('#gold-' + config.id + ' input.slider-value:first').val();
        var v2 = $('#gold-' + config.id + ' input.slider-value:last').val();

        $('.payment-do', '#gold-' + config.id).hide();
        $('.payment-check', '#gold-' + config.id).show();

        vv = Math.roundVal((config.position / 30) * this.ostatokDays, 2);

        r = vv - (v2/30) * v1;

        if (r < 0) {
            this.save = false;

            r = Math.roundVal(r * -1 * price, 2);

            // показать сообщение
            $('#gold-' + config.id + ' .payment-check').html('Доплатите <span>' + r + '</span> руб.');

            // показать "доплатить"
            $('.payment-do', '#gold-' + config.id).show();
        } else {
            this.save = true;
            r = Math.roundVal(r * -1 * price, 2);

            // показать сообщение
            $('#gold-' + config.id + ' .payment-check').text('Потеря ' + r + ' руб.');
        }
    }

    this.reset = function(item) {
        $('#gold-' + config.id + ' input.slider-value:first').val(this.ostatokDays);
        $('#gold-' + config.id + ' input.slider-value:last').val(this.ostatok);

        this.daysObject.slider('option', 'value', this.ostatokDays);
        this.weightObject.slider('option', 'value', this.ostatok);

        $this.refreshDate(this.tStart, this.tEnd);

        $(item).hide();

        $('#gold-' + config.id + ' .save-btn').attr('disabled', 'disabled');
        $('.payment-check, .payment-do', '#gold-' + config.id).hide();
    }

    this.save = function(item) {
        return $(this).parents('form.gold-save').submit();
    }

    this.payment = function(item) {
        document.location.href = '/payment?conferenceId=' + config.id + '&price=' + $('#gold-' + config.id + ' .payment-check span').text();
    }

    this.doChange = function() {
        $('#gold-' + config.id + ' .cancel').show();

        if (true == this.save) {
            $('#gold-' + config.id + ' .save-btn').removeAttr('disabled');
        } else {
            $('#gold-' + config.id + ' .save-btn').attr('disabled', 'disabled');
        }
    }

    this.doBundle = function() {
        result = this.bundle;

        this.bundle = !this.bundle;

        if (false == result) {
            this.sync(true);
            this.sync(false);
        }

        return this.bundle;
    }

    /**
     * инициализация
     */
    this.init = function() {
        this.refreshDate(this.tStart, this.tEnd);
        this.initDays();
        this.initWeight();
    }

    $(document).scroll(function(){

        $('.lent-box').css({
            opacity: 1
        });

        switch (true) {
            case $(this).scrollTop() > 235:
                $('.lent-box').css({
                    'position' : 'fixed',
                    'top'      : '30px'
                });
            break;

            default:
                $('.lent-box').css({
                    'position' : 'absolute',
                    'top'      : '235px'
                });

        }
    });

    return this.init();
}
