// SHARED FUNCTIONS --------------------------------------------
Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}
function CheckLogin()
{
	return isLoggedIn;
}

function showAlert(txt)
{
	alert(txt);
	return false;
}

function postFormByForm(form,async,successCallback)
{
	var formVars=new Array();
	var str = "";
	for(var i=0;i<form.elements.length;i++)
	{
		var formElement=form.elements[i];
		if((formElement.type=='radio'||formElement.type=='checkbox')&&!formElement.checked)
		{
			continue;
		}
		var v=new Object;
		str += formElement.name;
		v.name=formElement.name;
		v.value=formElement.value;
		formVars.push(v);
	}
	postUrl(form.action,urlEncodeDict(formVars),async,execOnSuccess(successCallback));
}

function postUrl(url,data,async,stateChangeCallback)
{
	var xmlHttpReq=getXmlHttpRequest();
	if(!xmlHttpReq)
		return;
	xmlHttpReq.open("POST",url,async);
	xmlHttpReq.onreadystatechange=function()
	{
		stateChangeCallback(xmlHttpReq);
	};
	xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttpReq.send(data);
}

function urlEncodeDict(dict)
{
	var result="";
	for(var i=0;i<dict.length;i++)
	{
		result+="&"+encodeURIComponent(dict[i].name)+"="+encodeURIComponent(dict[i].value);
	}
	return result;
}

function execOnSuccess(stateChangeCallback,successCallback,div_id)
{
	return function(xmlHttpReq)
	{
		if(xmlHttpReq.readyState==4 && xmlHttpReq.status==200)
		{
			if(div_id)
			{
				stateChangeCallback(xmlHttpReq,successCallback,div_id);
			}
			else
			{
				stateChangeCallback(xmlHttpReq,successCallback);
			}
		}
	};
}

function getXmlHttpRequest()
{
	var httpRequest=null;
	try
	{
		httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e)
		{
			httpRequest=null;
		}
	}
	if(!httpRequest&&typeof XMLHttpRequest!="undefined")
	{
		httpRequest=new XMLHttpRequest();
	}
	return httpRequest;
}

function fillDiv(url,div_id,data)
{
	var xmlHttpReq=getXmlHttpRequest();
	if(!xmlHttpReq)
		return;
	xmlHttpReq.open("POST",url,true);
	xmlHttpReq.onreadystatechange=function()
	{
		if(xmlHttpReq.readyState==4 && xmlHttpReq.status==200)
		{
			GetElement(div_id).innerHTML = xmlHttpReq.responseText;
		}
	};
	xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttpReq.send(data);
}


// COMMENTS FUNCTIONS -------------------------------------
function loadComments(pg, gn)
{
	GetElement('commentDisplay').innerHTML = '<table width=100% height=300><tr><td align=center><img src="/images/loader_gray.gif" border=0></td></tr></table>';
	fillDiv('/comments.php', 'commentDisplay', '&video_id='+video_id+'&pg='+pg+'&gn='+gn);
}

function postThreadedComment(comment_form_id)
{
	var msg = new Object();
	msg["add"] = "Adding comment...";
	postThreadedComment_js(comment_form_id, msg);
}
function postThreadedComment_js(comment_form_id,messages)
{
	
	var form=document.forms[comment_form_id];
	if(ThreadedCommentHandler(form,comment_form_id))
	{
		var add_button=form.add_comment_button;
		add_button.value=messages["add"];
		form.video_comment.disabled=true;
		add_button.disabled=true;
		add_button.className="bluebutton_disabled";
	}
}

