// Сообщение о том, что контент загружается
var log_loading_html = '<img src="/i/loading-long.gif" title="' + _('Загружается') + '" id="iii-ajax-loader">';

// {{{ трекер курсора мышки
/*var $mx = 0;
var $my = 0;
var $mouseIndicator = $('<div style="padding-left:3px;padding-right:3px;align:center;position:absolute;width:auto;height=20px;background:black;color:white;opacity:0.2"></div>').hide();
$(document).ready(function () {
    $('body').append($mouseIndicator.show());
    $().mousemove(function (e) {
        $mx = e.pageX;
        $my = e.pageY;
        $mouseIndicator.text(e.pageX + ', ' + e.pageY);
        $mouseIndicator.css({left: e.pageX, top: e.pageY - 20});
    });
});*/
// }}}

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, first) {
    for (var i = first || 0, l = this.length; i < l; i++) {
      if (this[i] === item) return i;
    }
    return -1;
  }
}

$(document).ready(function () {

    // {{{ Фикс PNG для MSIE6

    if (jQuery.browser.msie && jQuery.browser.version.charAt(0) == '6') {
        var opaque = '/i/1px.gif';
        $('img').each(function () {
            var src = $(this).attr('src');
            if (src.substring(src.length - 3, src.length) == 'png') {
                $(this).attr('src', opaque);
                $(this).css({
                    filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '",sizingMethod="image")'
                });
            }
        });
    }

    // }}}

    assignTooltips();
});


function assignTooltips(cntx) {
    if (undefined == cntx) {
        cntx = $(document);
    }
    $('.helpTooltip', cntx).hover(
        function(){
            var target = $('.content',this);
            if (target.data('visible') != true) {
                target.fadeIn("slow",function() {
                    target.data("visible",true);
                });
            }
        },
        function(){
            var target = $('.content',this);
            if (target.data('visible') == true) {
                target.stop().css({opacity:1.0}).fadeOut("slow",function(){
                    target.data("visible",false);
                });
            }
        }
    );
}

// {{{ Редактор логов
jQuery.fn.logEditor = function (container, custom) {
    var defaultOptions = {
        form: {
            action: '',
            method: 'post'
        },
        pattern: '',
        reply: '',
        chat: 0,
        message: 0,
        container: $(this).attr('id')
    };
    var options = $.extend(defaultOptions, custom);
    options.form = $.extend(defaultOptions.form, custom.form);
    var form = $('form.le_form', container);
        form.attr('method', options.form.method);
        form.attr('action', options.form.action);
        form.prepend($('<input type="hidden" name="chat"/>').val(options.chat));
        form.prepend($('<input type="hidden" name="message"/>').val(options.message));
        form.prepend($('<input type="hidden" name="container_id"/>').val(options.container));
        form.submit(function () {
            $.php($(this).attr('action'), $(this).formToArray());
            return false;
        });
    $("input[@name=pattern]", container).val(options.pattern);
    $("input[@name=answer]", container).val(options.reply);
    $(this).empty().append(container);
    return this;
};
// }}}

// {{{ РАСШИРЕНИЯ jQuery-PHP

/**
 * Обработка js-ошибок (отправка ошибки на сервер и показ сообщения пользователю)
 */
php.error = function (xmlEr, typeEr, except) {
    var errId = '#' + parseInt(Math.random() * 1000000);

    php.errorPopup(_("Упс! Произошла ошибка")+" (" + errId + "). "+_("Мы с этим уже разбираемся."));
}

php.errorPopup = function(message) {
    $('#iii-error').remove();

    $(document.body).append('<div id="iii-error">' + message + '</div>');

    var timer = setTimeout(function() {$('#iii-error').fadeOut('slow', function() {$(this).remove();})}, 3000);

    $('#iii-error').css({
        position: 'fixed',
        top: 0,
        right: 0,
        width: '200px',
        minHeight: '30px',
        background: '#ff8282',
        border: '5px red solid',
        fontFamily: 'sans-serif',
        fontSize: '8pt',
        padding: '5px',
        cursor: 'pointer',
        borderRadius: '10px',
        '-moz-border-radius': '10px',
        '-webkit-border-radius': '10px'
    }).attr('title', _('Закрыть')).click(function() {clearTimeout(timer);$(this).remove()});
}

php.messagePopup = function(message) {
    php.errorPopup(message);
    $('#iii-error').css({
        background: '#82ff82',
        border: '5px green solid'
    });
}
// }}}

/**
 * Устанавливает таймер на элемент
 */
jQuery.fn.wait = function(time, type)
{
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            $(self).dequeue();
        }, time);
    });
};

/**
 * Кроссбраузерное определение текущего значения скроллинга окна браузера
 *
 * @see http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
 * @return int
 */
function getScrollPosition() {
    var n_result = window.pageYOffset ? window.pageYOffset : 0;
    var n_docel = document.documentElement ? document.documentElement.scrollTop : 0;
    var n_body = document.body ? document.body.scrollTop : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function urlencode (str) {
    // URL-encodes string
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/urlencode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str+'').toString();

    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str)
                .replace(/!/g, '%21')
                .replace(/'/g, '%27')
                .replace(/\(/g, '%28')
                .replace(/\)/g, '%29')
                .replace(/\*/g, '%2A')
                .replace(/%20/g, '+');
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'

    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}

