//<![CDATA[
var previous = "";
var next = "";
var useridtmp = "";
var videoidtmp = "";
var owneridtmp = "";
var page = "";
var ismypagetmp = "False";
var set=false;
var v=0;
var a;
var commentpageno = 0;
var TitleEditor = null;
var DescriptionEditor = null;
var TagsEditor = null;

var shadowbox_mac_loading_img = new Image();
shadowbox_mac_loading_img.src = '/static/v2p/images/shadowbox_mac_loading.gif';
var videodeleting = false;
var commentdeleting = false;
var commentposting = false

var groupInfoList = {};

function gotoprev()
{
	if($('hprevious').value!='')
	{
		//showElement('loading');
		getVideoList45($('hprevious').value,false)
	}
}

function gotonext()
{	
	if($('hnext').value!='')
	{
		//showElement('loading');
		getVideoList45($('hnext').value,false)
	}
}

function deleteimage()
{
	if(videoidtmp !='' && !videodeleting)
	{
		if(confirm(_('Do you want to delete video?')))
		{
			videodeleting = true;
			showElement('loading');
			var opt = {
				method: 'post',
				postBody: 'videoid=' + videoidtmp,
				onSuccess: function(t) {
					if($('hnext').value!='')
					{
						getVideoList45($('hnext').value,false);
					}
					else
					{
						if($('hprevious').value!='')
						{
							getVideoList45(t.responseText,false);
						}
						else
						{
							videodeleting = false;
							window.location.href = "/videos/category/"+useridtmp;
						}
					}
				},
				onFailure: function(t) {
					videodeleting = false;
					hideElement('loading');
					alert(_("Sorry, Can't delete. Try again please."));
				}
			}
			new Ajax.Request('/video/delete', opt);
		}
	}
}

function deletecomment_click(itemtype,itemid)
{
	if(itemid!='' && !commentdeleting)
	{
		if(confirm(_('Do you want to delete this message?')))
		{
			commentdeleting = true;
			var opt = {
				method: 'post',
				postBody: 'type=' + itemtype + '&id=' + itemid,
				onSuccess: function(t) {
					commentdeleting = false;
					refreshcomments(useridtmp,commentpageno);
				},
				onFailure: function(t) {
					commentdeleting = false;
					alert(_("Sorry, the message cannot be deleted. Please try again"));
				}
			}
			new Ajax.Request('/videos/deleteVideosComment', opt);
		}
	}
	else
	{
		if(commentdeleting)
		{
			alert(_("Sorry, the message is deleting. Please wait"));
		}
	}
}

function getVideoList45(videoid,firsttime)
{
	if(videoid.indexOf('i')==0)
		videoid = videoid.substring(1);
	if(firsttime)
		showElement('loading');
	if(TitleEditor!=null)
	{
		if(TitleEditor._editing)
			TitleEditor.leaveEditMode();
	}

	if(DescriptionEditor)
	{
		if (DescriptionEditor._editing)
			DescriptionEditor.leaveEditMode();
	}
	
	if(TagsEditor)
	{
		if (TagsEditor._editing)
			TagsEditor.leaveEditMode();
	}

	var opt = {
			method: 'post',
			postBody: 'videoid=' + videoid,
			onSuccess: function(t) {
                result = t.responseText.evalJSON();
				var reslist = result.videolist.split("|");
				var output = '';
				if(!firsttime)
				{
					//if(navigator.userAgent.match("Firefox/3.0")==null){
						window.location.href="/video/view/"+videoid;
					//}
					//videoidtmp = videoid;
					//refreshcomments(useridtmp,'0');
					//getvideodetail(videoid);
				}
				else
				{ 
                    
                var useridtmp2 = reslist[0];
				useridtmp = useridtmp2;
				for(var i = 1;i<reslist.length;i++)
				{
					if(reslist[i]!="")
					{
						if(reslist[i].indexOf('current')==-1)
							{
								var videoitem = reslist[i].split(':')
								output += '<a href="javascript:void(0);" id="i'+videoitem[0]+'" onclick="getVideoList45(this.id,false);" ><img id="img'+videoitem[0]+'"  class="avatar" style="cursor:pointer;" src="/asset/video/png/30x30/'+useridtmp2+'/'+videoitem[1]+ '" alt="'+videoitem[0]+'"/></a>';
							}
							else
							{
								var currentview = reslist[i].substring(8);
								var videoitem = currentview.split(':')
								output += '<a href="javascript:void(0);" id="i'+videoitem[0]+'" onclick="getVideoList45(this.id,false);"><img  id="img'+videoitem[0]+'" class="currentview"  style="cursor:pointer;" src="/asset/video/png/30x30/'+useridtmp2+'/'+videoitem[1]+ '" alt="'+videoitem[0]+'"/></a>';
								videoidtmp = videoitem[0];
							    videofilename = videoitem[1];
                            
                            groupInfoList = {};
                            if(result.grouplist.length == 0){
                                hideElement("groupContainer");
                            }else{
                                showElement("groupContainer");
                                hideElement("grouplist");

                                var grouplistitem = $("grouplistitem");
                                grouplistitem.innerHTML = "";

                                var groupphoto = $("groupphoto");
                                if(result.isMyPage){
                                    groupphoto.onclick = function(){showSaveGroupVideo();}
                                    groupphoto.onmouseover = function(){groupphoto.style.backgroundColor = "#FFFF99";}
                                    groupphoto.onmouseout = function(){
                                        groupphoto.style.backgroundColor = "";
                                        new Effect.Highlight(groupphoto,{startcolor: "#FFFF99", endcolor: "", restorecolor: "", keepBackgroundImage: true});
                                    }

                                    var ul = document.createElement("ul");
                                    for(var id = 0; id < result.grouplist.length; id++){
                                        var groupInfo = result.grouplist[id];
                                        var li = document.createElement("li");
                                        var imgl = document.createElement("img");
                                        imgl.src = "/asset/group/"+groupInfo.displayPicture;
                                        imgl.className = "avatar avatar28";
                                        var span = document.createElement("span");
                                        span.innerHTML = " " + groupInfo.groupName;
                                        var input = document.createElement("input");
                                        input.type = "checkbox";
                                        input.checked = groupInfo.checked;
                                        input.value = groupInfo.id+":"+groupInfo.type;
                                        groupInfoList[groupInfo.id+":"+groupInfo.type] = groupInfo;

                                        li.appendChild(imgl);
                                        li.appendChild(span);
                                        li.appendChild(input);
                                        ul.appendChild(li);
                                    }
                                    grouplistitem.appendChild(ul);
                                }else{
                                    groupphoto.onclick = function(){}
                                    groupphoto.style.backgroundColor = "";
                                    groupphoto.onmouseover = function(){}
                                    groupphoto.onmouseout = function(){}
                                    for(var id = 0; id < result.grouplist.length; id++){
                                        var groupInfo = result.grouplist[id];
                                        groupInfoList[groupInfo.id+":"+groupInfo.type] = groupInfo;
                                    }
                                }
                                genGroupNameText();
                            }
						}
					}
				}
				output += '<div class="clear"></div>';
				$('itemlist45').innerHTML = output;
				}
				videodeleting = false;
				hideElement('loading');
			},
			onFailure: function(t) {
				videodeleting = false;
				hideElement('loading');
			}
		  }
	new Ajax.Request('/video/GetVideoList45', opt);
}

