function InsertText(insTexte) {
	var startTag = '';
	var endTag = '';
	var input = document.getElementById('comment_area');

	if (!input)
		return false;

	input.value += startTag + insTexte + endTag;
	
	input.focus();
	
	return false;
}

function ImposeMaxLength(Object, MaxLen) {
	var bukv_remaining = MaxLen - Object.value.length;

	$('bukv').innerHTML = bukv_remaining;
	if (bukv_remaining < 50)
		$('bukv').style.color = '#f00';
	else
		$('bukv').style.color = '#000';

  return (Object.value.length <= MaxLen);
}

function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	} else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		} else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function draw_i_like(link) {
	var login = getCookie('l');

	if (! login) {
	}
}

function i_like(a) {
	a.outerHTML = a.innerHTML;

	new Ajax.Request(a.href);

	return false;
}

function i_dont_like(a) {
	new Ajax.Request(a.href);

	var subbar = getParentByTagName2(a, 'div');
	var content = $(subbar).previous();

	subbar.remove();
	content.remove();

	return false;
}

function removeParentByTagName2(el, tagName) {
	getParentByTagName(el, tagName).remove();
}

function getParentByTagName2(el, tagName) {
	if (el.parentNode.tagName == tagName.toUpperCase())
		return el.parentNode;
	else
		return getParentByTagName2(el.parentNode, tagName);
}

function comment_vote(a, summand, id) {
	//Голосовать могут только авторизованные пользователи
	var login = getCookie('l');

	if (! login) {
		alert('Голосовать могут только зарегистрированные пользователи!');
		return false;
	}
	
	element = $('respect_span' + id);
	if ("" == element.innerHTML)
		element.innerHTML = '(0)';
	
	summarize(element, summand);

	element = $('respect_div' + id);
	if ("" == element.innerHTML)
		element.innerHTML = '0';

	summarize(element, summand);

	//Проголосовать можно только один раз
	a.onclick = function() { return false; }
	$(a).siblings()[0].onclick = function() { return false; }

	new Ajax.Request(a.href);

	return false;
}

function summarize(element, summand) {
	var str = element.innerHTML;

	var reg = /[\-+]?\d+/
	var result = reg.exec(str);

	var oldrating = result[0];

	var rating = parseInt(oldrating) + summand;

	if (rating < 0)
		element.style.color = 'red';
	else {
		element.style.color = 'green';

		if (rating > 0)
			rating = '+' + rating;
	}

	if (! rating)
		element.innerHTML = '';
	else
		element.innerHTML = str.replace(reg, rating);
}

function remind_password(a) {
	new Ajax.Request(a.href, {
		onSuccess: function (transport) {
			alert(transport.responseText);
		}
	});

	return false;
}

function reload_paginator(link) {
	new Ajax.Request(link, {
		onSuccess: function (transport) {
			if (Prototype.Browser.IE) {
				var doc = new ActiveXObject("MSXML.DOMDocument");	
				doc.loadXML(transport.responseText);
				var nodeList = doc.selectNodes('//*[@id="paginator"]');
				
				newNode = nodeList[0].xml.replace(/xmlns=".*?"/,'');
				newNode = newNode.replace(/<([a-z]+)([^>]*?)\/>/g, '<$1$2></$1>');
				newNode = newNode.replace(/<br><\/br>/g, '<br>');

			} else {
				var newNode = transport.responseXML.getElementById('paginator');
				newNode = document.importNode(newNode, true);	
			}

			$('paginator').replace(newNode);
		}
	});

	return false;
}

var form_blocked = false;

