var clientPC = navigator.userAgent.toLowerCase();
var clientVer = parseInt(navigator.appVersion);
var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);



/**
 *
 */
var cfg_path_web;
var cfg_site_theme;




/**
 *
 */
function setPopuperText(text)
{
	if (text) {
		jQuery('#popuper_text').html(text);
	} else {
		jQuery('#popuper_text').html('выполняется...');
	}
}
function enablePopuperIndicator(indicator_on) {
	if (indicator_on > 0) {
		jQuery('#popuper_indicator').css({display: 'block'});
	} else {
		jQuery('#popuper_indicator').css({display: 'none'});
	}
}

function calculatePopuperTop() {
	top_margin = (jQuery('body').height() / 2) - (jQuery('.popuper').height() / 2);
	if (top_margin < 15) {
		top_margin = 15;
	}
	top_margin = top_margin + document.body.scrollTop;
	return(top_margin);
}
function viewPopuper(text, indicator_on)
{
	jQuery('.blackBack').css({display: 'block'});
	
	setPopuperText(text);
	enablePopuperIndicator(indicator_on);
	
	jQuery('.popuper').fadeIn('fast');
	
	jQuery('.popuper').css({top: calculatePopuperTop()});
	
	jQuery('#popuper iframe').width(jQuery('#popuper table.table').width());
	jQuery('#popuper iframe').height(jQuery('#popuper table.table').height());
	jQuery('#popuper iframe').css({display: 'block'});
	
	jQuery(window).scroll(function () {
		jQuery('.popuper').css({top: calculatePopuperTop()});
	});
}
function hidePopuper() {
	jQuery('.popuper').fadeOut('fast');
	jQuery('.blackBack').fadeOut('fast');
}

/**
 *
 */
function putString(context, str){
	var m=document.getElementById(context);
	if(m){
		if(document.selection){
			m.focus();
			sel=document.selection.createRange();
			sel.text=str;
		}else if(m.selectionStart || m.selectionStart=="0"){
			var s=m.selectionStart;
			var e=m.selectionEnd;
			m.value=m.value.substring(0,s)+str+m.value.substring(e,m.value.length);
		}else{
			m.value += str;
		}
		m.focus();
	}
}

function putURL(context)
{
	if(url=prompt('Введите ссылку','http://'))
	{
		var m=document.getElementById(context);
		if(m){
			m.focus();
			if((clientVer >= 4) && is_ie && is_win)
			{
				sel = document.selection.createRange();
				if(sel.text!='') {
					sel.text = '<a href="'+url+'">'+sel.text+'</a>';
				}
				else {
					putString(context, '<a href="'+url+'">'+url+'</a>');
				}
			}
			else {
				mozWrap(m, '<a href="'+url+'">','</a>', url);
			}
			m.focus();
		}
	}
}

/* Это больше не нужно для нового редактора */
/*
function putTag(context, tag)
{
	var m=document.getElementById(context);
	if(m){
		m.focus();
		if ((clientVer >= 4) && is_ie && is_win)
		{
			sel = document.selection.createRange();
			sel.text = '<'+tag+'>'+sel.text+'</'+tag+'>';
		}
		else {
			mozWrap(m, '<'+tag+'>', '</'+tag+'>');
		}
		m.focus();
	}
}

function mozWrap(txtarea, open, close, somevalue)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2) {
		selEnd = selLength;
	}

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	if (s2!='') {
		txtarea.value = s1 + open + s2 + close + s3;
	}
	else {
		if(somevalue) txtarea.value = s1 + open + somevalue + close + s3;
	}
	return;
}
*/
/*  /Это больше не нужно для нового редактора */

/* А это необходимо для нового редактора  ;)*/
/**
* bbCode control by subBlue design [ www.subBlue.com ]
* Includes unixsafe colour palette selector by SHS`
*/
/**/

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf('msie') != -1) && (clientPC.indexOf('opera') == -1));
var is_win = ((clientPC.indexOf('win') != -1) || (clientPC.indexOf('16bit') != -1));

