checkFlashVersion();

var VideoPlayer = {
	objectId : 'videoPlayer',
	movieId : null,
	movieTitle : '',
	currentRatingClassName :'',
	currentDetailsName :'',
	rated : false,
	reportAsInappropriate : false,
	showMessage : true,
	jumpToTop : true,
	height : 200,
	action : '',
	userRating : 0,
	pendingRate : -1,
	movieRated : false,
	movieLoaded : false
};

var videoPlayerTimer = null;

VideoPlayer.getFlashMovie = function(movieName)
{
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
};

VideoPlayer.loadMovie = function(id, jumpToTop)
{
	if(!isNaN(id)){
		VideoPlayer.movieId = id;
		doAJAXGet('/ajax/getMovie.php','movieId='+id, 'VideoPlayer.setAndPlay');
		VideoPlayer.jumpToTop = jumpToTop;
		
		VideoPlayer.getRatingAttrbutes(id);
	}
};

var vCounter = 0;
VideoPlayer.loadFile = function(url,uid,movieId,thumbnail)
{
	if(VideoPlayer.movieLoaded) return;
	
	clearTimeout(videoPlayerTimer);
	var serverURL = getServerURL();
	var player = VideoPlayer.getFlashMovie(VideoPlayer.objectId);
	if(player && player.loadFile && vCounter++>1){
		player.loadFile(url,uid,movieId,thumbnail,serverURL);
		if(videoPlayerTimer){
			clearTimeout(videoPlayerTimer);
		}
	}else {
		videoPlayerTimer = setTimeout("VideoPlayer.loadFile('"+url+"',"+uid+","+movieId+",'"+thumbnail+"','"+serverURL+"')",500);
	}
};

VideoPlayer.setAndPlay = function(res){
	var result = json_decode(res.responseText);
	if(document.forms['frmVideoPlayer']){
		var form = document.forms['frmVideoPlayer'];
		form.elements['movieId'].value = result.id;
		if(form.elements['comment'].getAttribute('oValue')){
			form.elements['comment'].value = form.elements['comment'].getAttribute('oValue');
		}
		else {
			form.elements['comment'].value = '';
		}
	}

	VideoPlayer.loadFile(result.url,result.uid,result.id,result.large_thumb);
	VideoPlayer.movieTitle = result.title;
	var rTitle = (result.title)?result.title:'';
	var playerTitle = (rTitle.length>45) ? rTitle.substring(0,45)+'...' : rTitle;
	if(playerTitle!=rTitle){
		if($j('player_title')){
			$j('player_title').title = rTitle;
		}
	}
	var playerFrom = (result.from.length>36) ? result.from.substring(0,36)+'...' : result.from;
	if(playerFrom!=result.from){
		if($j('player_from')){
			$j('player_from').title = result.from;
		}
	}
	
	if(result.status=='LIVE') {
		$('#videoPlayerContainer').removeClass().addClass('festival');
	}
	else {
		$('#videoPlayerContainer').removeClass().addClass('filmedia');
	}
	
	// set values
	with(VideoPlayer){
		movieId = result.id;
		rated = result.ratedThisMovie;
		setValue('movieInfo_title', rTitle);
		setValue('movieInfo_director', result.director);
		setValue('movieInfo_producer', result.producer);
		setValue('movieInfo_country', result.country);
		setValue('movieInfo_genre', result.genre);
		setValue('movieInfo_year', result.year);
		setValue('movieInfo_synopsis', result.synopsis);
		setValue('player_title', playerTitle);
		setValue('player_from', '<a href="/storyteller/'+result.screenName+'">'+playerFrom+'</a>&nbsp;');
		setValue('player_viewed', result.viewed);
		setValue('player_favoriated', result.favorites);
		setNumComments(result.numComments);
		setRating(result.rating);
		setUserRating(result.userRating);
		setNumShared(result.numShared);
		setNumTweets(result.numTweets);
		setEmbedScript(result.id,result.url,result.large_thumb,rTitle,result.from);
		setShareLink(result.id,result.playerLink);
		reportInappropriateMovieHandler(result.reportedAsBadMovie);
	}
	if($j('icon_info')){
		VideoPlayer.showInfo('icon_info',1);
	}
	if($j('details_rating_done')) {
		$j('details_rating_done').className = 'details_rate_' + result.userRating;
	}
	
	VideoPlayer.movieRated = result.movieRated;
	
	if(VideoPlayer.movieRated)
		VideoPlayer.disableRatingForm();
	
	if(VideoPlayer.action!=''){
		switch(VideoPlayer.action){
			case 'rate':
				showRollOverIconSet('icon_rate');
				VideoPlayer.showInfo('icon_rate');
				break;
			case 'inappropriate':
				showRollOverIconSet('icon_inappropriate');
				VideoPlayer.showInfo('icon_inappropriate');
				break;
			case 'comment':
				if(savedComment) {
					$j('comment').value = savedComment;
					alert('Please click POST to submit your comment.');
					window.location = '#videoDetail';
				}
				break;
			case 'share':
				showRollOverIconSet('icon_share');
				VideoPlayer.showInfo('icon_share');
				break;
			case 'show_comments':
				VideoPlayer.getComments();
				window.location = '#videoDetail';
				break;
		}
		VideoPlayer.action = '';
	}
	else {	
		if(VideoPlayer.jumpToTop){
			window.location='#';
		}
	}
	VideoPlayer.jumpToTop = true;
};