function saveGroupVideo(){
    $("groupphoto").innerHTML = "Saving...";

    var groupidlist = new Array();
    $("grouplistitem").select("input").each(function(element){
        if(element.checked){
            var key = element.value.split(":");
            groupidlist.push([key[0],key[1]]);
        }
    });
    var opt = {
        postBody: "id="+videoidtmp+"&groupidlist="+groupidlist.toJSON(),
        onSuccess: function(t) {
            if(t.responseText == "200"){
                hideElement('grouplist');
                for(key in groupInfoList){
                    groupInfoList[key].checked = false;
                }
                for(var i = 0; i<groupidlist.length; i++){
                    groupInfoList[groupidlist[i][0]+":"+groupidlist[i][1]].checked = true;
                }
                genGroupNameText();
            }else{
                cancelSaveGroupVideo();
            }
        },
        onFailure: function(t) {
            cancelSaveGroupVideo();
        }
    }
    new Ajax.Request("/video/saveGroupVideo", opt);
}

function showSaveGroupVideo(){
    $("grouplistitem").select("input").each(function(element){
        element.checked = groupInfoList[element.value].checked;
    })
    showElement('grouplist');
}

function cancelSaveGroupVideo(){
    hideElement('grouplist');
}

function genGroupNameText(){
    var tmpGroupName = "";
    for(key in groupInfoList){
        if(groupInfoList[key].checked){tmpGroupName += groupInfoList[key].groupName+ ", ";}
    }
    if(tmpGroupName.length == 0){
        if(ismypagetmp == "True"){
            tmpGroupName = _("Click here to add video to your groups");
        }else{
            tmpGroupName = "";
        }
    }else{
        tmpGroupName = tmpGroupName.substring(0,tmpGroupName.length-2);
    }
    $("groupphoto").innerHTML = tmpGroupName;
}

function getvideodetail(videoid)
{
	var randomnumber=Math.floor(Math.random()*9999999).toString()
	var d = loadJSONDoc('/video/GetVideoDetail',{videoid:videoid,n:randomnumber});
	d.addCallback(handleLoadCallback);
}

function EditInPlace()
{
	TitleEditor.url = '/'+page+'/edit/'+videoidtmp+'/title';

	DescriptionEditor.url ='/'+page+'/edit/'+videoidtmp+'/description';

	TagsEditor.url = '/'+page+'/edit/'+videoidtmp+'/tag';
}