var baseHeight;
//onload_functions.push('initInsertions()');

/**
* Shows the help messages in the helpline window
*/
function helpline(help)
{
	document.forms[form_name].helpbox.value = help_line[help];
}

/**
* Apply bbcodes
*/
function bbfontstyle(bbopen, bbclose)
{
	theSelection = false;

	var textarea = document.forms[form_name].elements[text_name];

	textarea.focus();

	if ((clientVer >= 4) && is_ie && is_win)
	{
		// Get text selection
		theSelection = document.selection.createRange().text;

		if (theSelection)
		{
			// Add tags around selection
			document.selection.createRange().text = bbopen + theSelection + bbclose;
			document.forms[form_name].elements[text_name].focus();
			theSelection = '';
			return;
		}
	}
	else if (document.forms[form_name].elements[text_name].selectionEnd && (document.forms[form_name].elements[text_name].selectionEnd - document.forms[form_name].elements[text_name].selectionStart > 0))
	{
		mozWrap(document.forms[form_name].elements[text_name], bbopen, bbclose);
		document.forms[form_name].elements[text_name].focus();
		theSelection = '';
		return;
	}
	
	//The new position for the cursor after adding the bbcode
	var caret_pos = getCaretPosition(textarea).start;
	var new_pos = caret_pos + bbopen.length;		

	// Open tag
	insert_text(bbopen + bbclose);

	// Center the cursor when we don't have a selection
	// Gecko and proper browsers
	if (!isNaN(textarea.selectionStart))
	{
		textarea.selectionStart = new_pos;
		textarea.selectionEnd = new_pos;
	}	
	// IE
	else if (document.selection)
	{
		var range = textarea.createTextRange(); 
		range.move("character", new_pos); 
		range.select();
		storeCaret(textarea);
	}

	textarea.focus();
	return;
}

/**
* Insert text at position
*/
function insert_text(text, spaces, popup)
{
	var textarea;
	
	if (!popup) 
	{
		textarea = document.forms[form_name].elements[text_name];
	} 
	else 
	{
		textarea = opener.document.forms[form_name].elements[text_name];
	}
	if (spaces) 
	{
		text = '' + text + '';
	}
	
	if (!isNaN(textarea.selectionStart))
	{
		var sel_start = textarea.selectionStart;
		var sel_end = textarea.selectionEnd;

		mozWrap(textarea, text, '')
		textarea.selectionStart = sel_start + text.length;
		textarea.selectionEnd = sel_end + text.length;
	}
	else if (textarea.createTextRange && textarea.caretPos)
	{
		if (baseHeight != textarea.caretPos.boundingHeight) 
		{
			textarea.focus();
			storeCaret(textarea);
		}

		var caret_pos = textarea.caretPos;
		caret_pos.text = caret_pos.text.charAt(caret_pos.text.length - 1) == ' ' ? caret_pos.text + text + ' ' : caret_pos.text + text;
	}
	else
	{
		textarea.value = textarea.value + text;
	}
	if (!popup) 
	{
		textarea.focus();
	}
}

/**
* From http://www.massless.org/mozedit/
*/
/**/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	var scrollTop = txtarea.scrollTop;

	if (selEnd == 1 || selEnd == 2) 
	{
		selEnd = selLength;
	}

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);

	txtarea.value = s1 + open + s2 + close + s3;
	txtarea.selectionStart = selEnd + open.length + close.length;
	txtarea.selectionEnd = txtarea.selectionStart;
	txtarea.focus();
	txtarea.scrollTop = scrollTop;

	return;
}

/**
* Insert at Caret position. Code from
* http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
*/
function storeCaret(textEl)
{
	if (textEl.createTextRange)
	{
		textEl.caretPos = document.selection.createRange().duplicate();
	}
}