VideoPlayer.setValue = function(id,value)
{
	if($j(id)){
		$j(id).innerHTML = value;
	}
};

VideoPlayer.setRating = function(num)
{
	if($j('rating')){
		$j('rating').className = 'rate_' + Math.floor(num);
	}
};

VideoPlayer.setNumComments = function(num)
{
	VideoPlayer.setValue('commentCount', 'TOTAL: '+num);
};

VideoPlayer.setUserRating = function(num)
{
	if($j('details_rating')){
		VideoPlayer.currentRatingClassName = 'details_rate_'+num;
		VideoPlayer.restoreRating();
		userRating = num;
	}
};

VideoPlayer.setNumShared = function(num)
{
	if($j('player_shared')){
		$j('player_shared').innerHTML = num;
	}
};

VideoPlayer.setNumTweets = function(num)
{
	if($j('player_tweets')){
		$j('player_tweets').innerHTML = num;
	}
};

VideoPlayer.setEmbedScript = function(id, filename,thumb,title,from)
{
	var videoLink = getServerURL()+'/documentary/watch-online/play/'+VideoPlayer.movieId+'/'+title.replace(/[^0-9a-zA-Z]/,'-');
	if($j('embed_script')){
		//*
		$j('embed_script').value =  '<div style="width:400px"><embed src="'+getServerURL()+'/swf/embedplayer.swf"'
			+ ' flashvars="video='+filename.replace(' ', '%20')+'&m='+id+'&u=0&thumb='+thumb+'&sURL='+getServerURL()+'&title='+title+'&from='+from+'"'
			+ ' width="400" height="300" quality="high" salign="b" allowScriptAccess="always" allowFullScreen="true" name="cultureUnpluggedPlayer"'
			+ ' align="middle" wmode="transparent" type="application/x-shockwave-flash"'
			+ ' pluginspage="http://www.macromedia.com/go/getflashplayer" ></embed>'
			+ '<div style="margin-top:5px;text-align:center"><a href="'+videoLink+'" target="_blank">View this movie at cultureunplugged.com</a></div></div>';
		//*/
		/*$j('embed_script').value =  '<iframe frameborder="0" border="0" allowtransparency="true" width="400" height="320"'
			+ ' src="'+getServerURL()+'/embed.php?width=400&height=320&'
			+ '	video='+filename.replace(' ', '%20')+'&m='+id+'&u=0&thumb='+thumb+'&sURL='+getServerURL()+'&title='+title+'&from='+from+'"'
			+ '></iframe>';
		*/
	}
	
	if($j('PutWidgetHere')){
		$j('PutWidgetHere').value = $j('embed_script').value;
	}
};

VideoPlayer.setEmbedSize = function(size){
	var val = $j('embed_script').value;
		
	if(size=='l'){
		val = val.replace('width="400"', 'width="700"');
		val = val.replace('height="320"', 'height="480"');
		val = val.replace('width=400', 'width=700');
		val = val.replace('height=320', 'height=480');
	}
	else {
		val = val.replace('width="700"', 'width="400"');
		val = val.replace('height="480"', 'height="320"');
		val = val.replace('width=700', 'width=400');
		val = val.replace('height=480', 'height=320');
	}
	
	$j('embed_script').value = val;
	
	if($j('PutWidgetHere')){
		$j('PutWidgetHere').value = $j('embed_script').value;
	}
	
	if($j('details_embed')) {
		$j('details_embed').style.display = 'none';
		setTimeout("$j('details_embed').style.display = 'block';",200);
	}
}

VideoPlayer.setShareLink = function(id,playerlink)
{
	var link = '';
	if($j('frmShare')){
		$j('frmShare').movieId.value = id;
		var url = $j('frmShare').shareLink.value + id + playerlink.substr(playerlink.lastIndexOf('/'),playerlink.length);
		var text = url;
		if(text.length>60){
			/*var ndx = text.lastIndexOf('?');
			if(ndx>=60){
				ndx = text.lastIndexOf('/');
			}
			*/
			var ndx = text.lastIndexOf('/');
			text = text.substring(0,ndx)+'<br/>'+text.substring(ndx,text.length);
		}
		link = '<a href="'+url+'" target="_blank">' + text + '</a> ';
	}
	if($j('mailLink')) {
		$('#mailLink').click(function(){
			$.get('/ajax/getMovie.php', { movieId:id}, function(data){
					var subject = 'discover this film on Culture Unplugged...';
					var body = "Dear friend,\n\n";
					body += "I have found an interesting documentary "+data.title+" on Culture Unplugged and want to share with you.\n\n";
					body += "http://www.cultureunplugged.com/documentary/watch-online/play/" + id +"\n\n";
					body += "Director:  "+data.director+"  |  Producer: "+data.producer+"\n\n";
					body += "Genre: "+data.genre+"  |  Produced In: "+data.year+"  |  Country: "+data.country+"\n\n";
					body += "Synopsis: " + data.synopsis +"\n\n\n";
					body += "Hope you Enjoy!\n";
					body += "promote films. promote consciousness.\n\n";
					body += "Culture Unplugged\n\n";
					
					
					location = 'mailto:?subject='+encodeURI(subject)+'&body='+encodeURIComponent(body);
			}, 'json');
			
			return false;
		});
		//$j('mailLink').href = 'mailto:?subject=You%20have%20received%20a%20Cultureunpluggged%20video&body=http%3A//cutv.ws/'+id;
	}
	
	VideoPlayer.setValue('shareLink', link);
};