function handleLoadCallback(result)
{

	if(result.Title=='' && ismypagetmp=="True")
			$('Title').innerHTML = _("Click here for edit title");
	else
	{
			if(result.Title=='')
				$('Title').innerHTML = "&nbsp;"
			else
				$('Title').innerHTML = result.Title;
	}


	if(result.Description=='' && ismypagetmp=="True")
		$('Description').innerHTML = _("Click here to edit detail");
	else
		$('Description').innerHTML = result.Description;

	if(result.VideoTags=='' && ismypagetmp=="True")
		$('Tags').innerHTML = _("Click here to edit tags");
	else
		$('Tags').innerHTML = result.VideoTags;
	

	if( result.Previous == '')
	{
		hideElement('previous');
		$('hprevious').value = '';
	}
	else
	{
		showElement('previous');
		$('hprevious').value = result.Previous;
	}

	if(result.Next == '')
	{
		hideElement('next');
		$('hnext').value = '';
	}
	else
	{
		showElement('next');
		$('hnext').value = result.Next;
	}

	if(result.DeviceImage == '')
	{
		hideElement('mobiledetail');
	}
	else
	{
		showElement('mobiledetail');
		$('mobileimg').src="/device/"+result.DeviceImage;
		$('mobilename').innerHTML = result.DeviceBrand + " " + result.DeviceModel;
		mobileurl = result.DeviceURL;
		if(mobileurl!='')
			$('mobileimg').style.cursor = 'pointer';
		else
			$('mobileimg').style.cursor = '';
	}

	if(result.UploadDate == "")
	{
		$('UploadDate').innerHTML = "&nbsp;";
	}
	else
	{
		$('UploadDate').innerHTML = result.UploadDate;
	}

	if(result.MobileCellLocation=='')
	{
		$('Location').innerHTML = "&nbsp;";
	}
	else
	{
		$('Location').innerHTML = result.MobileCellLocation;
	}

	if(result.VisitorCount=='')
	{
		$('VisitorCount').innerHTML = '0';
	}
	else
	{
		$('VisitorCount').innerHTML = result.VisitorCount;
	}

	if(result.Location == '') {
		//$('map').innerHTML = '<span/>';
		//if(ismypagetmp == 'False')hideElement('map_container');//ถ้าแก้สถานที่ได้ให้ใช้อันนี้
		hideElement('map_container');
        hideElement('quickpost-googlemapembed');
	} 
	else 
	{
		showElement('map_container');
        $('quickpost-googlemapembed').style.display = 'inline';
		if(isEditableMode)cancelEditableMode();
		map.checkResize();
		var locationlist = result.Location.split(',');
		if (GBrowserIsCompatible()) 
		{
			if(marker) map.removeOverlay(marker);
			
			defaultPoint = new GLatLng(Number(locationlist[0]),Number(locationlist[1]));
	        point = defaultPoint;
			marker = new GMarker(point);
			map.setCenter(point, Number(locationlist[2]));
			map.addOverlay(marker);

			//if(isEditableMode == true) cancelEditableMode();
		}
	}
}


function loadStars()
{
   staroff = new Image();
   staroff.src = "/static/images/StarOff.gif";
   staron = new Image();
   staron.src= "/static/images/StarOn.gif";
}

