function DoConfirmForm(q) {
	if (q == null) {
		var agree=confirm('Вы уверены что хотите удалить комментарий?');
	} else {
		var agree=confirm(q);
	}
		
	if (agree) return true ;
	else return false ;
}

function DoConfirmDeleteVideo() {
	var agree=confirm('Вы уверены что хотите удалить свой видеоклип из очереди на модерацию?');
	if (agree) return true ;
	else return false ;
}

function show(el) {
	var eel = document.getElementById(el);
	if (eel != null) {
		if (eel.style.display) { 
			eel.style.display = '';
		} else { 
			eel.style.display = 'none';
		}
	}
}

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

var noHref = 0;
function hrefCode(url) {
	if (!noHref) {
		window.location.href = url;
	} else {
		noHref = 0;
	}
}

function insertAtCursor(myField, myValue) {
	textAreaScrollPosition = myField.scrollTop;
	//IE support
	if (document.selection) {
		myField.focus();

		//in effect we are creating a text range with zero
		//length at the cursor location and replacing it
		//with myValue
		sel = document.selection.createRange();
		sel.text = myValue;

	//Mozilla/Firefox/Netscape 7+ support
	} else if (myField.selectionStart || myField.selectionStart == '0') {

		myField.focus();
		//Here we get the start and end points of the
		//selection. Then we create substrings up to the
		//start of the selection and from the end point
		//of the selection to the end of the field value.
		//Then we concatenate the first substring, myValue,
		//and the second substring to get the new value.
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
		myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
	} else {
		myField.value += myValue;
	}
	myField.scrollTop = textAreaScrollPosition;
}

function smile (icon)
{
	var txtarea = document.getElementById('text');
	insertAtCursor(txtarea, ' ::' + icon + ':: ');
	txtarea.focus();
}

function mozWrap(txtarea, open, close)
{
	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);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

function bbcode (icon)
{
	var txtarea = document.sendmessage.text;
	var theSelection = false;
	
	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));
	txtarea.focus();
	
	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			document.selection.createRange().text = '<' + icon + '>' + theSelection + '</' + icon + '>';
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, '<' + icon + '>', '</' + icon + '>');
		return;
	}

	txtarea.value = txtarea.value + '<' + icon + '>' + '</' + icon + '>';
	txtarea.focus();
}

function citate (name)
{
	document.sendmessage.text.value = document.sendmessage.text.value + ' <b>' + name + '</b>, ';
	document.sendmessage.text.focus();
}

function checkAll(oForm, cbName, checked)
{
	for (var i=0; i < oForm[cbName].length; i++) 
		oForm[cbName][i].checked = checked;
}

var selectionStore = false; // Selection data