function ThreadedCommentHandler(comment_form, comment_form_id)
{
	var msg = new Object();
	msg["empty"] = "You must enter a comment!";
	msg["toolong"] = "Your comment must be shorter than 500 characters!";
	ThreadedCommentHandler_js(comment_form, comment_form_id, msg);
}
function ThreadedCommentHandler_js(comment_form,comment_form_id,messages)
{
    var comment=comment_form.video_comment;
	var name=comment_form.txtname;
	var comment_button=comment_form.add_comment_button;
	if(comment.value.length==0||comment.value==null||name.value.length==0)
	{
		alert(messages["empty"]);
		comment.disabled=false;
		comment.focus();
		return false;
	}
	if(comment.value.length>500)
	{
		alert(messages["toolong"]);
		comment.disabled=false;
		comment.focus();
		return false;
	}
	postFormByForm(comment_form,true,commentResponse);
	return true;
}

function commentResponse(xmlHttpRequest)
{
	var msg = new Object();
	msg["ok"] = "Comment Posted!";
	msg["pending"] = "Comment Pending Approval!";
	msg["toolong"] = "The comment you have entered is too long. Limit is 500 characters. Please write a shorter comment and try again";
	msg["tooshort"] = "The comment you have entered is too short. Please write a longer comment and try again";
	msg["toosoon"] = "Commenting Limit Exceeded";
	msg["notlogged"] = "You must be logged to post a comment!";
	msg["email"] = "You must confirm your email address before you can submit comments.  Click OK to confirm your email address.";
	msg["captchFail"] = "The response to the letters on the image was not correct, please try again.";
	msg["default"] = "Post Comment"; 
	commentResponse_js(xmlHttpRequest, msg);
}
function commentResponse_js(xmlHttpRequest,messages)
{
	response_str=xmlHttpRequest.responseText;
	response_code=response_str.substr(0,response_str.indexOf(" "));
	form_id=response_str.substr(response_str.indexOf(" ")+1);
	var form=document.forms[form_id];
	var dstDiv=form.add_comment_button;
	var commentDiv=form.video_comment;

	//var video_id = form.video_id.value;
	if(response_code=="OK")
	{
		dstDiv.value=messages["ok"];
		dstDiv.disabled=true;
		dstDiv.className="bluebutton_disabled";
		loadComments('1', '1');
        form.video_comment.disabled=true;
    form.txtname.disabled=true;
        if (!CheckLogin())
        showAlert(messages["pending"]);   
            
	}
    else if(response_code=="TOOLONG")
    {
        showAlert(messages["toolong"]);
        dstDiv.disabled=false;
        commentDiv.disabled=false;
    }	
    else if(response_code=="NOTAPPROVED")
	{
		showAlert(messages["pending"]);
		dstDiv.disabled=false;
		commentDiv.disabled=false;
	}
	else if(response_code=="NOTLOGGED")
	{
		showAlert(messages["notlogged"]);
		dstDiv.disabled=true;
		dstDiv.className="bluebutton_disabled";
		commentDiv.disabled=true;
	}
}

// TAGS FUNCTIONS --------------------------
function selectTag(id)
{
	var vTags = new Array();
	if (GetElement('video_tags').value)
		vTags = GetElement('video_tags').value.split('|');
	var aTags = new Array();
	if (GetElement('tags_to_add').value)
		aTags = GetElement('tags_to_add').value.split('|');
	var rTags = new Array();
	if (GetElement('tags_to_remove').value)
		rTags = GetElement('tags_to_remove').value.split('|');
	if (GetElement('tag_'+id).className == "tag")
	{
		GetElement('tag_'+id).className = "tagSelected";
		if (!vTags.in_array(id) && !aTags.in_array(id))
		{
			aTags.push(id);
			GetElement('tags_to_add').value = aTags.join('|');
		}
		if (rTags.in_array(id))
		{
			var tmp = new Array();
			for (var i=0; i<rTags.length; i++)
			{
				if (rTags[i] != id)
				{
					tmp.push(rTags[i]);
				}
			}
			rTags = tmp;
			GetElement('tags_to_remove').value = rTags.join('|');
		}
	}
	else
	{
		GetElement('tag_'+id).className = "tag";
		if (vTags.in_array(id) && !rTags.in_array(id))
		{
			rTags.push(id);
			GetElement('tags_to_remove').value = rTags.join('|');
		}
		if (aTags.in_array(id))
		{
			var tmp = new Array();
			for (var i=0; i<aTags.length; i++)
			{
				if (aTags[i] != id)
				{
					tmp.push(aTags[i]);
				}
			}
			aTags = tmp;
			GetElement('tags_to_add').value = aTags.join('|');
		}
	}
}
function postThreadedTag(tag_form_id)
{
	var msg = new Object();
	msg["add"] = "Updating Tags...";
	postThreadedTag_js(tag_form_id, msg);
}
function postThreadedTag_js(tag_form_id,messages)
{
	if(CheckLogin()==false)
	{
		showAlert("You must be logged to update video tags!");
		return false;
	}
	var form=document.forms[tag_form_id];
	if(ThreadedTagHandler(form,tag_form_id))
	{
		var update_button=form.update_tag_button;
		update_button.value=messages["update"];
		update_button.disabled=true;
		update_button.className="bluebutton_disabled";
	}
}