function highlight(x)
{
if (set==false)
	{
	y=x*1+1
	switch(x)
		{
		case "1": $(x).src= staron.src;
		break;
		case "2":for (i=1;i<y;i++)
		{
		$(i).src= staron.src;
		}
		break;
		case "3":for (i=1;i<y;i++)
		{
		$(i).src= staron.src;
		}
		break;
		case "4":for (i=1;i<y;i++)
		{
		$(i).src= staron.src;
		}
		break;
		case "5":for (i=1;i<y;i++)
		{
		$(i).src= staron.src;
		}
		break;
		}
	}
}
function losehighlight(x)
{	
   if (set==false)
   {
	   for (i=1;i<6;i++)
	   {
	   $(i).src = staroff.src;
	   //$('vote').innerHTML=""
	   }
   }
}
function setStar(rate)
{	var opt = {
			method: 'post',
			postBody: 'rate=' + rate + '&voterid=' + useridtmp + '&videoid=' + videoidtmp,
			onSuccess: shine(rate),
			onFailure: function(t) {
				alert('Sorry, could not vote your video');
			}
		  }
	new Ajax.Request('/video/vote', opt);
}
function shine(x)
{
   y=x*1+1
   if (set==false)
   {
   switch(x)
   {
   case "1": a="1" 
   flash(a);
   break;
   case "2": a="2" 
   flash(a);
   break;
   case "3": a="3" 
   flash(a);
   break;
   case "4":a="4" 
   flash(a);
   break;
   case "5":a="5" 
   flash(a);
   break;
   }
   set=true;
   $('vote').innerHTML="you has been rated on this video!" 
   var ajax = new Ajax.Updater('currentrate','/video/calrate/'+videoidtmp+'/',        
					         {method:'get',onComplete: showrate(req)});
	function showrate(req)
	{	alert(req);
		$('currentrate').value = req
	}
   }
}
function flash()
{	
   y=a*1+1
   switch(v)
   {
   case 0:
   for (i=1;i<y;i++) 
   {
   $(i).src= staroff.src;
   }
   v=1
   setTimeout(flash,200)
   break;
   case 1: 
   for (i=1;i<y;i++) 
   {
   $(i).src= staron.src;
   }
   v=2
   setTimeout(flash,200)
   break;
   case 2:
   for (i=1;i<y;i++) 
   {
   $(i).src= staroff.src;
   }
   v=3
   setTimeout(flash,200)
   break;
   case 3:
   for (i=1;i<y;i++) 
   {
   $(i).src= staron.src;
   }
   v=4
   setTimeout(flash,200)
   break;
   case 4:
   for (i=1;i<y;i++) 
   {
   $(i).src= staroff.src;
   }
   v=5
   setTimeout(flash,200)
   break;
   case 5:
   for (i=1;i<y;i++) 
   {
   $(i).src= staron.src;
   }
   v=6
   setTimeout(flash,200)
   break;
   }
}
function EditVideoDetails(editvideotitle,editvideodescription,editvideolength,editvideocategory,privacy) 
{	
	var editvideotitle = encodeURIComponent($(editvideotitle).value);
	var editvideodescription = encodeURIComponent($(editvideodescription).value);
	var editvideolength = $(editvideolength).value;
	var editvideocategory = encodeURIComponent($(editvideocategory).value);
	var privacy = $(privacy).value;
	var opt = {
			method: 'post',
			postBody: 'editvideotitle=' + editvideotitle + '&editvideodescription=' + editvideodescription + '&editvideolength=' + editvideolength + '&editvideocategory=' + editvideocategory + '&userid=' + useridtmp+ '&videoid=' + videoidtmp + '&privacy=' + privacy,
			onSuccess: function(t) {
				$('zoneeditvideodetail').style.display = 'none';
			},
			onFailure: function(t) {
				alert('Sorry, could not edit your video details');
			}
		  }
	new Ajax.Request('/video/editdetail', opt);
}
function refreshcomments(userid,commentspage)
{
	var opt = {
			method: 'post',
			postBody: 'pagesname=video&userid=' + userid + '&commentspage='+ commentspage+'&videoid='+ videoidtmp + '&categoryid=0',
			onSuccess: function(t) {
				if(t.responseText.indexOf('commentitem')!=-1  || commentpageno == 0)
				{
					commentposting = false;
					hideElement('commentloading');
					commentpageno = commentspage;
					$('commentlist').innerHTML = t.responseText;
				}
				else
				{
						commentpageno = (parseInt(commentspage)-1).toString();
						refreshcomments(userid,commentpageno);
				}
				ReplacePgLinkComment();			
			},
			onFailure: function(t) {
				commentposting = false;
				hideElement('commentloading');
				//alert('Sorry, could not load  your album');
				$('commentlist').innerHTML = t.responseTest;//'Sorry, could not load  your photos'
			}
		  }
	new Ajax.Request('/videos/showVideosComment', opt);
}
function commentsubmit()
{	
    if(commentposting)
	{
		alert(_('Posting comment. Please wait'));
		return;
	}

	if(ownerid == '-1' && Trim($('txtcomment').value)=='')
		return;	
	showElement('commentloading');
	commentposting = true;
	var ownerid = owneridtmp;
	var posttext = encodeURIComponent($('txtcomment').value);
	var opt = {
			method: 'post',
			postBody: 'videoid=' + videoidtmp + '&text=' + posttext + '&userid=' + ownerid ,
			onSuccess: function(t) {
				refreshcomments(useridtmp,'0');
				$('txtcomment').value="";
				showrecentupdate(useridtmp);
			},
			onFailure: function(t) {
				//alert('Sorry, could not load  your album');
				commentposting = false;
				hideElement('commentloading');
				$('commentlist').innerHTML = t.responseTest;//'Sorry, could not load  your photos'
			}
		  }
	new Ajax.Request('/video/PostVideoComment', opt);
}

function quotesubmit(qid,types,itemid,commentid)
{
	if(commentposting)
	{
		alert(_('Posting comment. Please wait'));
		return;
	}
	if(Trim($(qid).value)=='')
		return;
	showElement('loading'+qid.substring(4));
    commentposting = true;
	var ownerid = owneridtmp;
    var posttext = encodeURIComponent($(qid).value);
	var opt = {
			method: 'post',
			postBody: 'videoid=' + videoidtmp + '&text=' + posttext + '&userid=' + ownerid + "&commentid=" + commentid,
			onSuccess: function(t) {
				refreshcomments(useridtmp,'0')
				$(qid).value="";
				showrecentupdate(useridtmp);
			},
			onFailure: function(t) {
				commentposting = false;
				hideElement('loading'+qid.substring(4));
				$('commentlist').innerHTML = t.responseText;
			}
		  }
	new Ajax.Request('/video/PostVideoComment', opt);
}

function replysubmit(rid,types,itemid,commentid)
{
	if(commentposting)
	{
		alert(_('Posting comment. Please wait'));
		return;
	}
	if(Trim($(rid).value)=='')
		return;
	showElement('replyloading'+rid.substring(4));
    commentposting = true;
	var ownerid = owneridtmp;
    var posttext = encodeURIComponent($(rid).value);
	var opt = {
			method: 'post',
			postBody: 'videoid=' + videoidtmp + '&text=' + posttext + '&userid=' + ownerid + "&commentid=" + commentid + "&isreply=True",
			onSuccess: function(t) {
				refreshcomments(useridtmp,'0')
				$(rid).value="";
				showrecentupdate(useridtmp);
			},
			onFailure: function(t) {
				commentposting = false;
				hideElement('replyloading'+rid.substring(4));
				$('commentlist').innerHTML = t.responseText;
			}
		  }
	new Ajax.Request('/video/PostVideoComment', opt);
}

function checkEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) return true;
	return false;
}

var quickPostIndexPage;
function quickPostIndex(){
	$('quickpost').innerHTML = quickPostIndexPage;
    $('quickpost-googlemapembed').style.display = ($('map_container').style.display == "block")?'inline':'none';
}