VideoPlayer.preview = function(id)
{
	if(isNaN(id)) {
		return;
	}
	
	// for filmedia profile page
	var jumpToTop = true;
	if(window.switchMyFilmView){
		switchMyFilmView('full');
		jumpToTop = false;
		window.location = '#mainPlayer';
	}
	
	if(!$j('videoPlayer')){
		//window.location = '/index.php?viewMovieId='+id;
		window.location = '/documentary/watch-online/play/'+id;
	}
	else if(VideoPlayer.movieId != id) {
		VideoPlayer.loadMovie(id, jumpToTop);
	}else {
		window.location = '#mainPlayer';
	}
}

VideoPlayer.showRating = function(num)
{
	if(VideoPlayer.movieRated || VideoPlayer.isUninspiringSelected()) return;
	
	$style('details_inappropriate_done').display = 'none';
	
	var div = $j('details_rating');
	VideoPlayer.currentRatingClassName = div.className;
	div.className = 'details_rate_' + num;
	
	if($j('rating_indicator')){
		$j('rating_indicator').className = 'rating_ind_' + num;
	}
}

VideoPlayer.restoreRating = function(){
	$j('details_rating').className = VideoPlayer.currentRatingClassName;

	if($j('rating_indicator')){
		var name = VideoPlayer.currentRatingClassName;
		var num = name.substring(name.length-1, name.length);
		if(isNaN(num)) num = 1;
		$j('rating_indicator').className = 'rating_ind_' + num;
	}
};

VideoPlayer.restoreUserRating = function() {
	VideoPlayer.setUserRating(userRating);
	VideoPlayer.pendingRate = -1;
};

VideoPlayer.submitRating = function(num){	
	if(VideoPlayer.isUninspiringSelected()) return;
	VideoPlayer.currentRatingClassName = $j('details_rating').className;
	
	VideoPlayer.pendingRate = num;
};

VideoPlayer.confirmSubmitRating = function(num) {	
	/*
	$j('details_rating_done').className = VideoPlayer.currentRatingClassName;
	$style('details_rate').display = 'none';
	$style('details_rate_done').display = '';
	VideoPlayer.currentDetailsName = 'details_rate_done';
	VideoPlayer.rated = true;
	*/

	doAJAXGet('/ajax/rateTheMovie.php','movieId='+VideoPlayer.movieId+'&rating='+num,'VideoPlayer.submitRatingHandler');
	VideoPlayer.pendingRate = -1;
	VideoPlayer.updateRatingAttribute();
	VideoPlayer.disableRatingForm();
	
}

VideoPlayer.disableRatingForm = function() {
	VideoPlayer.movieRated = true;
	$('#btnRateSubmit').hide();
	
	var form = document.forms['frmRateCategory']; 
	if(form)
	{
		for(var i=0;i<form.elements.length;i++){
			var elm = form.elements[i];
			if(elm.type=='checkbox'){
				FormHandler.selectCheckbox(elm, false);
				elm.disabled = true;
			}
		}
	}
}

VideoPlayer.showConfirmRatingPopUp = function()
{
	if(VideoPlayer.movieRated) return;
	
	var attrs = VideoPlayer.getRatingAttributes();
	
	if(attrs=='' && VideoPlayer.pendingRate==-1){
		alert('Please select at least one attribute or click trophie to rate this movie.');
		return;
	}
	
	var id = 'popupConfirmRating';
	var url = 'confirmVideoRating.php?num='+VideoPlayer.pendingRate+'&id='+VideoPlayer.movieId+'&attr='+VideoPlayer.getRatingAttributes();
	if(!popUps[id]) {
		popUps[id] = new PopUpWindow(id, url, 420, 200);
		popUps[id].remoteServer = false;
		popUps[id].showCloseButton = false;
	}
	else {
		popUps[id].url = url;
	}

	if(attrs!='' && VideoPlayer.pendingRate!=-1){
		popUps[id].height = 320;
	}
	else {
		popUps[id].height = 200;
	}
	popUps[id].show();
}

VideoPlayer.submitRatingHandler = function(res)
{
	var result = json_decode(res.responseText);
	if(result.isOK) {
		VideoPlayer.setRating(result.result.rating);
		VideoPlayer.setUserRating(result.result.userRating);
	}
	
	VideoPlayer.showInfo('icon_info');
	VideoPlayer.rated = true;
	VideoPlayer.movieRated = true;
};

