/* COMMENT { */
function showCommentForm(formId)
{
    var els = getElementsByClass('comment_form');
    for (var i = 0; i  < els.length; i++)
    {
        els[i].className = 'comment_form hidden';
        els[i].getElementsByTagName('textarea')[0].value = '';
        document.getElementById('count_chars_' + formId).firstChild.nodeValue = '1000';
    }
    var target_el = document.getElementById('comment_form_' + formId);
    target_el.className = 'comment_form';
}

function hideCommentForm(formId)
{
    var target_el = document.getElementById('comment_form_' + formId);
    target_el.className = 'comment_form hidden';
}

function addComment(target_form, object_id, comment_id, parent_id, object_type_id, creator_id)
{
    if (object_type_id == 2 || object_type_id == 8 || creator_id == null)
    {
        creator_id = object_id;
    }
    $.get('ajax/xml_check_blocked/?userid=' + creator_id,
        function(data)
        {
            isBlocked = data.getElementsByTagName('is-blocked').item(0).firstChild.nodeValue;

    if (isBlocked == 1 )
    {
        showAlert(i18n['m1622']? i18n['m1622'] : 'You can not leave a comment because you were blocked by the user!');
    }
    else
    {
    var text = encodeURIComponent(target_form.comment_text.value);
    //alert(text)
    if (text.length == 0)
    {
        showAlert(i18n['m1618'] ? i18n['m1618'] : 'Please enter your comment!');
        return true;
    }
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange = function()
    {
        if (req.readyState == 4) 
        {
            if (req.status == 200) 
            {
                sendCommentList(object_id, 0, 10, object_type_id);
            }
        }
    } 
    req.open("post", "/ajax/add_comment/", true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send("object_id=" + object_id + "&text=" + text + "&comment_id=" + comment_id + "&parent_id=" + parent_id + "&object_type_id=" + object_type_id);
    return true;
    }
    });
}

function editComment(object_type, comment_id, object_id, text)
{
    if (text.length == 0)
    {
        showAlert(i18n['m1618'] ? i18n['m1618'] : 'Please enter your comment!');
        return false;
    }
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange = function()
    {
        if (req.readyState == 4) 
        {
            if (req.status == 200) 
            {
                sendCommentList(object_id, 0, 5, object_type);
            }
        }
    } 
    req.open('post', '/ajax/edit_comment/', true);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send('object_type=' + object_type + '&comment_id=' + comment_id + '&text=' + encodeURIComponent(text));
    return true;
}

function deleteComment(object_type,comment_id, object_id)
{
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange = function()
    {
        if (req.readyState == 4) 
        {
            if (req.status == 200) 
            {
                sendCommentList(object_id, 0, 5, object_type);
            }
        }
    } 
    req.open("post", "/ajax/delete_comment/", true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send("object_type=" + object_type + "&comment_id=" + comment_id);
}

function checkLength(target_el, formId, count_el)
{  
    var count_char_el = document.getElementById(count_el + formId);
    var count_chars = 1000-target_el.value.length;
    if(count_chars > 0)
    {
        count_char_el.firstChild.nodeValue = count_chars.toString();    
    }
    else
    {
        if (target_el.value.length > 1000)
        {
            target_el.value = target_el.value.substr(0, 1000);
        }
        count_char_el.firstChild.nodeValue = 0;    
    }
       
}

function setCharsCount(target_el_id, char_count_target)
{  
    var count_char_el = document.getElementById(target_el_id);
    remain_chars = (1000 - char_count_target.value.length).toString();
    count_char_el.firstChild.nodeValue = remain_chars;
    return true;
}

function checkRate(btn, target_form, video_id, comment_id, parent_id, object_id)
{
    var ratings = document.getElementById('video_ratings');
    if (ratings.isRate)
    {
        btn.disabled = true;
        addComment(target_form,video_id,comment_id,parent_id, object_id);
    }
    else
    {
        showAlert(i18n['m0526'] ? i18n['m0526'] : 'Please rate this video first.');
    }
}

function sendCommentList(object_id, pageNo, perPage, object_type_id)
{
    listEl = document.getElementById('comment_list');
    loadingMessage(listEl);
    var params = new Array(listEl, object_type_id);
    sendHTTPRequest('/ajax/xml_creator_comment_list/?object_id=' + object_id + '&pn=' + pageNo + '&pp=' + perPage + '&object_type_id=' + object_type_id, setCommentItemList, params);
}

function setCommentItemList(xml_http, params)
{
    params[0].innerHTML = '';
    params[0].innerHTML = xml_http.responseText;
    if(params[1] == 1)
    {
        comments_count = document.getElementById('com_count').firstChild.nodeValue;
        count_element = document.getElementById('video_comments_count');
        count_element.innerHTML = comments_count;
        setHeight('block_top', 'block_bottom', 'comments');    
    }
    if(params[1] == 2)
    {
        //setHeight('block_top', 'block_bottom', 'comments');
    }
}
/* } COMMENT */

/* MARK AS SPAM { */
function markAsSpam(spamEl, commentId, objectTypeId)
{
    spamEl.onclick = '';
    var params = new Array(spamEl, commentId);
    sendHTTPRequest('/ajax/comments_spam_report/?&comment_id=' + commentId + '&object_type_id=' + objectTypeId, setSpamStatus, params);
}

function setSpamStatus(xml_http, params)
{
    spamEl = params[0];
    formId = params[1];

    showAlert(i18n['m2118'] ? i18n['m2118'] : 'Your report has been successfully sent. We will review it shortly.');
    spamEl.parentNode.innerHTML = i18n['m2121'] ? i18n['m2121'] : 'Marked as spam';
    hideCommentForm(formId);
}
/* } MARK AS SPAM */

/* COMMENT VOTING { */
function voteComment(voteEl, commentId, objectTypeId, vote)
{
    els = voteEl.parentNode.parentNode.getElementsByTagName('a');
    for (i = 0; i < els.length; i++)
    {
        els[i].onclick = null;
        els[i].className = 'comment_vote_disable';
    }
    sendHTTPRequest('/ajax/comments_vote_comment/?&comment_id=' + commentId + '&object_type_id=' + objectTypeId + '&vote=' + vote, setVoteComment, commentId);
}

function setVoteComment(xml_http, commentId)
{
    var vote = xml_http.responseXML.getElementsByTagName('vote').item(0).firstChild.nodeValue;
    document.getElementById('comment_vote_' + commentId).firstChild.nodeValue = vote;
  
}
/* } COMMENT VOTING */

/* SUBSCRIBE { */
function sendSubscribe(subEl, creatorId, type)
{
    subEl.old = subEl.onclick;
    subEl.onclick = '';
    var params = new Array(subEl, type);
    sendHTTPRequest('/ajax/subscribe/?&creator_id=' + creatorId, setSubscribe, params);
}

function setSubscribe(xml_http, params)
{
    var isSubscribe = xml_http.responseXML.getElementsByTagName('is-subscribe').item(0).firstChild.nodeValue;
    if (isSubscribe == 0)
    {
        if(params[1] == 1)
        {
            showAlert(i18n['m1373']); //You were unsubscribed successfully!   
        }
        else
        {
            showAlert(i18n['m0522']); //You have unsubscribed from a channel with this video.
        }
        params[0].className = 'subscribe';
        params[0].firstChild.nodeValue = i18n['m0110']; //Subscribe
    }
    else
    {
        if(params[1] == 1)
        {
            showAlert(i18n['m1374']); //You were subscribed successfully   
        }
        else
        {
            showAlert(i18n['m0523']); //You have subscribed to a channel with this video.  
        }
        params[0].className = 'unsubscribe';
        params[0].firstChild.nodeValue = i18n['m0111']; // Unsubscribe
    }
    params[0].onclick = params[0].old;
}
/* } SUBSCRIBE */

/* RATE { */
function videoRate(starEl)
{
    var numCurrent = 0;
    var el = starEl.parentNode.firstChild;
    while (el)
	{
		if (el.nodeName.toLowerCase() == 'span')
		{
		    if (!window.timerStar)
            {
                el.oldClassName = el.className;
            }
            el.className = 'empty';
		}
        el = el.nextSibling;
	}
	clearTimeout(window.timerStar);
    el = starEl.parentNode.firstChild;
    while (el)
	{
		if (el.nodeName.toLowerCase() == 'span')
		{
		    numCurrent++;
			el.className = 'star';
            if (el == starEl)
            {
                break;
            }    
		} 
		el = el.nextSibling;
	}
    starEl.parentNode.userRate = numCurrent;
}

function restoreClass(starEl)
{
    window.timerStar = setTimeout(function(arg){return function(){ restoreClassST(arg); }}(starEl), 1000);
}

function restoreClassST(starEl)
{
   
    var el1 = starEl.parentNode.firstChild;
    while (el1)
	{
		if (el1.nodeName.toLowerCase() == 'span')
		{
            if (el1.oldClassName == null)
            {
                el1.oldClassName = 'empty';
            }
			el1.className = el1.oldClassName; 
		} 
		el1 = el1.nextSibling;
	}
}

function sendRate(starEl, videoId)
{
    var ratings = document.getElementById('video_ratings');
    if (ratings.isRate)
    {
        showAlert(i18n['m0174']); //You have already rated
    }
    else
    {
        var userRate = starEl.parentNode.userRate;
        sendHTTPRequest('index.php?service=videos&action=addrate&video_id=' + videoId + '&user_rate=' + userRate, setRate, userRate);
        showAlert(i18n['m0527'] + ' "' + userRate + '"'); //Thanks for rating! Your rate is
        ratings.isRate = 1;
    }
}

function setRate(xml_http, userRate)
{
    var rate = xml_http.responseXML.getElementsByTagName('rate').item(0).firstChild.nodeValue;
    var ratings = xml_http.responseXML.getElementsByTagName('ratings').item(0).firstChild.nodeValue;
    document.getElementById('video_ratings').firstChild.nodeValue = ratings;
    var els = getElementsByClass('stars');
    for (var i = 0; i < els.length; i++)
    {
        videoRate(els[i].getElementsByTagName('span')[userRate-1]);
    }
}
/* } RATE */

/* SHARE VIDEO AND CHANNEL { */
function requiredValidator(s, error)
{
    error = error ? error : i18n['m0763']; //Value is required
	switch (s.type)
	{
		case 'text':
		case 'textarea': 
			if(s.value.length == 0) 
			{
			    showAlert(error);
			    s.focus();
			    return false; 
			}
			break;
		case 'checkbox': 
			if (s.checked == false) 
			{
			    showAlert(error);
			    s.focus();
			    return false; 
			}
			break;
	}
	return true;
}

function regexpValidator(s, pattern, error)
{
	if (!pattern.test(s.value))
	{
	    error = error ? error : i18n['m0765']; //Missing format or contains illegal character
        showAlert(error); 
	    s.focus();
	    return false; 
	}
	return true;
}

function strLenthValidator(s, min, max)
{
	if((min && s.value.length < min) || (max && s.value.length > max)) 
	{
        error = i18n['m0770']; //Length from :min to :max characters
        error = error.replace(':min', min);
        error = error.replace(':max', max);
		showAlert(error); 
		s.focus(); 
		return false; 
	}
	return true;
}

function sendVideoLink(f, videoId)
{
	if (!requiredValidator(f.to,i18n['m0786'])) return false;
	if (!regexpValidator(f.to, /^[\da-zA-Z\\-_\\.]+@[\da-zA-Z\\-_\\.]+\.[a-zA-Z]{2,4}(\,\s*[\da-zA-Z\\-_\\.]+@[\da-zA-Z\\-_\\.]+\.[a-zA-Z]{2,4})*$/ , i18n['m0786'])) return false;
	
	if (!strLenthValidator(f.message, 0, 10000)) return false;
	
	var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	request.open('post', '/ajax/send_videolink/', true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.send('video_id=' + videoId + '&to=' + f.to.value + '&body=' + f.message.value);
    showAlert(i18n['m1392']); //Message has been sent successfully.
    f.reset();
	return true;   
}

function sendChannelLink(f, creatorId)
{
    if (!requiredValidator(f.to,i18n['m0786'])) return false;
	if (!regexpValidator(f.to, /^[\da-zA-Z\\-_\\.]+@[\da-zA-Z\\-_\\.]+\.[a-zA-Z]{2,4}(\,\s*[\da-zA-Z\\-_\\.]+@[\da-zA-Z\\-_\\.]+\.[a-zA-Z]{2,4})*$/ , i18n['m0786'])) return false;
	
	if (!strLenthValidator(f.message, 0, 10000)) return false;
	
	var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	request.open('post', '/ajax/send_channellink/', true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.send('creator_id=' + creatorId + '&to=' + f.to.value + '&body=' + f.message.value);
    showAlert(i18n['m1392']); //Message has been sent successfully.
    f.reset();
    return true;
}
/* } SHARE VIDEO AND CHANNEL */

/* VIDEO AND CHANNEL PHOTOS HEIGHT { */
function getPosY(idEl)
{
	var posY = 0;
	var obj = document.getElementById(idEl);
	while (obj)
	{
		posY += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return posY; 
}

function setHeight(topIdEl, bottomIdEl, scrollIdEl, scrollMinHeight)
{
    scrollMinHeight = ((scrollMinHeight) ? scrollMinHeight+35 : 375);
    var el = document.getElementById(scrollIdEl);
    el.style.height = 0 + 'px';
    scrollHeight = getPosY(bottomIdEl)-getPosY(topIdEl);
    el.style.height = (scrollHeight < scrollMinHeight) ? scrollMinHeight-35 + 'px' : scrollHeight-35+15 + 'px';
}
/* } VIDEO AND CHANNEL PHOTOS HEIGHT */