var preloadimg = new Image();
preloadimg.src="/static/v2p/images/share-loader.gif";

function socialnetworkLoginPage(network){
	if(network == "twitter"){
		url = "http://twitter.com/home?status=[Playground] " + encodeURIComponent(videotitle.unescapeHTML()) + " - http://www.pg.in.th/v/" + videoidtmp;
		window.open(url);
		return;
	}
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;

	showElement('qppostingimg');
    hideElement("quickpost")

	var opt = {
        postBody: 'page=video',
        onSuccess: function(result){
            if(result.responseText == 401){
                showElement("addNewNetworkBtn");
                $("infotext").innerHTML = _("incorrect email or password");
                showElement("infobox");
            }else{
                $('quickpost').update(result.responseText);
                hideElement('qppostingimg');
                showElement("quickpost");
            }
        },
        onFailure: function(result){
            $("infotext").innerHTML = _('Cannot show %s login page').replace("%s",network);
            showElement("infobox");
            hideElement('qppostingimg');
            showElement("quickpost");
        },
        onTimeout: onTimeout
    }
	new Ajax.Request('/socialnetwork/login/'+network, opt);
}

function socialnetworkLogin(form,network){
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;

	if(form.email.value == ""){
		$("infotext").innerHTML = _('Please enter email address');
		showElement("infobox");
		return;
	}else if(network != 'multiply' && network != 'youtube' && network != 'mthai' && checkEmail(form.email.value) == false){
		$("infotext").innerHTML = _('incorrect email format');
		showElement("infobox");
		return;
	}else if(form.password.value == ""){
		$("infotext").innerHTML = _('Please enter password');
		showElement("infobox");
		return;
	}

	$("refreshAlbumBtn").style.display = 'block';

	var opt = {
				postBody: 'refreshAlbumList=&email='+form.email.value+ '&password='+form.password.value +'&network='+network+'&page=video',
				onSuccess: function(t){
					if(t.responseText == 201){
						$("refreshAlbumBtn").style.display = 'none';
						socialnetworkLoginPage(network);
					}else if(t.responseText == 401){
						$("infotext").innerHTML = _('Invalid username or password');
						showElement("infobox");
						$("refreshAlbumBtn").style.display = 'none';
					}else if(t.responseText == 501){
						$("infotext").innerHTML = _('The album cannot be updated');
						showElement("infobox");
						$("refreshAlbumBtn").style.display = 'none';
					}else if(Number(t.responseText)){
						$("infotext").innerHTML = _('Can not login');
						showElement("infobox");
						$("refreshAlbumBtn").style.display = 'none';
					}else{
						$('quickpost').update(t.responseText);
					}
				},
				onFailure: function(t){
					$("infotext").innerHTML = _('Can not login');
					showElement("infobox");
					$("refreshAlbumBtn").style.display = 'none';
				},
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/login/', opt);
}

function switchToEmbedCode(){
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;

	$('quickpost').innerHTML =  '<div id="socialloginform"><a onclick="quickPostIndex()" class="deleteoverlay deleteicon" href="javascript:void(0);">'+_("Back")+'</a>'+
								'<h2 id="embedurl">Embeded URL</h2>'+
								'<p>'+
									'<input id="inputembed" type="text" onclick="this.focus();this.select();" value="'+$('embledcode').value+'"/>'+
								'</p>'+
								'<div class="clear"></div></div>';
}
/*function postToHi5(form){
	hi5LoginPage = $('quickpost').innerHTML;
	waiting();
	
	var opt = {
				method: 'post',
				postBody: 'id='+videoidtmp+ '&email='+form.email.value+ '&password='+form.password.value+ '&remember='+form.remember.checked+ '&section='+form.section.value+ '&type='+page,
				onSuccess: postResult,
				onFailure: postResult,
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/postToHi5', opt);
}*/
function postVideo(form,network){
	waiting();

	var opt = {
				method: 'post',
				postBody: 'id='+videoidtmp+ '&email='+form.email.value+ '&password='+form.password.value+ '&network='+network,
				onSuccess: postResult,
				onFailure: postResult,
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/postVideo', opt);
}
/*
function postToMultiply(form){
	multiplyLoginPage = $('quickpost').innerHTML;
	waiting();
	
	var opt = {
				method: 'post',
				postBody: 'id='+videoidtmp+ '&userid='+form.userid.value+ '&password='+form.password.value+ '&remember='+form.remember.checked+ '&title='+encodeURIComponent(form.title.value)+ '&type='+page,
				onSuccess: postResult,
				onFailure: postResult,
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/postToMultiply', opt);
}
function postToFacebook(form){
	waiting();
	var link = ""
	if(window.location.toString().indexOf("test")!= -1){
		window.open('http://apps.facebook.com/playgroundprodapp/?item='+encodeURIComponent(form.title.value)+'_type:flv_'+videoidtmp);
		link = 'http://apps.facebook.com/playgroundprodapp/?item='+encodeURIComponent(form.title.value)+'_type:flv_'+videoidtmp
	}else{
		window.open('http://apps.facebook.com/playgroundapp/?item='+encodeURIComponent(form.title.value)+'_type:flv_'+videoidtmp);
		link = 'http://apps.facebook.com/playgroundapp/?item='+encodeURIComponent(form.title.value)+'_type:flv_'+videoidtmp
	}
	$('quickpost').innerHTML =  '<div style="width:335px; background-color:#FFFFCC; padding:5px; padding-top:15px;  border:1px solid #666666;"><p>'+
									_("If new facebook window is block.")+'<br/>'+
									_("Just copy embeded code below and paste to your browser")+'<br/>'+
								'</p>'+
								'<p>'+
									'<input style="width: 300px;" type="text" onclick="this.focus();this.select();" value="'+link+'"/>'+
								'</p>'+
								'<a onclick="quickPostIndex()" class="button" href="javascript:void(0);">_("Back")</a>'+
								'<div class="clear"></div></div>';
	Shadowbox.close();
}*/
function submitQuickpost(e,form,network){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return;

	if (keycode == 13){
		socialnetworkLogin(document.quickpostlogin,network);
	}
}
function waiting(){
	var options = {
		loadingImage: "/static/v2p/images/shadowbox_mac_loading.gif",
		listenOverlay: false,
		initialHeight: 32,
		initialWidth: 32,
        text:           {
            cancel:     '',
            loading:    '',
            close:      '',
            next:       '',
            prev:       '',
            errors:     {
                single: 'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',
                shared: 'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',
                either: 'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'
            }
        }
	};
	Shadowbox.init(options);
	Shadowbox.open({
        title:      '',
        type:       'html',
        content:    '<img src="/static/v2p/images/shadowbox_mac_loading.gif"/>',
        height:     32,
        width:      32
    });
}
function postResult(result){
	$('quickpost').innerHTML = result.responseText;
	Shadowbox.close();
}
function onTimeout(){
	$('quickpost').innerHTML = '<p>Timeout, please try again later. <a href="javascript:quickPostIndex()">Back</a></p>'
	Shadowbox.close();
}

function editvideodetail_onclick(){
	var editvideodetail = $('zoneeditvideodetail');
	if (editvideodetail.style.display == 'none'){
		editvideodetail.style.display = 'block';
	}else{
		editvideodetail.style.display = 'none';
	}
}

var stars;
var original_rating = 0;
var rating = 0;

function clickRatingEvent(event) {
var original_rating = rating;
var voterid = owneridtmp;
if(voterid == '-1')
	return;    
var opt = {
			method: 'post',
			postBody: 'videoid=' +videoidtmp +'voterid=' + voterid + '&rate=' + (original_rating+1),
			onSuccess: function(t) {
				$('starratefirefox').innerHTML =  t.responseText; 
			},
			onFailure: function(t) {
				alert('Sorry, could not vote your video!');
				$('starratefirefox').innerHTML =  t.responseText;  
			}
		  }
		new Ajax.Request('/video/vote', opt);
}
function rateVideo(img) {
var rating = 5;
for(i = 0; i < stars.length; i++) {
stars[i].src = (i < rating) ? staron.src : staroff.src;
if(stars[i] == img) { rating = i; }
}
}
function hoverRatingEvent(event) {
var img = event ? event.target : window.event.srcElement;
rateVideo(img);
}
function resetRatingEvent() {
rateVideo(stars[original_rating]);
}
//edit location part
mapsearch = undefined;
point = new GLatLng(13.911906992670394,100.49838066101074);

function setEditableMode(){
	if($("mapeditbtn").innerHTML==_("Add Location")){
		hideElement("locationNameContainer");
		showElement('map_container');
        $('quickpost-googlemapembed').style.display = 'inline';
		map.checkResize();
		point = new GLatLng(13.911906992670394,100.49838066101074);
		map.setCenter(point, 13);
	}
	showElement("mapsearchbox");
	$("mapsearchbox").scrollTo();
	if(!mapsearch){
		mapsearch = new GMap2($("mapsearch"));
		mapsearch.addControl(new GLargeMapControl());
		mapsearch.addControl(new GMapTypeControl());
		mapsearch.enableContinuousZoom();
	}
	mapsearch.checkResize();
	mapsearch.setCenter(map.getCenter(), map.getZoom());

	if($("Location").innerHTML == "&nbsp;"){
		$("locationName").value = "";
	}else{
		$("locationName").value = $("Location").innerHTML.unescapeHTML();
	}
	$("searchLocationGC").value = "";

	if(marker){
		map.removeOverlay(marker);
		marker = undefined;
	}

	if(defaultPoint){
		showElement("locationNameContainer");
		marker = new GMarker(point, {draggable: true});
		GEvent.addListener(marker, "dragend", function(){
			point = marker.getLatLng();
		});
		mapsearch.addOverlay(marker);
		mapsearch.panTo(point);
		$("msgdiv").innerHTML = _('Drag and drop marker on the map');
	}else{
		hideElement("mapsavebtn");
		hideElement("locationNameContainer");
		$("msgdiv").innerHTML = _('Click on the map in order to add a marker');
	}
	GEvent.addListener(mapsearch, 'click', function(overlay, p){
		if (p){
			point = p;
			if(marker){
				GEvent.clearListeners(marker, 'dragend');
				mapsearch.removeOverlay(marker);
				marker = undefined;
			}
			marker = new GMarker(point, {draggable: true});
			GEvent.addListener(marker, "dragend", function(){
				point = marker.getLatLng();
			});
			mapsearch.addOverlay(marker);
			mapsearch.panTo(point);
			showElement("mapsavebtn");
			showElement("locationNameContainer");
			$("msgdiv").innerHTML = _('Drag and drop marker on the map');
		}
	});
	isEditableMode = true;
}

function cancelEditableMode(){
	if($("mapeditbtn").innerHTML==_("Add Location")){
		hideElement('map_container');
        hideElement('quickpost-googlemapembed');
	}
	hideElement("mapsearchbox");

	if(marker){
		GEvent.clearListeners(marker, 'dragend');
		mapsearch.removeOverlay(marker);
		marker = undefined;
	}
	if(defaultPoint){
		point = defaultPoint
		marker = new GMarker(point);
		map.addOverlay(marker);
		map.setCenter(point, map.getZoom());
	}else{
		point = undefined;
	}
	GEvent.clearListeners(mapsearch, 'click');

	$("msgdiv").innerHTML = "";
	$("searchResultDiv").innerHTML = "";
	isEditableMode = false;
}

gLocalSearch = new GlocalSearch();
gLocalSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
gLocalSearch.setNoHtmlGeneration();
gLocalSearch.setSearchCompleteCallback(null, onLocalSearchCallback);
gLocalSearch.setCenterPoint('thailand');
var gCurrentResults = [];
var markerlist = new Array();

function searchLocation(){
	if($("searchLocationGC").value == "") return;
	showElement("postingimg");
	$("searchLocationGC").readonly = true;

	searchMobileCellLocation($("searchLocationGC").value);
}
function searchMobileCellLocation(value){
	var searchResultDiv = $("searchResultDiv");
	searchResultDiv.innerHTML = "";
	var opt = {
		parameters: {value:encodeURIComponent(value)},
		onSuccess: function(t) {
			searchResults = t.responseText.evalJSON();

			gCurrentResults.length = 0;
			if(searchResults.results.length > 0){
				if(marker){
					GEvent.clearListeners(marker, 'dragend');
					mapsearch.removeOverlay(marker);
					marker = undefined;
				}
				for (var i = 0; i < searchResults.results.length; i++) {
					var localResult = new LocalResult(searchResults.results[i])
					gCurrentResults.push(localResult);
				}

				var first = searchResults.results[0];
				point = new GLatLng(Number(first.lat), Number(first.lng));
				marker = new GMarker(point, {draggable: true});
				GEvent.addListener(marker, "dragend", function(){
					point = marker.getLatLng();
				});

				mapsearch.addOverlay(marker);
				mapsearch.panTo(point);
			}
			gLocalSearch.execute(value);
		},
		onFailure: function(t) {
			gLocalSearch.execute(value);
		}
	}
	new Ajax.Request("/"+page+"/searchMobileCellLocationName", opt);
}
function onLocalSearchCallback(){
	var searchResultDiv = $("searchResultDiv");

	if (gLocalSearch.results && gLocalSearch.results.length > 0){
		var attribution = gLocalSearch.getAttribution();
		if(attribution){
			searchResultDiv.appendChild(attribution);
		}

		if(gCurrentResults.length == 0){
			if(marker){
				GEvent.clearListeners(marker, 'dragend');
				mapsearch.removeOverlay(marker);
				marker = undefined;
			}

			var first = gLocalSearch.results[0];
			point = new GLatLng(Number(first.lat), Number(first.lng));
			marker = new GMarker(point, {draggable: true});
			GEvent.addListener(marker, "dragend", function(){
				point = marker.getLatLng();
			});
			mapsearch.addOverlay(marker);
			mapsearch.panTo(point);
		}

		for (var i = 0; i < gLocalSearch.results.length && gCurrentResults.length <= 15; i++) {
			var localResult = new LocalResult(gLocalSearch.results[i])
			gCurrentResults.push(localResult);
		}
	}
	
	GEvent.clearListeners(mapsearch, 'click');
	if(gCurrentResults.length > 0){
		$("msgdiv").innerHTML = _('Location name match on search keyword');
		showElement("mapsavebtn");
		showElement("locationNameContainer");
	}else{
		if(defaultPoint && $("searchLocationGC").value == $("Location").innerHTML){
			if(marker){
				GEvent.clearListeners(marker, 'dragend');
				mapsearch.removeOverlay(marker);
				marker = undefined;
			}
			point = defaultPoint;
			marker = new GMarker(point, {draggable: true});
			GEvent.addListener(marker, "dragend", function(){
				point = marker.getLatLng();
			});
			mapsearch.addOverlay(marker);
			mapsearch.panTo(point);
			$("msgdiv").innerHTML = _('Drag and drop marker on the map');
		}else{
			if(marker){
				$("msgdiv").innerHTML = _('Cannot find location');
			}else{
				hideElement("mapsavebtn");
				hideElement("locationNameContainer");
				GEvent.addListener(mapsearch, 'click', function(overlay, p){
					if (p){
						point = p;
						if(marker){
							GEvent.clearListeners(marker, 'dragend');
							mapsearch.removeOverlay(marker);
							marker = undefined;
						}
						marker = new GMarker(point, {draggable: true});
						GEvent.addListener(marker, "dragend", function(){
							point = marker.getLatLng();
						});
						mapsearch.addOverlay(marker);
						mapsearch.panTo(point);
						showElement("mapsavebtn");
						showElement("locationNameContainer");
						$("msgdiv").innerHTML = _('Drag and drop marker on the map');
					}
				});
				$("msgdiv").innerHTML = _('Click on the map in order to add a marker');
			}
		}
	}
	hideElement("postingimg");
}

function LocalResult(result) {
	this.result_ = result;
	this.resultNode_ = this.createResultNode();
	$("searchResultDiv").appendChild(this.resultNode_);
}

LocalResult.prototype.createResultNode = function() {
	var li = document.createElement("li");
	var a = document.createElement("a");
	a.href = "javascript:void(0);";
	a.innerHTML = this.result_.title;
	li.appendChild(a);

	GEvent.bindDom(a, "click", this, function() {
		if(marker){
			GEvent.clearListeners(marker, 'dragend');
			mapsearch.removeOverlay(marker);
			marker = undefined;
		}

		point = new GLatLng(Number(this.result_.lat), Number(this.result_.lng));
		marker = new GMarker(point, {draggable: true});
		GEvent.addListener(marker, "dragend", function(){
			point = marker.getLatLng();
		});
		mapsearch.addOverlay(marker);
		mapsearch.panTo(point);
	});
	return li;
}

function submitenter(input,e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return;

	if (keycode == 13){
	   searchLocation();
	   input.focus();
	   input.select();
	}
}

function updateLocation(){
	hideElement("mapsearchbox");

	if(point == undefined) return;

	var opt = {
		parameters: {
			id: videoidtmp,
			Name: $("locationName").value,
			Latitude: point.lat(),
			Longtitude: point.lng(),
            Zoom: mapsearch.getZoom()
		},
		onSuccess: function(result) {
			$("mapeditbtn").innerHTML = _("Edit Location");

			if(marker){
				GEvent.clearListeners(marker, 'dragend');
				mapsearch.removeOverlay(marker);
				marker = undefined;
			}
			GEvent.clearListeners(mapsearch, 'click');
			
			defaultPoint = point;
			marker = new GMarker(point);
			map.addOverlay(marker);
			map.setCenter(point, mapsearch.getZoom());

			$("Location").innerHTML = $("locationName").value.escapeHTML();
			$("msgdiv").innerHTML = "";
			isEditableMode = false;
		},
		onFailure: function(t) {
			$("infotext").innerHTML = _('The location cannot be editted');
			showElement("infobox");
		}
	}
	new Ajax.Request("/"+page+"/updateLocation", opt);

	$("msgdiv").innerHTML = "";
	$("searchResultDiv").innerHTML = "";
}

function sendPM(id)
{
	var topic = $('topic'+id).value;
	var message = $('msg'+id).value;
	var targetid = $('huid'+id).value;
	var postdata = "userid=" + owneridtmp + "&targetid=" + targetid + "&topic="+ encodeURIComponent(topic) + "&message=" + encodeURIComponent(message);
	var posturl = "/sendPrivateMessage";
	hideElement('p'+id);
	var opt = {
			method: 'post',
			postBody: postdata,
			onSuccess: function(t) {
				$('topic'+id).value = "";
				$('msg'+id).value = "";
				if (t.responseText=="Success")
				{
					$('infotext').innerHTML = _('Send message completed');
					showElement('infobox');
					$('infobox').focus();	
				}
			},
			onFailure: function(t) {
				$('topic'+id).value = "";
				$('msg'+id).value = "";
				$('infotext').innerHTML = _("Cannot send message");
				showElement('infobox');
				$('infobox').focus();
			}
		  }
	new Ajax.Request(posturl, opt);
}

function saveTags(value){
		if(videoidtmp!='')
		{
				$("Tags").innerHTML = 'Save...'
				var opt = {
					method: 'post',
					postBody: 'value=' + encodeURIComponent(value),
					onSuccess: function(t) {
						if(t.responseText == ''){
							$("Tags").innerHTML = _('Click here to edit tags');
						}
						else{
							$("Tags").innerHTML =  t.responseText;
						}
					},
					onFailure: function(t) {
					}
				}
				new Ajax.Request('/video/edit/'+ videoidtmp +'/tag', opt);
		}
}

//sendImproper
function sendImproper(){
    var opt = {
        method: 'post',
        postBody: 'id=' + videoidtmp ,
        onSuccess: function(t) {
			if (t.responseText=="Improper"){
                $('infotext').innerHTML = _("This video has been set to improper");
            }
            else if (t.responseText=="OK"){
                $('infotext').innerHTML = _("This video has been reported as improper");
            }
            else if (t.responseText=="Repeatedly"){
                $('infotext').innerHTML = _("You have already reported this video as improper");
            }
            else if (t.responseText=="False"){
                $('infotext').innerHTML = _("You have already reported this video as improper");
            }
            else {
            }
            showElement('infobox');
            $('infobox').focus();
        },
        onFailure: function(t) {}
    }
    new Ajax.Request('/video/setImproper', opt);
}

/*stars = document.getElementsByClassName("rating_star1");
for(i = 0; i < stars.length; i++) {
stars[i].onmouseover = hoverRatingEvent;
stars[i].onmouseout = resetRatingEvent;
stars[i].onclick = clickRatingEvent;
}
*/
      
//]]>