IiiPopup = function(msg, options) {
    return new IiiPopup.prototype.init(msg, options);
};
IiiPopup.prototype = {
    container: null,
    defaults: {
        top: '25%',
        persistent: false,
        buttons: {}
    },
    init: function(msg, options) {
        if (typeof msg == 'object') {
            options = msg;
            msg = options.msg;
            delete options.msg;
        }
        msg = msg || '';
        options = $.extend({}, this.defaults, options);
        var callback = options.callback;
        options.callback = function(val, msg, form) {
            IiiPopup.prototype._unbindHandlers();
            if (callback) {
                callback(val, msg, form);
            }
        }
        this.container = $.prompt(msg, options).find('.jqimessage');
        $(document).bind('keypress', this._keypressHandler);
        if (!options.persistent) {
            $('#jqifade').bind('click', IiiPopup.prototype._unbindHandlers);
        }
    },
    _keypressHandler: function(event) {
        if (event.keyCode == 27) {
            $('.jqiclose').filter(':last:visible').click();
        }
    },
    _unbindHandlers: function() {
        if ($('.jqibox').length == 1) {
            $(document).unbind('keypress', IiiPopup.prototype._keypressHandler);
        }
    },
    html: function(html) {
        this.container.html(html);
        return this;
    },
    load: function(url, params, complete) {
        var self = this.showLoading();
        $.ajax({
            url: url,
            data: params,
            complete: function(xhr, status) {
                self.html(status == 'success' ? xhr.responseText : '<h1>' + _('Ошибка') + '</h1>');
                if (complete) {
                    complete(xhr, status);
                }
                self.checkPosition();
            }
        });
        return this;
    },
    showLoading: function() {
        return this.html('<img src="/i/loading.gif" width="16" height="16" alt="'+_('Загрузка...')+'" />');
    },
    checkPosition: function() {
        var jqi = $('#jqi');
        var dh = $(window).height() - jqi.position().top - jqi.innerHeight();
        if (dh < 0) {
            jqi.css('marginTop', $(document).scrollTop());
            $('#jqibox').css('position', 'absolute');
            $('#jqifade').css('position', 'fixed');
            var self = this;
            $(window).one('resize', function() {
                jqi.hide();
                setTimeout(function() {
                    jqi.css('marginTop', 0).show();
                    self.checkPosition();
                }, 1);
            });
        }
    },
    close: function() {
        IiiPopup.prototype._unbindHandlers();
        $.prompt.close();
    }
};
IiiPopup.prototype.init.prototype = IiiPopup.prototype;

IiiNutsPopup = {
    open: function() {
        var html = '<img src="/i/nuts/popup.png" width="658" height="480" alt="" usemap="#nutspopup" />'
                 + '<map name="nutspopup"><area shape="rect" coords="588,47,610,70" href="#" onclick="$.prompt.close(); return false;" />'
                 + '<area shape="rect" coords="87,369,310,397" href="http://nuts4you.ru" /></map>';
        $.prompt(html, {
            persistent: false,
            classes: 'nuts-popup',
            buttons: {}
        });
    }
};

IiiPayment = {
    init: function() {
        $('#payment-country').change(function() {
            IiiPayment.showLoading();
            $.ajax({
                url: '/payment/form-select-operator/',
                data: 'country=' + $(this).val(),
                complete: function(xhr) {
                    var html = xhr.responseText || '';
                    $('#payment-operator-box').html(html);
                    IiiPayment.initSelectOperator();
                    $('#payment-operator').change();
                }
            });
        });
        this.initSelectOperator();
        this.initControlRate();
    },
    initSelectOperator: function() {
        $('#payment-operator').change(function() {
            IiiPayment.showLoading();
            $.ajax({
                url: '/payment/form-control-rate/',
                data: 'operator=' + $(this).val(),
                complete: function(xhr) {
                    var html = xhr.responseText || '';
                    var ratebox = $('#payment-rate-box');
                    var items = ratebox.html(html).children('label');
                    if (items.length > 0) {
                        IiiPayment.initControlRate();
                        items.filter('.selected').click();
                        $('li', '#payment').not(':first').css('visibility', 'visible');
                    } else {
                        $('li', '#payment').not(':first').css('visibility', 'hidden');
                    }
                    IiiPayment.hideLoading();
                }
            });
        });
    },
    initControlRate: function() {
        $('label', '#payment-rate-box').click(function() {
            var self = $(this);
            $('label', '#payment-rate-box').removeClass('selected');
            self.addClass('selected');
            $('#payment-number').html(self.attr('number'));
            $('#payment-cost').html(self.attr('cost'));
        });
    },
    open: function(submit) {
        var html = '<img id="payment-loading-icon" src="/i/loading.gif" width="16" height="16" alt="'+_('Загрузка...')+'" />';
        $.prompt(html, {
            top: '20%',
            persistent: false,
            classes: 'payment-popup',
            submit: submit || function() {},
            buttons: submit ? JSON.parse('{ "'+_('SMS-уведомление получено')+'": true }') : {}
        });
        $.ajax({
            url: '/payment/',
            complete: function(xhr) {
                var html = xhr.responseText || '<h1>' + _('Ошибка') + '</h1>';
                $('.jqimessage', '.payment-popup').html(html);
                $('#payment-loading-fade').height($('#jqi').innerHeight());
            }
        });
    },
    showLoading: function() {
        $('select, input', '#payment').attr('disabled', true);
        $('#payment-loading-fade').show();
        $('#payment-loading-icon').show();
    },
    hideLoading: function() {
        $('select, input', '#payment').attr('disabled', false);
        $('#payment-loading-fade').hide();
        $('#payment-loading-icon').hide();
    }
};


/** /js/common.js */

function zoom(el) {
    $('#' + el).slideToggle(300);
}