function ThreadedTagHandler(tag_form, tag_form_id)
{
	var msg = new Object();
	msg["empty"] = "Select at least a tag";
	msg["toolong"] = "";
	ThreadedTagHandler_js(tag_form, tag_form_id, msg);
}
function ThreadedTagHandler_js(tag_form,tag_form_id,messages)
{
	postFormByForm(tag_form,true,tagResponse);
	return true;
}

function tagResponse(xmlHttpRequest)
{
	var msg = new Object();
	msg["ok"] = "Tags Updated";
	msg["pending"] = "Comment Pending Approval!";
	msg["toolong"] = "The comment you have entered is too long. Limit is 500 characters. Please write a shorter comment and try again";
	msg["noselection"] = "You have to select some tags to add or to remove !";
	msg["toosoon"] = "Commenting Limit Exceeded";
	msg["notlogged"] = "You must be logged to update video tags!";
	msg["email"] = "You must confirm your email address before you can submit comments.  Click OK to confirm your email address.";
	msg["captchFail"] = "The response to the letters on the image was not correct, please try again.";
	msg["default"] = "Post Comment"; 
	tagResponse_js(xmlHttpRequest, msg);
}
function tagResponse_js(xmlHttpRequest,messages)
{
	response_str=xmlHttpRequest.responseText;
	response_code=response_str.substr(0,response_str.indexOf(" "));
	form_id=response_str.substr(response_str.indexOf(" ")+1);
	var form=document.forms[form_id];
	var dstDiv=form.update_tag_button;
	var chkTab = form.elements;
	if(response_code=="OK")
	{
		dstDiv.value=messages["ok"];
		dstDiv.disabled=true;
		dstDiv.className="bluebutton_disabled";
		for(var i=0;i<chkTab.length;i++)
		{
			if (chkTab[i].type=='checkbox')
			{
				chkTab[i].disabled=true;
			}
		}
	}
	else if(response_code=="NOTLOGGED")
	{
		showAlert(messages["notlogged"]);
		dstDiv.disabled=true;
		dstDiv.className="bluebutton_disabled";
		for(var i=0;i<chkTab.length;i++)
		{
			if (chkTab[i].type=='checkbox')
			{
				chkTab[i].disabled=true;
			}
		}
	}
	else if(response_code=="NOSELECTION")
	{
		showAlert(messages["noselection"]);
		dstDiv.disabled=false;
		dstDiv.className="bluebutton";
	}
}


// FAVORITES FUNCTIONS ------------------------------
function postThreadedFav(fav_form_id)
{
	var msg = new Object();
	msg["add"] = "Updating Tags...";
	postThreadedFav_js(fav_form_id, msg);
}
function postThreadedFav_js(fav_form_id,messages)
{
	if(CheckLogin()==false)
	{
		showAlert("You must be logged to add a video to your favorites!");
		return false;
	}
	var form=document.forms[fav_form_id];
	if(ThreadedFavHandler(form,fav_form_id))
	{
		var add_button=form.add_fav_button;
		add_button.value=messages["update"];
		add_button.disabled=true;
		add_button.className="bluebutton_disabled";
	}
}