VideoPlayer.addToMyFavorite = function(id)
{
	if($j('details_inappropriate_done')){
		$style('details_inappropriate_done').display = 'none';
	}
	doAJAXGet('/ajax/addToFavorite.php','movieId='+id,'VideoPlayer.addToFavoriteHandler');
};

VideoPlayer.showInfo = function(divId, autoLoad) {
	$style('details_inappropriate_done').display = 'none';
	
	var showDetail = typeof(autoLoad)=='undefined' ? true: false;
	var divName = divId.replace('icon_','details_');
	var currentDivIcon = VideoPlayer.currentDetailsName.replace('details_','icon_');
	VideoPlayer.resetHeight();
	
	if($j(divName)){
		
		if(divName=='details_rate' && VideoPlayer.rated){
			//divName = 'details_rate_done';
			alert("You have already rated this movie.\nThank you!");
			return;
		}
		else if(divName=='details_inappropriate' && VideoPlayer.reportAsInappropriate){
			divName = 'details_inappropriate_done';
		}
		else if(divName=='details_watchLater') {
			VideoPlayer.addToWatchLater();
			return;
		}
		else if(divName=='details_favorite'){
			VideoPlayer.addToMyFavorite(VideoPlayer.movieId);
			return;
		}
		else if(divName=='details_contribute'){
			showContributionForm();
			if(showDetail) {
				window.location = '#videoDetail';
			}
			return;
		}
		
		
		if(VideoPlayer.currentDetailsName!=''){
			$style(VideoPlayer.currentDetailsName).display = 'none';
		}

		
		if(divName=='details_embed'){
			VideoPlayer.selectEmbedSize('s');
			//$('#embedSizeLabel1').addClass('RadioSelected');
			//$('#embedSizeLabel2').removeClass('RadioSelected');
			//$('#embedSizeLabel1').attr('checked',true);
			//$('#embedSizeLabel2').attr('checked',false);
			$('#embedSizeContainer').show();
			
			VideoPlayer.setEmbedSize($('#embedSize1').val());
		}
		else {
			$style(divName).display = '';
		}
		
		VideoPlayer.currentDetailsName = divName;
		// set height
		VideoPlayer.setHeight(divName);
		// captcha of share link
		VideoPlayer.resetCaptchaTotal();
	}
	selectIconSet(divId);
	if(showDetail){
		window.location = '#videoDetail';
	}
}

VideoPlayer.resetHeight = function()
{
	//$style('section_2').height = VideoPlayer.height +'px';
}

VideoPlayer.setHeight = function(divName)
{
	/*
	if($j(divName).offsetHeight > 150){
		var h = $j('section_2').offsetHeight + $j(divName).offsetHeight - 150;
		$style('section_2').height  = h + 'px';
	}
	*/
}

VideoPlayer.getComments = function(page){
	if(currentSelectedIcon!=null) {
		currentSelectedIcon.setAttribute('oSelected',false);
		showNormalIconSet(currentSelectedIcon.id);
	}
	if(VideoPlayer.currentDetailsName!=''){
		$style(VideoPlayer.currentDetailsName).display = 'none';
	}
	doAJAXGet('/ajax/getComments.php','movieId='+VideoPlayer.movieId+'&page='+page,'VideoPlayer.showComments');
	$style('details_comments').display = '';
	VideoPlayer.currentDetailsName = 'details_comments';
};

VideoPlayer.showComments = function(res){
	$j('details_comments').innerHTML = res.responseText;
	VideoPlayer.setHeight('details_comments');
	
	if($j('totalComments')){
		var total = $j('totalComments').innerHTML;
		VideoPlayer.setNumComments(total);
	}
};

VideoPlayer.submitShowMessage = function(val) {
	if(val=='Y') {
		setCUCookie('showWatchLaterMsg',1,365,'/');
		$j('iconWatchLater_y').src=  imagePath+'/icon_radio_on.gif';
		$j('iconWatchLater_n').src=  imagePath+'/icon_radio_off.gif';
		VideoPlayer.showMessage = true;
	}
	else {
		setCUCookie('showWatchLaterMsg',0,365,'/');
		$j('iconWatchLater_y').src=  imagePath+'/icon_radio_off.gif';
		$j('iconWatchLater_n').src=  imagePath+'/icon_radio_on.gif';
		VideoPlayer.showMessage = false;
	}
};

VideoPlayer.reportInappropriateMovie = function(val){
	if(val=='Y') {
		$j('iconInappropriate_y').src=  imagePath+'/icon_radio_on.gif';
		$j('iconInappropriate_n').src=  imagePath+'/icon_radio_off.gif';
		doAJAXGet('/ajax/reportInappropriateMovie.php','movieId='+VideoPlayer.movieId);
		VideoPlayer.reportAsInappropriate = true;
		$style('details_inappropriate').display = 'none';
		$style('details_inappropriate_done').display = '';
	}
	else {
		$j('iconInappropriate_y').src=  imagePath+'/icon_radio_off.gif';
		$j('iconInappropriate_n').src=  imagePath+'/icon_radio_off.gif';
		VideoPlayer.showInfo('icon_info');
	}
};