function emoticon_wospaces_news(text) {
	var txtarea = document.sendmessage.text;
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

// Catching selection
function catchSelectionNews()
{
	if (window.getSelection)
	{
		selectionStore = window.getSelection().toString();
	}
	else if (document.getSelection)
	{
		selectionStore = document.getSelection();
	}
	else if (document.selection)
	{
		selectionStore = document.selection.createRange().text;
	}
}

// Чистит комменты от BlockQuote
function cleanOtherQuotes(str)
{
	var s = String(str);
	var clientPC = navigator.userAgent.toLowerCase(); // Get client info
	var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
	// Цитаты
	s = s.replace(/<blockquote(.|\s)*?<\/blockquote>/ig, "");
	// Смайлы
	s = s.replace(/<img src=\"images\/smiles\/(\d+)\.gif\" border=\"0\">/ig, "::$1::");
	// Концы строк
	if (is_ie)
		s = s.replace(/<br\s*\/?>/img, "\n");
	else
		s = s.replace(/<br\s*\/?>/img, "");
	return s
}

// Putting selection to the post box
function quoteSelectionNews(name, divName)
{
	if (selectionStore)
	{
		var str = selectionStore;
		emoticon_wospaces_news('[quote="'+name+'"]' + str + '[/quote]\n'); 
		selectionStore = '';
		document.sendmessage.text.focus(); 
		return; 
	}
	else if (divName != '')
	{
		var str = cleanOtherQuotes(document.getElementById(divName).innerHTML);
		emoticon_wospaces_news('[quote="'+name+'"]' + str + '[/quote]\n'); 
		document.sendmessage.text.focus(); 
		return; 
	}
	else
	{ 
		alert('Выделите текст на странице и попробуйте ещё раз');
		return; 
	} 
}

var requestAMVNews;
var destAMVNews;
var callURL;

function processStateChange()
{
	if (requestAMVNews.readyState == 4)
	{
		contentDiv = document.getElementById(destAMVNews);
		if (requestAMVNews.status == 200)
		{
			response = requestAMVNews.responseText;
			contentDiv.innerHTML = response;	
		}
		else
		{
			contentDiv.innerHTML = "Error: Status "+requestAMVNews.status;
		}
	}
}

function getNewHTTPObject()
{
        var xmlhttp;

        /** Special IE only code ... */
        /*@cc_on
          @if (@_jscript_version >= 5)
              try
              {
                  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch (e)
              {
                  try
                  {
                      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (E)
                  {
                      xmlhttp = false;
                  }
             }
          @else
             xmlhttp = false;
        @end @*/

        /** Every other browser on the planet */
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
        {
            try
            {
                xmlhttp = new XMLHttpRequest();
            }
            catch (e)
            {
                xmlhttp = false;
            }
        }

        return xmlhttp;
}

function loadHTML(URL, destination)
{
	destAMVNews = destination;
	requestAMVNews = getNewHTTPObject();
	if (requestAMVNews)
	{
		requestAMVNews.onreadystatechange = processStateChange;
		requestAMVNews.open("GET", URL, true);
		requestAMVNews.send(null);
	}
}

function vote_comment(bal, type, pn, id)
{
	callURL = '/index.php?go='+type+'&file=vote_comment&id='+id+'&bal='+bal;
	divID = 'comment-vote-'+pn+'-'+id;
	loadHTML(callURL, divID);
	//$('#'+divID).load(callURL);
}

function vote_ocen(bal, id)
{
	var el;
	callURL = '/index.php?go=Files&file=vocen&id='+id+'&bal='+bal;
	loadHTML(callURL, 'voteres');
	el = document.getElementById('voteyes');
	el.innerHTML = '';
	el = document.getElementById('voteno');
	el.innerHTML = '';
	//$('#'+divID).load(callURL);
}

var JWplayer = null;
var JWcurrentPosition  = 0;
var JWpreviousPosition = 0;
var JWtotalPlayed = 0;
var JWcurrentVideoID = 0;
var JWskippedVideo = 0;

function playerReady( obj )
{
	JWplayer = document.getElementById( obj.id );
	JWplayer.addModelListener('STATE', 'stateMonitor');
	JWplayer.addModelListener('TIME', 'timeMonitor');
	JWplayer.addControllerListener('ITEM', 'outputPlayListItemInfo');
	JWtotalPlayed = 0;
	JWskippedVideo = 0;
	var s = String(obj.id);
	s = s.replace(/player/ig, "");
	JWcurrentVideoID = s;
};

function stateMonitor( obj )
{
	if (obj.newstate == "COMPLETED")
	{
	}
	if (obj.newstate == "IDLE")
	{
		JWtotalPlayed = 0;
		JWskippedVideo = 0;
	}
};

function timeMonitor(obj)
{
	if (JWtotalPlayed > 1000000)
	{
		return;
	}
	if (JWtotalPlayed > 30)
	{
		loadHTML('/index.php?go=Files&file=prevstat&id=' + JWcurrentVideoID + '&plmode=flash', 'fakedata');
		JWtotalPlayed = 2000000;
	}
	JWcurrentPosition = obj.position;
	if (JWpreviousPosition < JWcurrentPosition - .5)
	{
		JWskippedVideo += JWcurrentPosition - JWpreviousPosition;
	} else {
		JWtotalPlayed += JWcurrentPosition - JWpreviousPosition;
	}
	JWpreviousPosition = JWcurrentPosition;
};

function reloadPlayerContent (link, type) {
	if (JWplayer != null) {
		JWplayer.sendEvent('LOAD', link);
		var lnk1 = document.getElementById('preview-std');
		var lnk2 = document.getElementById('preview-hq');
		if (type == '0' && lnk1 != null && lnk2 != null) {
			lnk1.style.fontWeight = 'normal';
			lnk1.style.borderBottom = '1px dotted black';
			lnk2.style.fontWeight = 'bold';
			lnk2.style.borderBottom = '0px';
		}
		if (type == '4' && lnk1 != null && lnk2 != null) {
			lnk2.style.fontWeight = 'normal';
			lnk2.style.borderBottom = '1px dotted black';
			lnk1.style.fontWeight = 'bold';
			lnk1.style.borderBottom = '0px';
		}
	}
}

// Function for AJAX vote for videos
function GoForVideoVote(id, vote)
{
	if (vote == '0' || vote == '')
		return;
	callURL = '/index.php?go=Files&in=ajaxreiting&id='+id+'&vote='+vote;
	spanID = 'vote-text';
	loadHTML(callURL, spanID);
}

// Function for AJAX comments
function reloadComments(id, url, tp, count, page)
{
	callURL = '/ajax.php?type=comm&id='+ id +'&url='+ url +'&tp='+ tp +'&count=' + count + '&page=' + page;
	divID = 'comments-container';
	loadHTML(callURL, divID);
}

// Check if we should show HTML5 content to user
function isShowHTML5Test () {
	if (navigator.userAgent.indexOf("iPhone") != -1 || navigator.userAgent.indexOf("iPad") != -1 || navigator.userAgent.indexOf("Chrome") != -1 || 1) {
		return true;
	}
	return false;
}

// Check if we should show HTML5 content to user
function isShowHTML5 () {
	if (navigator.userAgent.indexOf("iPhone") != -1 || navigator.userAgent.indexOf("iPad") != -1) {
		return true;
	}
	return false;
}

// Resize player window
function resizeEmbed(width, height, bottom_menu_size, x) 
{
    var vid = document.getElementById(x);
	if (isShowHTML5())
	{
		vid.width = width;
		vid.height = height;
	} else {
		var ht2 = parseInt(height) + parseInt(bottom_menu_size);
		vid.setAttribute("width", width);
		vid.setAttribute("height", ht2);
	}
	callURL = '/ajax.php?type=save_videoplayer_state&size='+ width;
	divID = 'change-player-state-container';
	loadHTML(callURL, divID);
}

// Calculate time video played by HTML5 player
function timeMonitorHTML5(obj)
{
	if (JWtotalPlayed > 1000000.0) {
		return;
	}
	if (JWtotalPlayed > 30.0) {
		loadHTML('/index.php?go=Files&file=prevstat&id=' + JWcurrentVideoID + '&plmode=html5', 'fakedata');
		JWtotalPlayed = 2000000.0;
	}
	JWcurrentPosition = JWplayer.currentTime;
	if (JWpreviousPosition < JWcurrentPosition - .5)
	{
		JWskippedVideo += JWcurrentPosition - JWpreviousPosition;
	} else {
		JWtotalPlayed += JWcurrentPosition - JWpreviousPosition;
	}
	JWpreviousPosition = JWcurrentPosition;
}

// Check if HTML5 player loaded and ready to play
var initHTML5 = 0;
function checkHTML5PlayerReady(obj) {
	if (initHTML5 == 0) {
		var s = String(this.id);
		s = s.replace(/playercontainer/ig, "");
		JWcurrentVideoID = s;
		JWplayer = document.getElementById('player' + JWcurrentVideoID);
		if (JWplayer != null) {
			JWplayer.addEventListener('timeupdate', timeMonitorHTML5, false);
			JWtotalPlayed = 0.0;
			JWskippedVideo = 0.0;
			JWpreviousPosition = 0.0;
			JWcurrentPosition = 0.0;
			initHTML5 = 1;
		}
	}
}

// Load player for HTML5 browsers
function loadHTML5Player(div, id) 
{
	var containerHTML5 = document.getElementById(div);
	callURL = '/ajax.php?type=html5video&id='+ id;
	loadHTML(callURL, div);
	containerHTML5.addEventListener('mouseover', checkHTML5PlayerReady, false);
}

// Check HTML5 video support in browser
function supports_video() {
  return !!document.createElement('video').canPlayType;
}

// Check HTML5 video support for H264 in browser
function supports_h264_baseline_video() {
  if (!supports_video()) { return false; }
  var v = document.createElement("video");
  return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}

// Function for AJAX add to favorites
function addFavor(id, div)
{
	callURL = '/index.php?go=Files&in=addfav&id='+id;
	loadHTML(callURL, div);
	return false;
}

// Function for AJAX del from favorites
function delFavor(id, div)
{
	callURL = '/index.php?go=Files&in=delfav&id='+id;
	loadHTML(callURL, div);
	return false;
}

// Function switch HD
function switchHDForVideo(id, div)
{
	callURL = '/ajax.php?type=switchhd&id='+id;
	loadHTML(callURL, div);
	return false;
}

// EMBED Functions START

function printEmbedCodeString(emb) {
	var s = document.getElementById(emb);
	var h = embedCodeParamHeight + embedCodeParamMenu;
	var str;
	if (s == null)
		return;
	if (embedCodeParamStyle == 'iframe') {
		if (embedCodeParamMini == false) {
			str = '<p align="center"><iframe width="' + embedCodeParamWidth + '" height="' + h + '" src="http://amvnews.ru/index.php?go=Files&file=embed&id=' + embedCodeParamID + '" frameborder="0" allowfullscreen></iframe><BR><b><a href="http://amvnews.ru/index.php?go=Files&in=view&id=' + embedCodeParamID + '" target=_blank title="' + embedCodeParamTextForLinkTitle + '">' + embedCodeParamTitle + '</a></b></p>';
		} else {
			str = '<iframe width="' + embedCodeParamWidth + '" height="' + h + '" src="http://amvnews.ru/index.php?go=Files&file=embed&id=' + embedCodeParamID + '" frameborder="0" allowfullscreen></iframe>';
		}
	}
	else if (embedCodeParamStyle == 'embed') {
		if (embedCodeParamMini == false) {
			str = '<p align="center"><embed src="http://amvnews.ru/Video/SWF/v5/player.swf" width="' + embedCodeParamWidth + '" height="' + h + '" allowscriptaccess="always" allowfullscreen="true" flashvars="height=' + h + '&amp;width=' + embedCodeParamWidth + '&amp;file=http%3A%2F%2Famvnews.ru%2Findex.php%3Fgo%3DFiles%26file%3Dse%26id%3D' + embedCodeParamID + '&amp;backcolor=CCFFFF&amp;frontcolor=000000"><BR><b><a href="http://amvnews.ru/index.php?go=Files&in=view&id=' + embedCodeParamID + '" target=_blank title="' + embedCodeParamTextForLinkTitle + '">' + embedCodeParamTitle + '</a></b></p>';
		} else {
			str = '<embed src="http://amvnews.ru/Video/SWF/v5/player.swf" width="' + embedCodeParamWidth + '" height="' + h + '" allowscriptaccess="always" allowfullscreen="true" flashvars="height=' + h + '&amp;width=' + embedCodeParamWidth + '&amp;file=http%3A%2F%2Famvnews.ru%2Findex.php%3Fgo%3DFiles%26file%3Dse%26id%3D' + embedCodeParamID + '&amp;backcolor=CCFFFF&amp;frontcolor=000000">';
		}
	}
	else
		return;
	s.value = str;
}

function setEmbedParams (param, value) {
	if (param == 'width') {
		embedCodeParamWidth = parseInt(value);
	}
	if (param == 'height') {
		embedCodeParamHeight = parseInt(value);
	}
	if (param == 'style') {
		var obj = document.getElementById('use-flash-code');
		if (obj == null)
			return;
		if (obj.checked)
			embedCodeParamStyle = 'embed';
		else
			embedCodeParamStyle = 'iframe';
	}
	if (param == 'mini') {
		var obj = document.getElementById('use-minimized-code');
		if (obj == null)
			return;
		if (obj.checked)
			embedCodeParamMini = true;
		else
			embedCodeParamMini = false;
	}
	printEmbedCodeString('embed-code');
}

function setEmbedSizeState(num) {
	var obj;
	for (var i = 0; i < embedCodeParamSizeNumber; i++) {
		obj = document.getElementById('embed-code-size-' + i);
		if (obj != null)
			obj.className = 'embed-codes-size';
	}
	obj = document.getElementById('embed-code-size-' + num);
	if (obj != null)
		obj.className = 'embed-codes-size-selected';
}

// EMBED Functions END
