// Сообщение о том, что контент загружается
var log_loading_html = '<img src="/images/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:fixed;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});
	});
});*/
// }}}

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

$(document).ready(function () {
    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")'
                });
            }
        });
    }
});

// }}}

// {{{ Редактор логов
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 exObj = except ? except : false;
    var errId = '#' + parseInt(Math.random() * 1000000);

    var txt = xmlEr.responseText;
    if (typeof(xmlEr.responseText) == 'string') {
        txt = txt.substr(0, 2048);
    }
    var xml = xmlEr.responseXML;
    if (typeof(xmlEr.responseXML) == 'string') {
        xml = xml.substr(0, 2048);
    }
    var headers = null;
    if ('function' == typeof xmlEr['getAllResponseHeaders']) {
        headers = xmlEr.getAllResponseHeaders();
    }
    if ('function' == typeof xmlEr['getResponseHeader']) {
        if ("true" == xmlEr.getResponseHeader("X-Ganesha-ReloadOnError")) {
            window.location.reload();
        }
    }
    var error = {
        id: errId,
        location: window.location.href,
        browser: navigator.userAgent,
        type: typeEr,
        readyState: xmlEr.readyState,
        httpStatus: xmlEr.status,
        httpStatusText: xmlEr.statusText,
        requestUrl: $(document).data('.php.ajax.url'),
        requestParams: $(document).data('.php.ajax.params'),
        responseHeaders: headers,
        responseText: txt,
        responseXml: xml
    };
    if (exObj) {
        error.exception = {
            message: exObj.message,
            file: exObj.fileName,
            line: exObj.lineNumber
        }
    }

    $.ajax({
        url: '/jslogger.php',
        type: 'POST',
        global: false,
        processData: false,
        data: JSON.stringify(error)
    });
    
    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
/**
 * Перекрывает родительский элемент новым div'ом, в котором будет ссылка "закрыть", удаляющая его из документа.
 * 
 * @param string|element content Содержимое для нового div'а
 * @param [element] parent Необязательный указатель на родительский элемент
 * @param [object] custom Необязательный объект/массив со свойствами css, которые заменят значения по-умолчанию
 */
jQuery.fn.overlap = function (content, parent, custom) {
	var container = (parent == undefined) ? this : parent;
	custom = (undefined == custom ? {} : custom);

	var over = $('<div class="jquery_overlap" style="padding:5px;position:absolute;background:#eee;border:2px solid black;"></div>');
	var close = $('<a href="javascript:;" style="position:absolute; bottom: 5px; right: 5px;">закрыть</a>');
	close.click(function (event) {
		over.remove();
	});
	over.click(function () {
		close.css({
			bottom: '5px',
			right: '5px'
		});
	});
	var options = {
		top: custom.top ? custom.top : container.offset().top,
		left: custom.left ? custom.left : container.offset().left,
		width: custom.width ? custom.width : container.width(),
		height: custom.height ? custom.height : container.height(),
		overflow: 'hidden'
	};
	over.css($.extend(options, custom));
	if (typeof content == 'object') {
		over.append(content);
	} else {
		over.html(content);
	}
	over.append(close).appendTo('body');
	return over;
};

/**
 * Устанавливает таймер на элемент
 */
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;
}