VideoPlayer.reportInappropriateMovieHandler = function(res)
{
	VideoPlayer.reportAsInappropriate = res;
};

var commentForm;

VideoPlayer.submitComment = function(form, value)
{
	commentForm = form;
	if(!isValueUpdated(form.comment)) {
		alert('Please enter your comment.');
	}
	else if(hasValidEmail(form.comment.value)) {
		alert('Email address is not allowed in the comment.');
	}
	else if(hasHyperLink(form.comment.value)) {
		alert("Your comments are valuable.\n\nThe system did not allow posting of you comment due to one of the following reasons:\n\n- You may have entered hyperlink or special characters.\n- You may have missed a space between words or period.\n\nSo please review and correct appropriately to post your comment.\n\nThank you");
	}
	else {
		if($j('txtPost')) $style('txtPost').display = 'inline';			
		$style('post').display = 'none';
		
		if(window.showFacebookFeedForm){
			showFacebookFeedForm(form);
			$.post('/ajax/addComment.php', $(form).serialize(), VideoPlayer.restorePostButton, 'json');
		}
		else {
			$.post('/ajax/addComment.php', $(form).serialize(), VideoPlayer.submitCommentHandler, 'json');
		}
	}
	return false;
};

VideoPlayer.submitCommentHandler = function(result)
{
	alert(result.message);
	
	commentForm.comment.value = '';
	
	if($j('txtPost')) $style('txtPost').display = 'none';			
	$style('post').display = '';
	VideoPlayer.getComments(1);
};

VideoPlayer.submitRecommand = function(form, value)
{
	commentForm = form;
	
	if(window.showFacebookFeedForm){
		showFacebookFeedForm(form);
	}
	else {
		alert('You have to login with your facebook account.');
	}
	return false;
};


VideoPlayer.restorePostButton = function(res)
{
	if($j('txtPost')) $style('txtPost').display = 'none';			
	$style('post').display = '';
};

VideoPlayer.addToFavoriteHandler = function(res)
{
	var result = json_decode(res.responseText);
	if(result.isOK) {
		favorites = [];
		alert(result.message);
		VideoPlayer.setValue('player_favoriated', result.result);
	}
	else {
		showLoginForm('pf=favorite:'+VideoPlayer.movieId);
	}
};

VideoPlayer.inappropriateComment = function(commentId)
{
	doAJAXGet('/ajax/flagInappropriateComment.php', 'commentId='+commentId, 'VideoPlayer.onFlagInappropriateComment');
};

VideoPlayer.inappropriateComment2 = function(commentId)
{
	doAJAXGet('/ajax/flagInappropriateComment.php', 'commentId='+commentId, 'VideoPlayer.onFlagInappropriateComment2');
};

VideoPlayer.onFlagInappropriateComment = function(req)
{
	var res = json_decode(req.responseText);
	if(!res.isOK) {
		if(res.needLogin) {
			showLoginForm('ic=inappropriateComment:'+res.commentId);
			return;
		}
		else {
			alert(res.message);
		}
	}
	else {
		VideoPlayer.getComments();
	}
};

VideoPlayer.onFlagInappropriateComment2 = function(req)
{
	var res = json_decode(req.responseText);
	if(!res.isOK) {
		if(res.needLogin) {
			showLoginForm('ic=inappropriateComment:'+res.commentId);
			return;
		}
		else {
			alert(res.message);
		}
	}
	else {
		window.location.reload(true);
	}
};

VideoPlayer.sendShareLink = function(form)
{
	
	if(form.captchaTotal.value==''){
		alert('Please enter sum of two numbers.');
		return false;
	}
		
	var error = false;
	var hasValidEmail = form.elements['emails'].value!='';
	/*
	for(var i=0;i<form.elements.length;i++){
		var elm = form.elements[i];
		if(elm.type=='text' && elm.name!='captchaTotal'){
			if(elm.value!='' && elm.value!=elm.getAttribute('oValue')){
				elm.value = trim(elm.value);
				if(!isValidEmail(elm.value)){
					error = true;
				}
				else {
					hasValidEmail = true;
				}
			}
		}
	}
	*/
	
	if(error){
		alert('Invalid email address.');
	}
	else if(!error && hasValidEmail){
		// submit form
		doAJAXPost(form.action, form, 'VideoPlayer.onSendShareLink');
		form.btnSend.style.display = 'none';
		$style('msgSend').display = '';
	}
	else {
		alert('Please enter email adress.');
	}
	return false;
}

VideoPlayer.resetCaptchaTotal = function()
{		
	reloadImage($j('captchaDigit_0'));
	reloadImage($j('captchaDigit_1'));
	if($j('captchaTotal')){
		$j('captchaTotal').value = '';
	}
}