/**
* Color pallette
*/
/*
function colorPalette(dir, width, height)
{
	var r = 0, g = 0, b = 0;
	var numberList = new Array(6);
	var color = '';

	numberList[0] = '00';
	numberList[1] = '40';
	numberList[2] = '80';
	numberList[3] = 'BF';
	numberList[4] = 'FF';

	document.writeln('<table cellspacing="1" cellpadding="0" border="0">');

	for (r = 0; r < 5; r++)
	{
		if (dir == 'h')
		{
			document.writeln('<tr>');
		}

		for (g = 0; g < 5; g++)
		{
			if (dir == 'v')
			{
				document.writeln('<tr>');
			}
			
			for (b = 0; b < 5; b++)
			{
				color = String(numberList[r]) + String(numberList[g]) + String(numberList[b]);
				document.write('<td bgcolor="#' + color + '" border="0" width: ' + width + 'px; height: ' + height + 'px;">');
				document.write('<a class="btn" href="#" onclick="bbfontstyle(\'<font color=#' + color + '>\', \'</font>\'); return false;"><img src="http://football66.ru/themes/default/images/editor-buttons/spacer.gif" width="' + width + '" height="' + height + '" alt="#' + color + '" title="#' + color + '" /></a>');
				document.writeln('</td>');
			}

			if (dir == 'v')
			{
				document.writeln('</tr>');
			}
		}

		if (dir == 'h')
		{
			document.writeln('</tr>');
		}
	}
	document.writeln('</table>');
}
*/

/**
* Caret Position object
*/
function caretPosition()
{
	var start = null;
	var end = null;
}


/**
* Get the caret position in an textarea
*/
function getCaretPosition(txtarea)
{
	var caretPos = new caretPosition();
	
	// simple Gecko/Opera way
	if(txtarea.selectionStart || txtarea.selectionStart == 0)
	{
		caretPos.start = txtarea.selectionStart;
		caretPos.end = txtarea.selectionEnd;
	}
	// dirty and slow IE way
	else if(document.selection)
	{
	
		// get current selection
		var range = document.selection.createRange();

		// a new selection of the whole textarea
		var range_all = document.body.createTextRange();
		range_all.moveToElementText(txtarea);
		
		// calculate selection start point by moving beginning of range_all to beginning of range
		var sel_start;
		for (sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start++)
		{		
			range_all.moveStart('character', 1);
		}
	
		txtarea.sel_start = sel_start;
	
		// we ignore the end value for IE, this is already dirty enough and we don't need it
		caretPos.start = txtarea.sel_start;
		caretPos.end = txtarea.sel_start;			
	}

	return caretPos;
}

/**
* Add quote text to message
*/
if (document.selection||document.getSelection||window.getSelection) {Q=true} else {var Q=false}
var txt=''
function copyQ() {
        txt=''
        if (window.getSelection&&!window.opera) txt = window.getSelection() 
        else if (document.getSelection) txt=document.getSelection()
        else if (document.selection) txt=document.selection.createRange().text
        txt='<blockquote>'+txt+'</blockquote>'
}

function insertAtCaret(tObj,textV){    
    textV=textV.replace(/\s\[\?\]/g,'')
    if (textV==''||!tObj) return
    var ver=8
    if(document.all && !window.opera){
      if (tObj.createTextRange&&tObj.caretPos) {
          var caretPos=tObj.caretPos
          caretPos.text=textV
        }else tObj.value+= textV
        }else
        {var brows=navigator.userAgent.toString()
         var scrollTop, scrollLeft
         if (tObj.type=='textarea'&&tObj.scrollTop)
         {scrollTop=tObj.scrollTop;scrollLeft=tObj.scrollLeft}                
          if(brows.search(/opera\/?(\d*.\d*)/i)!=-1) ver=RegExp.$1 
          if(tObj.selectionStart>=0&&ver>=8){
          if(tObj.textLength!=undefined||tObj.value.length!=undefined) 
           {var selLength=tObj.textLength!=undefined?tObj.textLength:tObj.value.length 
            var selStart=tObj.selectionStart
            var selEnd=tObj.selectionEnd 
            if (selEnd==1||selEnd==2)selEnd=selLength  
            var s1=(tObj.value).substring(0,selStart) 
            var s2=(tObj.value).substring(selEnd,selLength)
            tObj.value=s1+textV+s2
            tObj.setSelectionRange(selStart+textV.length,selStart+textV.length) 
            } 
            if (typeof scrollTop != 'undefined')
            {tObj.scrollTop=scrollTop;tObj.scrollLeft=scrollLeft}
           }else tObj.value+=textV
        }
}
function pasteQ(){
    if (txt!='' && document.getElementById('topic_text'))
    insertAtCaret(document.getElementById("topic_text"),txt)
}