function ThreadedFavHandler(fav_form, fav_form_id)
{
	var msg = new Object();
	msg["empty"] = "Select at least a tag";
	msg["toolong"] = "";
	ThreadedFavHandler_js(fav_form, fav_form_id, msg);
}
function ThreadedFavHandler_js(fav_form,fav_form_id,messages)
{
	postFormByForm(fav_form,true,favResponse);
	return true;
}

function favResponse(xmlHttpRequest)
{
	var msg = new Object();
	msg["ok"] = "Video added to your Favorites";
	msg["pending"] = "Comment Pending Approval!";
	msg["toolong"] = "The comment you have entered is too long. Limit is 500 characters. Please write a shorter comment and try again";
	msg["tooshort"] = "The comment you have entered is too short. Please write a longer comment and try again";
	msg["toosoon"] = "Commenting Limit Exceeded";
	msg["notlogged"] = "You must be logged to add a video to your favorites!";
	msg["email"] = "You must confirm your email address before you can submit comments.  Click OK to confirm your email address.";
	msg["captchFail"] = "The response to the letters on the image was not correct, please try again.";
	msg["default"] = "Post Comment"; 
	favResponse_js(xmlHttpRequest, msg);
}
function favResponse_js(xmlHttpRequest,messages)
{
	response_str=xmlHttpRequest.responseText;
	response_code=response_str.substr(0,response_str.indexOf(" "));
	form_id=response_str.substr(response_str.indexOf(" ")+1);
	var form=document.forms[form_id];
	var dstDiv=form.add_fav_button;
	var chkTab = form.elements;
	if(response_code=="OK")
	{
		dstDiv.value=messages["ok"];
		dstDiv.disabled=true;
		dstDiv.className="bluebutton_disabled";
	}
	else if(response_code=="NOTLOGGED")
	{
		showAlert(messages["notlogged"]);
		dstDiv.disabled=true;
		dstDiv.className="bluebutton_disabled";
	}
}

// PLAYLISTS FUNCTIONS ------------------------------
function loadPlaylists()
{
	GetElement('playlistContent').innerHTML = '<table width=100% height=300><tr><td align=center><img src="/images/loader_gray.gif" border=0></td></tr></table>';
	fillDiv('/add_to_playlist.php', 'playlistContent', '&sid='+sid+'&video_id='+video_id);
}

function postThreadedPlay(play_form_id)
{
	if (GetElement('playlist_id').value=='0')
	{
		return false;
	}
	else if (GetElement('playlist_id').value=='new')
	{
		GetElement('formPDisplay').style.display='block';
		GetElement('formFDisplay').style.display='none';
	}
	else
	{
		var msg = new Object();
		msg["add"] = "Updating Tags...";
		postThreadedPlay_js(play_form_id, msg);
	}
}
function postThreadedPlay_js(play_form_id,messages)
{
	if(CheckLogin()==false)
	{
		showAlert("You must be logged to add a video to your plalist!");
		return false;
	}
	var form=document.forms[play_form_id];
	if(ThreadedPlayHandler(form,play_form_id))
	{
		var add_button=form.add_play_button;
		add_button.value=messages["update"];
		add_button.disabled=true;
		add_button.className="bluebutton_disabled";
	}
}

function ThreadedPlayHandler(play_form, play_form_id)
{
	var msg = new Object();
	msg["empty"] = "Select at least a tag";
	msg["toolong"] = "";
	ThreadedPlayHandler_js(play_form, play_form_id, msg);
}
function ThreadedPlayHandler_js(play_form,play_form_id,messages)
{
	postFormByForm(play_form,true,playResponse);
	return true;
}