function post_comment(form, action) {
	if (form_blocked)
		return false;

	if (form.elements['Comment[comment]'].value.length > 500) {
		alert('Комментарий не может быть длиннее 500 символов');
		return false;
	}

	if (form.elements['Comment[comment]'].value == '') {
		alert('Комментарий не может быть пустым');
		return false;
	}


	form_blocked = true;

	form.elements['Comment[submit]'].value = 'Подождите, идёт сохранение комментария...';
	$(form.elements['Comment[submit]']).disable();

	form.action = action;

	$(form).request({
		onSuccess: function(transport) {
			if (Prototype.Browser.IE) {
				var doc = new ActiveXObject("MSXML.DOMDocument");	
				doc.loadXML(transport.responseText);
				var nodeList = doc.selectNodes('//*[@id="comments"]');
				
				newNode = nodeList[0].xml.replace(/xmlns=".*?"/,'');
				newNode = newNode.replace(/<([a-z]+)([^>]*?)\/>/g, '<$1$2></$1>');
				newNode = newNode.replace(/<br><\/br>/g, '<br>');

			} else {
				var newNode = transport.responseXML.getElementById('comments');
				newNode = document.importNode(newNode, true);	
			}

			$('comments').replace(newNode);

			$(form.elements['Comment[comment]']).value = '';
			form_blocked = false;			
			$(form.elements['Comment[submit]']).value = 'Добавить';
			$(form.elements['Comment[submit]']).enable();
		}
	});

	return false;
}

function burn(frame) {
	if (5 == ++frame)
		frame = 0;

	$('logo_fire_container').style.backgroundPosition = (-frame*30 + 'px 0px');
	setTimeout("burn("+frame+")", 60);
}

// IE HACK: Define _importNode for IE since it doesnt support importNode
if (!document.ELEMENT_NODE) {
  document.ELEMENT_NODE = 1;
  document.ATTRIBUTE_NODE = 2;
  document.TEXT_NODE = 3;
  document.CDATA_SECTION_NODE = 4;
  document.ENTITY_REFERENCE_NODE = 5;
  document.ENTITY_NODE = 6;
  document.PROCESSING_INSTRUCTION_NODE = 7;
  document.COMMENT_NODE = 8;
  document.DOCUMENT_NODE = 9;
  document.DOCUMENT_TYPE_NODE = 10;
  document.DOCUMENT_FRAGMENT_NODE = 11;
  document.NOTATION_NODE = 12;
}

document._importNode = function(node, allChildren) {
  switch (node.nodeType) {
    case document.ELEMENT_NODE:
      var newNode = document.createElement(node.nodeName);
			/* does the node have any attributes to add? */
      for (var i = 0; i < node.attributes.length; i++)
        newNode.setAttribute(
					node.attributes[i].nodeName, 
					node.getAttribute(node.attributes[i].nodeName)
				);
      
				/* are we going after children too, and does the node have any? */
      if (allChildren && node.childNodes && node.childNodes.length > 0) 
        for (var i = 0; i < node.childNodes.length; i++) {
					impnode = document._importNode(node.childNodes[i], allChildren);
					try { 
						newNode.appendChild(impnode);	
					} catch (e) {}
				}
      
      return newNode;
      break;
    case document.TEXT_NODE:
    case document.CDATA_SECTION_NODE:
    case document.COMMENT_NODE:
      return document.createTextNode(node.nodeValue);
      break;
  }
};
// IE HACK (end)

function heap_send() {
	var minchars = 30;
	if ($('usercontent_textarea').value.length < minchars) {
		alert('Пожалуйста, отправьте нам что-нибудь подлиннее (больше ' + minchars + ' символов)');
		return false;
	}

	$('ajax_label').value = 1;

	$('UserContentForm').request({
		onSuccess: function (transport) {
			var pc = $(transport.responseXML).getElementsByTagName('tr')[0];//.getElementById('posted_content');
			var first_tr = $('heap_contents').getElementsByTagName('tr')[0];

			if (document.importNode)
				var imported_node = document.importNode(pc, true);
			else {
				if (pc.nodeType != document.ELEMENT_NODE)
 					 pc= pc.nextSibling;

				var imported_node = document._importNode(pc, true);
			}

			first_tr.parentNode.insertBefore(imported_node, first_tr);

			//парсим ссылки в только-что добавленном элементе
			$(imported_node).select('div.user-content').each(links_parser);

			$('UserContentForm').reset();
		},
		onFailure: function () {
			alert('Произошла какая-то фигня и ничего не добавилось!');
		}
	});

	return false;
}