function pastecommentQ(){
    if (txt!='' && document.getElementById('comment_textarea'))
    insertAtCaret(document.getElementById("comment_textarea"),txt)
}

/* Комментарий 
******************************/
function gebi(gid) { return document.getElementById(gid); }

//addEvent(window, 'load', displayReplyForm);
//addEvent(document, 'dblclick', displayDefaultReplyForm);

// инициализация формы (вызывается сразу после html самой формы)
/***/
function initReplyForm(){
	//replyForm = $('reply_form');	
	replyForm = gebi('reply_form');
	if(!replyForm) return;

	replyForm.replyto = gebi('replyto');
	replyForm.comment = gebi('comment_textarea');
	replyForm.style.display = 'blok';

	replyForm.onclick = function(e){
		if(!e) e=window.event;	
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();	
	}
} 

/***/
// обработчик кнопки 'ответить'
/***/
function commentIt(e, reply_link, user_link, comment_id){
  //alert('commentIt ok!')
	if(!e) e = window.event;	
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();	

	if(typeof replyForm == 'undefined') {
		return false;
	} else {
		return displayInPlaceReplyForm(reply_link, user_link, comment_id);		
	}
}


function displayInPlaceReplyForm(replyLink, userlink, comment_id){
	replyLink.blur();
	whereShowBox = replyLink.parentNode.parentNode.parentNode.parentNode.parentNode;
	whereShowBox.appendChild (replyForm);
	//replyForm.replyto.value = whereShowBox.parentNode.getAttribute('id');
	replyForm.replyto.value = comment_id;
	
  //replyForm.comment.value = '';
	//if(userlink){
	//	replyForm.comment.value = '<b>' + userlink + '</b>, ' + replyForm.comment.value;
	//}
	
	if (gebi('reply_link_default')) {
		gebi('reply_link_default').style.display = 'block';
	}
	replyForm.style.display = "block";
	replyForm.comment.focus();
	
	return false;
}

/*  /А это необходимо для нового редактора  ;)*/

/**
 *
 */
function nlToBr(text) {
	return text.replace(/(\r\n)|(\n)/g, "<br>");
}



/**
 *
 */
function preview(area_id, text)
{
	jQuery('#'+area_id).html('<div style="width: 100%; padding-top: 10px">'+text+'</div>');
	jQuery('#'+area_id).slideToggle();
}

function closePreview(area_id) {
	jQuery('#'+area_id).slideToggle();
}



/**
 *
 */
function printMessages(aMessages)
{
	if (aMessages.length > 0)
	{
		var mess_ul = jQuery('<ul></ul>');
		
		
		for (var i = 0; i < aMessages.length; i++)
		{
			var message_title = '';
			if (aMessages[i].is_error)
			{
				if (aMessages[i].title) {
					message_title = aMessages[i].title;
				} else {
					message_title = 'Ошибка:';
				}
				var mess_span = jQuery('<span>' + message_title + ' </span>').addClass('red');
			} else {
				if (aMessages[i].title) {
					var mess_span = jQuery('<span>' + aMessages[i].title + ' </span>').addClass('green');
				} 
			}
			if (mess_span) {
				mess_span.appendTo(mess_li);
			}
			
			var mess_span = jQuery('<span>' + aMessages[i].text + '</span>');
			var mess_li = jQuery('<li></li>');
			
			mess_span.appendTo(mess_li);
			mess_li.appendTo(mess_ul);
			
		}
		jQuery("#system_messages").html('');
		mess_ul.appendTo("#system_messages");
		jQuery('#system_messages').css({display: 'block'});		
	}
}