function playResponse(xmlHttpRequest)
{
	var msg = new Object();
	msg["ok"] = "Video added to your Playlist";
	msg["pending"] = "Comment Pending Approval!";
	msg["toolong"] = "The comment you have entered is too long. Limit is 500 characters. Please write a shorter comment and try again";
	msg["tooshort"] = "The comment you have entered is too short. Please write a longer comment and try again";
	msg["toosoon"] = "Commenting Limit Exceeded";
	msg["notlogged"] = "You must be logged to add a video to your playlist!";
	msg["email"] = "You must confirm your email address before you can submit comments.  Click OK to confirm your email address.";
	msg["captchFail"] = "The response to the letters on the image was not correct, please try again.";
	msg["default"] = "Post Comment"; 
	playResponse_js(xmlHttpRequest, msg);
}
function playResponse_js(xmlHttpRequest,messages)
{
	response_str=xmlHttpRequest.responseText;
	response_code=response_str.substr(0,response_str.indexOf(" "));
	dstDiv=GetElement(response_str.substr(response_str.indexOf(" ")+1));
	if(response_code=="OK")
	{
		dstDiv.innerHTML = '<table width=100% height=100><tr><td align=center valign=middle>Video Added to your playlist</td></tr></table>';
		(function() { viewTab('com'); loadPlaylists() }).delay(2);
	}
	else if(response_code=="NOTLOGGED")
	{
		showAlert(messages["notlogged"]);
	}
}

function postThreadedAPlay(play_form_id)
{
	var title = GetElement('playlist_title').value;
	var rege = new RegExp("/^([a-z0-9 ]+)$","gi")
	var special_matches = title.match(rege);
	if (special_matches || title.length==0)
	{
		GetElement('error_new_playlist').innerHTML = "Invalid Playlist Title !";
		return false;
	}
	else
	{
		var msg = new Object();
		msg["add"] = "Creating Playlist...";
		postThreadedAPlay_js(play_form_id, msg);
	}
}
function postThreadedAPlay_js(play_form_id,messages)
{
	if(CheckLogin()==false)
	{
		showAlert("You must be logged to add a video to your plalist!");
		return false;
	}
	var form=document.forms[play_form_id];
	if(ThreadedAPlayHandler(form,play_form_id))
	{
		var add_button=form.add_aplay_button;
		add_button.value=messages["update"];
		add_button.disabled=true;
		add_button.className="bluebutton_disabled";
	}
}

function ThreadedAPlayHandler(play_form, play_form_id)
{
	var msg = new Object();
	msg["empty"] = "Select at least a tag";
	msg["toolong"] = "";
	ThreadedAPlayHandler_js(play_form, play_form_id, msg);
}
function ThreadedAPlayHandler_js(play_form,play_form_id,messages)
{
	postFormByForm(play_form,true,aplayResponse);
	return true;
}

function aplayResponse(xmlHttpRequest)
{
	var msg = new Object();
	msg["ok"] = "Video added to your Playlist";
	msg["pending"] = "Comment Pending Approval!";
	msg["toolong"] = "The comment you have entered is too long. Limit is 500 characters. Please write a shorter comment and try again";
	msg["tooshort"] = "The comment you have entered is too short. Please write a longer comment and try again";
	msg["toosoon"] = "Commenting Limit Exceeded";
	msg["notlogged"] = "You must be logged to add a video to your playlist!";
	msg["email"] = "You must confirm your email address before you can submit comments.  Click OK to confirm your email address.";
	msg["captchFail"] = "The response to the letters on the image was not correct, please try again.";
	msg["default"] = "Post Comment"; 
	aplayResponse_js(xmlHttpRequest, msg);
}
function aplayResponse_js(xmlHttpRequest,messages)
{
	response_str=xmlHttpRequest.responseText;
	response_code=response_str.substr(0,response_str.indexOf(" "));
	dstDiv=GetElement(response_str.substr(response_str.indexOf(" ")+1));
	if(response_code=="OK")
	{
		dstDiv.innerHTML = '<table width=100% height=100><tr><td align=center valign=middle>New Playlist Created<br>Video Added to your playlist</td></tr></table>';
		(function() { viewTab('com'); loadPlaylists() }).delay(3);
	}
	else if(response_code=="NOTLOGGED")
	{
		showAlert(messages["notlogged"]);
	}
}