VideoPlayer.onSendShareLink = function(req)
{
	var res = json_decode(req.responseText);
	VideoPlayer.setNumShared(res.result.numShared);
	VideoPlayer.resetCaptchaTotal();
	/*
	$j('email1').value = $j('email1').getAttribute('oValue');
	$j('email2').value = $j('email2').getAttribute('oValue');
	$j('email3').value = $j('email3').getAttribute('oValue');
	$j('email4').value = $j('email4').getAttribute('oValue');
	$j('email5').value = $j('email5').getAttribute('oValue');
	*/
	if(res.isOK) 
		$j('emails').value = $j('emails').getAttribute('oValue');
	$j('frmShare').elements['btnSend'].style.display = '';
	$style('msgSend').display = 'none';
	alert(res.message);
}

VideoPlayer.addToWatchLater = function()
{
	doAJAXGet('/ajax/addToWatchLater.php','movieId='+VideoPlayer.movieId,'VideoPlayer.onAddToWatchLaterHandler');
}

VideoPlayer.onAddToWatchLaterHandler = function(req)
{
	$style('details_inappropriate_done').display = 'none';
	
	var res = json_decode(req.responseText);
	selectIconSet('icon_watchLater');
	
	if(!res.isOK){
		if(res.needLogin){
			VideoPlayer.currentDetailsName = 'details_watchLater';
			showLoginForm('pf=watchLater:'+VideoPlayer.movieId);
			return;
		}
		else {
			alert(res.message);
		}
	}else {
		$j('watchLaterMessage').innerHTML = res.message;
	}
	
	var ck = readCookie('showWatchLaterMsg');
	var showMsg = ck==1 || ck=='' || ck==null;
	if(VideoPlayer.showMessage && showMsg){
		if(VideoPlayer.currentDetailsName!=''){
			$style(VideoPlayer.currentDetailsName).display = 'none';
		}
		VideoPlayer.currentDetailsName = 'details_watchLater';
	
		$style('details_watchLater').display = '';
		window.location = '#videoDetail';
	}
}

VideoPlayer.selectEmbedSize = function(size) {
	if(size=='s'){
		$('#embedSizeLabel1').addClass('RadioSelected');
		$('#embedSizeLabel2').removeClass('RadioSelected');
		$('#embedSizeLabel1').attr('checked',true);
		$('#embedSizeLabel2').attr('checked',false);
		$('#embedSize1').attr('checked',true);
		$('#embedSize2').attr('checked',false);
	}
	else {
		$('#embedSizeLabel1').removeClass('RadioSelected');
		$('#embedSizeLabel2').addClass('RadioSelected');
		$('#embedSizeLabel1').attr('checked',false);
		$('#embedSizeLabel2').attr('checked',true);
		$('#embedSize1').attr('checked',false);
		$('#embedSize2').attr('checked',true);
	}
}

VideoPlayer.getRatingAttributes = function()
{
	var form = document.forms['frmRateCategory'];
	if(form){
		var checkedAttributes = [];
		for(var i=0;i<form.elements.length;i++){
			var elm = form.elements[i];
			if(elm.type=='checkbox' && elm.checked){
				checkedAttributes.push(elm.value);
			}
		}
		
		return checkedAttributes.join('|');
	}
	
	return '';
}

VideoPlayer.updateRatingAttribute = function()
{
	var form = document.forms['frmRateCategory'];
	if(form){
		var checkedAttributes = [];
		for(var i=0;i<form.elements.length;i++){
			var elm = form.elements[i];
			if(elm.type=='checkbox' && elm.checked){
				checkedAttributes.push(elm.value);
			}
		}
		
		if(checkedAttributes.length<1){
		//	alert('Please select at least one attribute.');	
		}
		else {
			var attrIds = checkedAttributes.join('|');
			
			doAJAXGet('/ajax/updateMovieRatingAttributes.php','movieId='+VideoPlayer.movieId+'&attrIds='+attrIds, VideoPlayer.onUpdateAttribute);
		}
	}
	
}

VideoPlayer.getRatingAttrbutes = function(movieId) {
	doAJAXGet('/ajax/updateMovieRatingAttributes.php','movieId='+movieId,VideoPlayer.onUpdateAttribute);
}

VideoPlayer.onUpdateAttribute = function(req) {
	var res = json_decode(req.responseText);
	for(var i=0;i<res.length;i++){
		var arr = res[i].split('|');
		var attrId = arr[0];
		var counter = arr[1];
		var div = $j('rateCounter'+attrId);
		if(div){
			div.innerHTML = '('+counter+')';
		}
	}
}

VideoPlayer.unCheckOtherAttributes = function(checked) {
	var form = document.forms['frmRateCategory']; 
	if(form && checked)
	{
		for(var i=0;i<form.elements.length;i++){
			var elm = form.elements[i];
			if(elm.type=='checkbox' && elm.value!=0){
				FormHandler.selectCheckbox(elm, false);
				elm.checked = false;
			}
		}
	}
}

VideoPlayer.unCheckNone = function() {
	var form = document.forms['frmRateCategory']; 
	if(form){
		var elm = form.elements['rateCat0'];
		if(elm.checked) {
			FormHandler.selectCheckbox(elm, false);
			elm.checked = false;
		}
	}
}