function process_user_content() {
	$$('div.user-content').each(links_parser);
}

function links_parser(el) {
	var text = el.innerHTML;
	text = text.replace(/(^|[^\/])www\./g, "$1http://www.");

	//youtube
	/********
	text = text.replace(/http:\/\/www\.youtube\.com\/watch\?v=([^ &\n]+)/g,
		"<object width='425' height='344'><param name='movie' value='http://www.youtube.com/v/$1'></param><embed src='http://www.youtube.com/v/$1' type='application/x-shockwave-flash' width='425' height='344'></embed></object><br/>");
	*/
/*	
	text = text.replace(/http:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_.-]+)([^ \n]*)/g,
		"<div id='swf$1' class='for-swfobject'>Флеш-ролик</div>");
*/

	text = text.replace(/http:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_.-]+)([^ \n]*)/g,
		"<h2>Кликните по картинке для просмотра видео</h2><br/><div id='swf$1'><a id='link$1' href='#' onclick='replace_with_object(\"$1\");return false'><img src='http://i.ytimg.com/vi/$1/0.jpg' alt='youtube video'/></a></div>"
	);

	//pics
	text = text.replace(/(^|[^'])(https?):\/\/([a-zA-Z0-9.-]+)\/([^ \n\)]+)\.(jpg|jpeg|gif|png)/g, 
		"$1<a target='_blank' href='$2://$3/$4.$5'><img src='$2://$3/$4.$5' onload='resize_image(this)' alt='Кликните для полноэкранного просмотра'/></a>");

	text = text.replace(/(^|[^'])(https?|ftp):\/\/([a-zA-Z0-9.-]+)\/([^ \n\)]+)/g, 
		"$1<a target='_blank' href='$2://$3/$4'>$3/$4</a>");


	text = text.replace(/(^|[^'])(https?|ftp):\/\/([a-zA-Z0-9.-]+)([^ \n\)]*)/g, 
		"$1<a target='_blank' href='$2://$3$4'>$3$4</a>");

/*
		var arr = 0;
		var reg = /href='([^\/][^']+)'/g
		var link = '';
		var re_link = '';
		
		while (arr = reg.exec(text)) {
			link = arr[1];
			re_link = link.replace(/(\.|\?|\(|\)|\\)/g, "\\$1");
			text = text.replace(
				new RegExp("href='"+re_link+"'", "m"), 
				"href='/go/?link="+escape(link)+"'"
			);
		}
*/		
		//E-mail
	text = text.replace(/([a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+\.[a-z]{2,5})/g, 
		"<a href='mailto:$1'>$1</a>");

	el.innerHTML = text;
}

function replace_with_object(video_id) {
	//Втыкаем флеш там где надо
	var player_id = 'player' + video_id.replace(/[^a-zA-Z0-9]/,'');

	swfobject.embedSWF(
		"http://www.youtube.com/v/" + video_id+'?autoplay=1', 
		'swf'+video_id, 
		"425",
		"356",
		"8"
	);
}

function resize_image(img) {
	if (img.width > 600)
		img.width = 600;
}

function remove_from_heap(a, content_id) {
	new Ajax.Request(a.href + '?ajax=1');

	$('tr_uc_' + content_id).remove();
}

/**
* Удаляем все кнопки "мне понравилось, если пользователь не авторизован"
*/
Event.observe(window, 'load', function () {
	burn(3);
	$(document.documentElement).select('a.i-like').each(function(el) {
		if (! getCookie('l'))
			el.remove();
	});
	$(document.documentElement).select('div.vk_ifun_btn').each(function(el) {
		el.setStyle({
			clear: 'none'
		});
	});
	process_user_content();
});