VideoPlayer.isUninspiringSelected = function()
{
	var form = document.forms['frmRateCategory']; 
	if(form){
		for(var i=0;i<form.elements.length;i++){
			var elm = form.elements[i];
			if(elm.type=='checkbox' && elm.value==0){
				return elm.checked;
			}
		}
	}
	
	return false;
}

function showRequestOnlineScreening(movieId, filmMakerName) {
	var id = 'dlgShowRequestOnlineScreeningPopup';
	var url = 'requestOnlineScreening.php?movieId='+movieId;
	var title = 'To: ' + decodeURIComponent(filmMakerName.replace('+',' '));
	
	if(!dialogPopUps[id]){
		dialogPopUps[id] = new PopUpDialog(id, title, url, 380,300);
		dialogPopUps[id].offsetX = 30;
		dialogPopUps[id].remoteServer = false;
	}
	dialogPopUps[id].title = title;// + title.toUpperCase();
	dialogPopUps[id].show();
}

checkFlashVersion();
var PreviewPlayer = {
thumbails:[],
setListener:false,
loadedPlayers:[],
mouseOver:false,
currentId:null
}
var previewPlayerTimer = null;
var previewVideoTimer = null;
PreviewPlayer.getFlashMovie = function(i)
{
return getFlashMovie('pp_'+i);
}
PreviewPlayer.play = function(num, url, u, m, thumb, ndx)
{
clearTimeout(previewVideoTimer);
var icon = $j('icon_preview_'+ndx);
if($j('previewPlayerThumbnail_'+ndx))
$style('previewPlayerThumbnail_'+ndx).display = 'none';
if($j('previewPlayer_'+ndx))
$style('previewPlayer_'+ndx).visibility = 'visible';
var player = PreviewPlayer.getFlashMovie(num);
if(player && player.loadFile){
if(icon.src.indexOf('preview')!=-1){
icon.src = icon.src.replace('preview','pause');
PreviewPlayer.stopOthers();
player.loadFile(url,u,m, thumb,ndx);
PreviewPlayer.loadedPlayers[ndx] = m;
}
else {
icon.src = icon.src.replace('pause','preview');
if(player.pauseVideo){
player.pauseVideo();
}
}
}
else {
previewVideoTimer = setTimeout("PreviewPlayer.play("+num+",'"+url+"',"+u+","+m+",'"+thumb+"',"+ndx+")",1000);
}
};
PreviewPlayer.addThumbnail = function(num, thumb)
{
PreviewPlayer.thumbails[num] = thumb;
if(!PreviewPlayer.setListener){
addListener(window, 'load',PreviewPlayer.loadThumbnails,false);
PreviewPlayer.setListener = true;
}
}
PreviewPlayer.loadThumbnails = function()
{
clearTimeout(previewPlayerTimer);
var num = 0;
var player = PreviewPlayer.getFlashMovie(num);
if(player.loadThumbnail) {
while(player){
if(PreviewPlayer.thumbails[num]!='' && player.loadThumbnail){
player.loadThumbnail(PreviewPlayer.thumbails[num]);
}
num++;
player = PreviewPlayer.getFlashMovie(num);
}
}
else {
previewPlayerTimer = setTimeout("PreviewPlayer.loadThumbnails",500);
}
}
PreviewPlayer.stopAll = function()
{
var i=0;
var player = PreviewPlayer.getFlashMovie(i++);
while(player!=null){
if(player.stopVideo){
player.stopVideo();
}
player = PreviewPlayer.getFlashMovie(i++);
} 
};
PreviewPlayer.stopOthers = function(movieId){
var i=0;
var player = PreviewPlayer.getFlashMovie(i++);
while(player!=null){
PreviewPlayer.toggleIcon(i-1, movieId,'preview');
if(player && player.checkMovie){
player.checkMovie(movieId);
}
player = PreviewPlayer.getFlashMovie(i++);
}
};
PreviewPlayer.pauseCurrent = function(movieId){
var i=0;
var player = PreviewPlayer.getFlashMovie(i++);
while(player!=null){
PreviewPlayer.toggleIcon(i-1, movieId,'pause');
player = PreviewPlayer.getFlashMovie(i++);
}
};
PreviewPlayer.pauseAll = function()
{
var i=0;
var player = PreviewPlayer.getFlashMovie(i++);
while(player!=null){
if(player.pauseVideo) {
player.pauseVideo();
}
var icon = $j('icon_preview_'+i);
if(icon) {
icon.src = icon.src.replace('pause','preview');
}
player = PreviewPlayer.getFlashMovie(i++);
} 
};
PreviewPlayer.toggleIcon = function(ndx,movieId,type){
if(PreviewPlayer.loadedPlayers[ndx] && PreviewPlayer.loadedPlayers[ndx]==movieId){
var icon = $j('icon_preview_'+ndx);
if(type=='preview'){
icon.src = icon.src.replace('preview','pause');
}
else {
icon.src = icon.src.replace('pause','preview');
}
}
};
PreviewPlayer.toggleFullScreen = function(num) {
var player = PreviewPlayer.getFlashMovie(num);
if(player){
player.fullscreen();
}
};
var movieInfo = [];
var movieIndex = [];
var infoTimer;
PreviewPlayer.getInfo = function(id,ndx) {
PreviewPlayer.mouseOver = true;
if(!isNaN(id)){
if(movieInfo[id]){
PreviewPlayer.pauseAll();
PreviewPlayer.showMovieInfo(id,ndx);
$style('previewPlayer_'+ndx).visibility = 'hidden';
$style('previewPlayerThumbnail_'+ndx).display = 'block';
}
else {
PreviewPlayer.currentId = id;
movieIndex[id] = ndx;
doAJAXGet('/ajax/getMovie.php','movieId='+id, 'PreviewPlayer.onGetInfo');
}
}
};
PreviewPlayer.onGetInfo = function(res) {
var result = json_decode(res.responseText);
movieInfo[result.id] = result;
var ndx = movieIndex[result.id];
if(PreviewPlayer.mouseOver && PreviewPlayer.currentId==result.id) {
PreviewPlayer.pauseAll();
PreviewPlayer.showMovieInfo(result.id, ndx);
$style('previewPlayer_'+ndx).visibility = 'hidden';
$style('previewPlayerThumbnail_'+ndx).display = 'block';
}
};
PreviewPlayer.hideMovieInfo = function(){
var popUpId = '_popUpMovieInfo';
$style(popUpId).display = 'none';
PreviewPlayer.mouseOver = false;
PreviewPlayer.currentId = null;
}
PreviewPlayer.showMovieInfo = function(id, ndx) {
var popUpId = '_popUpMovieInfo';
if(!$j(popUpId)){
var div = document.createElement('div');
div.id = popUpId;
with(div.style){
position = 'absolute';
border = '2px solid #282028';
backgroundColor = '#FFFFFF';
padding = '15px';
display = 'none';
zIndex = 900;
}
$j('wrapper').appendChild(div);
}
;
var o = findPos($j('previewContainer_'+ndx));
var x;
if($j('previewContainer_'+ndx).parentNode.className=='moviePreview'){
x = $j('previewContainer_'+ndx).parentNode.offsetLeft+30;
}
else if($j('previewContainer_'+ndx).parentNode.nodeName.toLowerCase()=='li'){
x = o.x -$j('wrapper').offsetLeft+30;
}
else if($j('previewContainer_'+ndx).parentNode.id && $j('previewContainer_'+ndx).parentNode.id=='festivalList') {
x = o.x -$j('wrapper').offsetLeft+30;
}
else {
x = $j('previewContainer_'+ndx).offsetLeft+30;
}
var y = o.y+132;
$style(popUpId).top = y + 'px';
$style(popUpId).left= x + 'px';
$j(popUpId).innerHTML = PreviewPlayer.parseMovieInfo(movieInfo[id]);
$style(popUpId).display = 'block';
};
PreviewPlayer.parseMovieInfo = function(info) {
var rating = [];
rating[0] = "background-position: -75px 0px;";
rating[1] = "background-position: -60px 0px;";
rating[2] = "background-position: -45px 0px;";
rating[3] = "background-position: -30px 0px;";
rating[4] = "background-position: -15px 0px;";
rating[5] = "background-position: -0px 0px;";
var css1 = 'style="font-size:15px;font-weight:bold"';
var css2 = 'style="font-size:13px;line-height:18px"';
var css3 = 'style="font-size:10px;line-height:15px"';
var cssRating = 'style="background-image: url(/images/filmedia/icon_rating2.gif);background-repeat: no-repeat;width:74px;height:34px;margin:5px 0px;'+rating[info.rating]+'"';
var content = '<div '+css1+'>'+info.title+'</div>';
content += '<div '+css2+'><b>Director:</b> '+info.director+'</div>';
content += '<div '+css2+'><b>Producer:</b> '+info.producer+'</div>';
content += '<div '+css2+'><b>Genre:</b> '+info.genre+'</div>';
content += '<div '+css2+'><b>Country:</b> '+info.country+'</div>';
content += '<div '+css2+'><b>Duration:</b> '+info.duration+'</div>';
content += '<div '+cssRating+'></div>';
content += '<div '+css3+'>VIEWED: '+info.viewed+'</div>';
content += '<div '+css3+'>SHARED: '+info.numShared+'</div>';
return content;
}
function initMovieInfoPopup($selector) {
if(typeof($selector)=='undefined') {
$selector = $('.previewPlayerThumbnail');}
$selector.bt({
cssClass: 'bt-tooltip',
fill: 'rgba(255,255,255,1)',
padding: 20,
strokeWidth: 2,
spikeLength: 20,
closeWhenOthersOpen: true,
offsetParent:$('body'),
width: 240,
ajaxPath: ["$(this).attr('infoUrl')"],
ajaxCache: true,
positions: ['left','right', 'bottom', 'top'],
showTip: function(box){
$(box).fadeIn(400);
},
shrinkToFit: true,
hoverIntentOpts: {
interval: 0,
timeout: 500
}
});
}

