onDomReady(function () {

	// init
    //debugger; 
	movie.initialize();
});


var movie = {
	// raiting index selected
	raite:2,
    
    inlineEditor:null,


	//timer for inbox 5 minutes call
	movieTimer:0,

	//movie.php comments tabs default
//	commentTabs:'during', // or after
//	commentPage:0,
//	commentsDuring:new Array(),
	comments:new Array(),
	isLive:false,
    movieLink:null, 
    movieLocation:"",
    currentMovieId:-1,
    
	//Light boxes
	addFriend:null,	//add friend
    maxCommentId:0,
    chatOpen:false,    
    
    
    
	fillMovieData: function(root) {
		
        movie.clearComments();
		var live = eval(root.getAttribute("live"));
		movie.isLive = live;
		if (live) {
			//$("__CommentsTitle").innerHTML = "Live Comments";
			//$("__CommentsTabs").style.display = "none";
			if ($("__Hot")) $("__Hot").innerHTML = "Live Flix";
            
		} else {
			$("__CommentsTitle").innerHTML = "Comments";
			//$("__CommentsTabs").style.display = "";
			if ($("__Hot")) $("__Hot").innerHTML = "Hot Flix";
		}
		var nodes = root.childNodes;
		var movieObject = {};
		//var commentsDuring = new Array();
		//var commentsAfter = new Array();

		for (var i=0;i<nodes.length;i++) {
			if (typeof(nodes[i].tagName) != "undefined") {
				switch (nodes[i].tagName) {
					case "Tags":
                        var tagArray = new Array();
						var tags = nodes[i].childNodes;
                        for (var t=0;t<tags.length;t++) {
							if (typeof(tags[t].tagName) != "undefined" && tags[t].firstChild != null) {
								tagArray.push("<a href='/moviesearch/search?search_string="+escape(tags[t].firstChild.nodeValue.replace(/^[ ]*/, ""))+"'>"+tags[t].firstChild.nodeValue+"</a>");
							}
						}
						movieObject["Tags"] = tagArray.join(", ");
						break;
					case "Comments":
						var comments = nodes[i].childNodes;
						try {
							for (var t=0;t<comments.length;t++)
                            {
								if (typeof(comments[t].tagName) != "undefined")
                                {
									//debugger;
                                    var commentId = comments[t].getAttribute("id"); 
                                    if(commentId > movie.maxCommentId)
                                    {
                                       movie.maxCommentId = commentId;
                                    }
                                    
                                    movie.comments.push({id:comments[t].getAttribute("id"), text:comments[t].firstChild.nodeValue, userId:comments[t].getAttribute("userId"), author:comments[t].getAttribute("userName"), time:comments[t].getAttribute("when")});
								}
							}
						} catch (e) { alert(e.message); }
						break;
					case "Category":
						movieObject["CategoryId"] = nodes[i].getAttribute("id");
						movieObject["Category"] = nodes[i].firstChild.nodeValue;
						break;
                    case "Stored":
                        movieObject["Stored"] = nodes[i].firstChild.nodeValue;
                        break;
					case "Sharing":
						movieObject["allowedViewers"] = nodes[i].getAttribute("allowedViewers");
						movieObject["sharingType"] = nodes[i].getAttribute("type");
						var groups = nodes[i].getElementsByTagName("Group");
						movieObject["groups"] = new Array();
						for (var g=0;g<groups.length;g++) {
							movieObject["groups"].push(groups[g].firstChild.nodeValue);
						}
						break;
					default:
						try {
							movieObject[nodes[i].tagName] = nodes[i].firstChild.nodeValue;
						} catch (e) {
						}
						break;
				}
			}
		}
		$("__NumOfViews").innerHTML = movieObject["NumOfViews"]+" "+Common.GetViewsLabel(movieObject["NumOfViews"]);
		$("__NumOfOtherMovies").innerHTML = "("+movieObject["NumOfOtherMovies"]+")";
        $("__Title").innerHTML = movieObject["Title"];
        $("__Description").innerHTML = movieObject["Description"];
		$("__Category").innerHTML = movieObject["Category"];
		$("__Category").value = movieObject["CategoryId"];
		$("__Privacy").innerHTML = movieObject["Privacy"];
		$("__movieSharingTypeIcon").src = "/images/"+((movieObject["Privacy"] == "Public") ? "/icons/icon_public" : "privatelock")+".gif"
		$("__Taken").innerHTML = movieObject["Taken"];
		//$("__NumOfComments").innerHTML = movieObject["NumOfComments"]+" comments";
		//$("__NumOfCommentsTitle").innerHTML = "("+movieObject["NumOfComments"]+")";
		$("__Tags").innerHTML = (typeof(movieObject["Tags"]) == "undefined") ? "" : movieObject["Tags"];
		//movieObject["Rate"] = parseInt(movieObject["Rate"], 10);
		//movie.setRate(movieObject["Rate"]);
		movieObject["FlashPlayer"] = movieObject["FlashPlayer"].replace(/ /g, "").replace(/^.*file=([^\&]*).*$/, "$1");  
        this.movieLocation = movieObject["FlashPlayer"]; 
		sendToActionScript(movieObject["FlashPlayer"], this.isLive, "");
		//if (typeof(movieObject["CommentThumbnailUrl"]) != "undefined") movie.CommentThumbnailUrl = movieObject["CommentThumbnailUrl"];
		movie.drawComments();
        //debugger;
		
		// sharing
		if(document.getElementById("sharing_groups_list")) {
            
            this.sharingGroups = new Array();
			movie.clearSharing();
			var availableGroups = Common.GetGroups();
			var groupsCounter = 0;
			for (var i=0;i<availableGroups.length;i++) {
				if (parseInt(availableGroups[i].id, 10) <= 0) continue;
				groupsCounter += 1;
				var div = $("sharing_groups").appendChild(document.createElement("div"));
				div.className = "group";
				var input = div.appendChild(document.createElement(document.addEventListener ? "input" : "<input type='checkbox'>"));
				if (document.addEventListener) input.type = "checkbox";
				input.id = "g"+availableGroups[i].id;
				input.value = availableGroups[i].id;
				var label = div.appendChild(document.createElement("label"));
				label.htmlFor = "g"+availableGroups[i].id;
				label.innerHTML = availableGroups[i].name;
				label = null;
				input = null;
				div = null;
			}
			$("sharing_groups_header").style.display = (groupsCounter == 0) ? "none" : "";
			
			this.FillSharingGroups(movieObject["groups"]);
			this.FillSharingTitle(movieObject["groups"]);
			
//			if (movieObject["groups"].length > 0) {
//				var div = $("__SharingGroupsList").appendChild(document.createElement("div"));
//				div.className = "seperatorRC";
//				div = null;
//			}
			
			// TODO: fix reloader position in IE
		    if(movieObject["Stored"] == "true")
            {
                   $("yticon").style.visibility = "visible";
            }
            else
            {
                   $("yticon").style.visibility = "hidden";
            
            }
            flixee.userName = $("UN").innerHTML; 
	
		
        }
		
		$("movieDetailsContainer").style.visibility = "visible";
        
        //if the movie is live = the chat send button changes to live mode
        
        if(movie.isLive == true)
        {
             $("sendComment").innerHTML = "send live comment";
             $("sendComment").style.color  = "red";
             $("chat").style.color  = "red";
             
             if(movieObject["NumOfComments"] > 0)
             {
               if(movieObject["NumOfComments"] > 1) $("commentTitle").innerHTML = 'Live Chat <font size="2.5">('+movieObject["NumOfComments"]+" comments)</font>";
               else $("commentTitle").innerHTML = 'Live Chat <font size="2.5">('+movieObject["NumOfComments"]+" comment)</font>"; 
             }
             else
             {
               $("commentTitle").innerHTML = "Live Chat";
             
             }
             
             header.endMovieId = movie.currentMovieId;
        }
        else
        {
        
            $("sendComment").innerHTML = "send";
           	$("sendComment").style.color  = "#FFFFFF";
            $("chat").style.color  = "#FFFFFF";
            if(movieObject["NumOfComments"] > 0)
            {
               if(movieObject["NumOfComments"] > 1) $("commentTitle").innerHTML = 'Chat <font size="2.5">('+movieObject["NumOfComments"]+" comments)</font>";
               else $("commentTitle").innerHTML = 'Chat <font size="2.5">('+movieObject["NumOfComments"]+" comment)</font>"; 
            }
            else
            {
               $("commentTitle").innerHTML = "Chat";
             
            }
        
        }
        
        // debugger;
        //reset the chat script
        chat.reset(movie.currentMovieId,movie.maxCommentId)
        
	},
	FillSharingTitle: function(arr) {
		var titles = new Array("Private (Some groups)", "Private (Only me)", "Private (All my contacts)", "Public");
		var sharingTitleId = 0;
		for (var i=0;i<arr.length;i++) {
			sharingTitleId = (parseInt(arr[i], 10) < 0) ? parseInt(arr[i], 10) : 0;
		}
		//$("__SharingType").innerHTML = titles[Math.abs(sharingTitleId)];
		$("__Privacy").innerHTML = titles[Math.abs(sharingTitleId)];
		//$("__sharingGroupListContainer").style.display = (sharingTitleId < 0) ? "none" : "";
		//$("__sharingTypeIcon").src = "/images/"+((sharingTitleId == -3) ? "/icons/icon_public" : "privatelock")+".gif";
		$("__movieSharingTypeIcon").src = "/images/"+((sharingTitleId == -3) ? "/icons/icon_public" : "privatelock")+".gif";
	},
	FillSharingGroups: function(arr) {
//		Common.ClearContainer($("__SharingGroupsList"), "DIV");
		for (var i=0;i<arr.length;i++) {
			if (parseInt(arr[i], 10) < 0) {
				$("sharingGroup_"+arr[i].replace(/^-/, "")).checked = true;
			}
			//var div = $("__SharingGroupsList").appendChild(document.createElement("div"));
			//div.className = "seperatorRC";
			//var div = $("__SharingGroupsList").appendChild(document.createElement("div"));
			//div.innerHTML = Common.GetGroupById(arr[i]);
			//div = null;
			//this.sharingGroups.push(arr[i]);
		}
	},
	setRate: function(rate) {
//		var smilies = $("__Rate").childNodes;
//		var current = 0;
//		for (var i=0;i<smilies.length;i++) {
//			if (smilies[i].nodeName.toLowerCase() == "a") {
//				smilies[i].className = "smiley on";
//				current += 1;
//			}
//			if (current > rate) {
//				smilies[i].className = "smiley off";
//			}
//		}
	},
	//firstDuringComment:0,
	//firstAfterComment:0,
	//currentPageDuring:1,
	//currentPageAfter:1,
	//pagesDuring:1,
	//pagesAfter:1,
	//CommentThumbnailUrl: "", 
	clearSharing:function() {
		if ($("__SharingGroupsList") != null) Common.ClearContainer($("__SharingGroupsList"), "DIV");
		Common.ClearContainer($("sharing_groups"), "DIV");
	},
	addComment:function(id, userId, userName, when, comment, section)
    {
		movie.comments.splice(0, 0, {id:id, userId:userId, author:userName, time:when, text:comment});
		movie.clearCommentsOnScreen(section);
		movie.drawComments();
		//movie.updateComments($(section));
		
		var numberOfComments = movie.comments.length;
		
        if(movie.isLive == true)
        {
             if(numberOfComments > 1) $("commentTitle").innerHTML = 'Live Chat <font size="2.5">('+numberOfComments+" comments)</font>";
             else $("commentTitle").innerHTML = "Live Chat ("+numberOfComments+" comment)"; 
             
             //$("commentTitle").innerHTML = "Live Chat ("+numberOfComments+")";
        }    
        else
        {
            
             if(numberOfComments > 1) $("commentTitle").innerHTML = 'Chat <font size="2.5">('+numberOfComments+" comments)</font>";
             else $("commentTitle").innerHTML = 'Chat <font size="2.5">('+numberOfComments+" comment)</font>"; 
            //$("commentTitle").innerHTML = "Chat ("+numberOfComments+")";    
        
        }
 
        //$("__NumOfComments").innerHTML = numberOfComments+" comments";
		//$("__NumOfCommentsTitle").innerHTML = "("+numberOfComments+")";
        
        chat.reset(movie.currentMovieId,id)
        
	},
    addNewComment:function(comment)
    {
         //first check if the comment doesnt exist
         for (var i=0;i<movie.comments.length;i++)
         {
             if(movie.comments[i].id == comment.id)
             {
               return;
             }
         
         }
         
         movie.addComment(comment.id,-1,comment.userName,comment.when,comment.text,"during");
         
         //debugger;
         if(movie.chatOpen == false)
         {
                $("newComment").style.display = "";
         }
         else
         {
               // debugger;
         
         } 
    
    },
	drawComments:function() {
			var duringCommentContainer = $("duringComments");

			var table = duringCommentContainer.appendChild(document.createElement("table"));
			table.border = "0";
			table.cellPadding = "5";
			table.cellSpacing = "0";
			table.width = "255";
			table.style.tableLayout = "fixed";
			var tbody = table.appendChild(document.createElement("tbody"));
			
			for (var i=0;i<movie.comments.length;i++)
             {
				var tr = tbody.appendChild(document.createElement("tr"));
				var td = tr.appendChild(document.createElement("td"));
				td.colSpan = 2;
				td.innerHTML = "<font class='commentAuthor'>"+movie.comments[i].author+":</font> <font class='abstract'>"+movie.comments[i].text+"</font>";
				
				var tr = tbody.appendChild(document.createElement("tr"));
				var td = tr.appendChild(document.createElement("td"));
				td.width = '215';
				td.className = "postedTime";
				td.innerHTML = "posted "+movie.comments[i].time;

				if(document.getElementById("sharing_groups_list"))   
                {
					var td = tr.appendChild(document.createElement("td"));
					td.width = '40';
					td.innerHTML = "<a href='javascript:void(0);' class='removeComment' onclick='myMovie.RemoveComment("+movie.comments[i].id+", \"during\", "+i+");'><nobr>remove</nobr></a>";
				} else {
					td.colSpan = 2;
				}
			}
			if (movie.comments.length == 0) {
				var div = duringCommentContainer.appendChild(document.createElement("div"));
				//div.innerHTML = "There are no comments for this flix yet";
				div = null;
			}
			//movie.pagesDuring = Math.ceil(movie.commentsDuring.length/5);
		
		
		//movie.handlePaging((typeof(section) == "undefined") ? "during" : section);
	},
	clearCommentsOnScreen:function(section) {
		try {
			var comments = $(section+"Comments").childNodes;
			for (var i=comments.length-1;i>=0;i--) {
				if (comments[i].tagName == "DIV" || comments[i].tagName == "TABLE") $(section+"Comments").removeChild(comments[i]);
			}
		} catch (e) {
		}
	},
	clearComments:function() {
		movie.comments = new Array();
		//movie.commentsDuring = new Array();
		movie.clearCommentsOnScreen("during");
		//movie.clearCommentsOnScreen("after");
	},

	playIt: function(id) {
		$("movieDetailsContainer").style.visibility = "hidden";
		movie.clearComments();
		//movie.updateComments("during");
		var movieId = id;
		this.currentMovieId = id; 
        document.location.href = document.location.href.replace(/\#.*$/, "")+"#m"+movieId;
		flix.showReloader('Loading...','load');

		var updater = new Ajax("/movie/data/movieId/"+movieId , {method: 'get', onComplete:function(){
			defaultJS.hideReloader();
			movie.fillMovieData(this.transport.responseXML.documentElement);
		}}).request();
        
        
	},
	doflag: function() {
		flix.showReloader('Updating...','update');
		var updater = new Ajax("/movie/Flag/movieId/"+Common.GetMovieId() , {method: 'get', onComplete:function(){
			flix.hideReloader();
			var result = Common.ParseXMLResult(this.transport.responseXML.documentElement);
			if (result.errorCode == -1) {
				$("errors").innerHTML = result.reason;
				movie.errorLB.show();
			} else {
				movie.statusLB.hide();
			}
		}}).request();
	},	
	flag: function() {
				$("status").innerHTML = "Are you sure you want to flag this flix as inappropriate?";
				$("flagButtons").style.display = '';
				$("closeButton").style.display = 'none';
				movie.statusLB.show();
	},
	initialize: function(){
		//debugger;
        if ($("formValidationErrors")) movie.errorLB = new Lightbox($("formValidationErrors"), {opacity:0.5});
		if ($("formValidationStatus")) movie.statusLB = new Lightbox($("formValidationStatus"), {opacity:0.5});

		if (!Common.IsLoggedIn())
        {
          $("joinNow").style.display = "";
        }
        else
        {
            $("visitorName").value = $("UN").innerHTML; 
            $("visitorName").readOnly = true;
        }
		
		if($("fullScreenLB")) movie.fullScreenLB = new Lightbox($("fullScreenLB"),{opacity:0.9});
		
		movie.clearComments();
		//movie.updateComments("during");
		flix.showReloader('Loading...','load');
		if (typeof(document.slider) == "undefined")
        {
			var slider = new Slider($("relatedMovies"), $("container"), 80, 60, $("previous"), $("next")); slider.draw();
			document.slider = slider;
		}
		var movieId = Common.GetMovieId();
		var updater = new Ajax("/movie/data/movieId/"+movieId+"?r="+Math.random()*100000, {method: 'get', onComplete:function(){
			defaultJS.hideReloader();
			movie.fillMovieData(this.transport.responseXML.documentElement);
		}}).request();
		$("flashcontent").style.visibility = "visible";
		
		//initialize the light box - add friend
		if($("addFriend"))
			movie.addFriend=new Lightbox($("addFriend"),{opacity:0.4});	
            
        this.currentMovieId = movieId;
        
        //register to window.unload event for unregistering from the header callback
        header.endCallback = movie.OnLiveMoviesEnd;
        
    },
    OnLiveMoviesEnd: function()
    {
         $("sendComment").innerHTML = "send";
         $("sendComment").style.color  = "#FFFFFF";
         $("chat").style.color  = "#FFFFFF";
         
        var numberOfComments = movie.comments.length;
        
        if(numberOfComments > 0)
        {
            if(numberOfComments > 1) $("commentTitle").innerHTML = 'Chat <font size="2.5">('+numberOfComments+" comments)</font>";
            else $("commentTitle").innerHTML = 'Chat <font size="2.5">('+numberOfComments+" comment)</font>"; 
            //$("commentTitle").innerHTML = "Chat ("+numberOfComments+")";    
        }
        else
        {
            $("commentTitle").innerHTML = "Chat";
        }
         
         
    },
//	// comments
//	updateComments: function(o) {
//		try {
//			var el = $(o);

//			$("duringComments").style.display = (el.id == "during") ? "" : "none";
//			$("afterComments").style.display = (el.id == "after") ? "" : "none";

			// hide last showed panel
//			if(flix.showIndex!=null)
//			flix.hideIt(flix.showIndex);

//			if(el != $(movie.commentTabs) && el != null) {
//				$(movie.commentTabs).removeClass('current'); // color white of the tab
//			}

//			if(!el.hasClass('current')) { el.addClass('current'); }

//			movie.commentTabs = el.id;
//			movie.handlePaging(el.id);
//		} catch (e) {
//		}
//	},

	//hide the light box - add friend
	AddFriend: function(){
		flix.hideIt(flix.showIndex); 
		movie.addFriend.show();
	},
	
	HideFriend: function() {
			flix.hideReloader(); // hide reloader
			Lightbox.hide();
	}, 
	
	AddAnotherFriend: function() {
			flix.hideReloader(); // hide reloader
			Lightbox.hide();
	}, 
	
	UpdateFriend: function() {
			flix.hideReloader(); // hide reloader
			Lightbox.hide();
	}, 
	
	//turn on all functions with lopping time delay
	setTimer: function(fn,exp){
		clearTimeout(movie.movieTimer);
		movie.updateMainMovieData(exp);
	},

	postacomment: function() {
		if ($('visitorName').value == "") {
			flix.showIt('noNameBox');
			$("visitorName").focus();
		} else if ($('txtPostContent').value == "") {
			flix.showIt('noBodyBox');
			$("txtPostContent").focus();
		}
	
		if ($('txtPostContent').value == '' || $('visitorName').value == '' )
        {
		//	$('txtPostContent').focus();
			return;
		} // End of if
		
        flix.showReloader('Sending...','send'); // Violet
		var poster = new Ajax("/movie/PostComment?movieId="+this.currentMovieId+"&author="+$('visitorName').value+"&content="+$('txtPostContent').value, {method:'get', onComplete:function() {
			var status = eval(this.transport.responseXML.firstChild.getAttribute("success"));
			flix.hideReloader(); // hide reloader
			//flix.hideIt('commentPanel');
			var userId, userName, when;
			try {
				userName = this.transport.responseXML.firstChild.getAttribute("userName");
				when = this.transport.responseXML.firstChild.getAttribute("when");
				commentId = this.transport.responseXML.firstChild.getAttribute("id");
			} catch (e) {
				userName = "";
				when = "";
				commentId = 0;
			}
			//debugger;
            movie.addComment(commentId, -1, userName, when, $('txtPostContent').value,"during");
			$('txtPostContent').value = "";
		}}).request();
	},
	AddToFavorite: function(el) {
		if(flix.isLogin()) {
			flix.showReloader('Update...','update'); // Violet
			var poster = new Ajax("/movie/AddToFavorites/movieId/"+Common.GetMovieId(), {method:'get', onComplete: function() {
				flix.hideReloader(); // hide reloader
				flix.showIt("favPanel", this);
			}}).request();
		} else {
			flix.login(el);
		}
	},
	rateIt: function (num, el) {
		if(flix.isLogin()) {
			flix.hideIt(flix.showIndex);
			flix.showReloader('Update...','update'); // Violet
			var poster = new Ajax("/movie/rate?movieId="+Common.GetMovieId()+"&rate="+num, {method: 'get', onComplete: function() {
				var status = eval(this.transport.responseXML.firstChild.getAttribute("success"));
				var rate = this.transport.responseXML.firstChild.getAttribute("rate");
				//movie.setRate(rate);
				flix.hideReloader(); // hide reloader
			}}).request();
		} else {
			flix.login(el);
		}
	},

	//--------------------------------general AJAX content updates from SERVER to movie.php --------------------------------------------------//
	// movie.php page (AJAX content) - refresh the number of views and comments of main movie, every 1 minute
	// <params>
	// movieId
	// </params>
	updateMainMovieData: function(movieId) {

		flix.showReloader('Update...','update'); // Violet
		var updater = new Ajax('includes/movie/mainmoviedata.php?movieId='+movieId+'&mode=views&r=' + Math.floor(Math.random()*1000) , {method: 'get', update: $('mainMovieViewsNum'), onComplete:function(){
			//flix.hideReloader(); // hide reloader
		}}).request();

		var updater = new Ajax('includes/movie/mainmoviedata.php?movieId='+movieId+'&mode=comments&r=' + Math.floor(Math.random()*1000) , {method: 'get', update: $('mainMovieCommentsNum'), onComplete:function(){
			flix.hideReloader(); // hide reloader
		}}).request();

		//set off the function every 1 minute
		movie.movieTimer = setTimeout("movie.updateMainMovieData("+movieId+")", 60000);
	},


	// send email
	_mailRx:/^[\w-\.]+@([a-z0-9\-]+\.)+[a-z]{2,5}$/i,
	sendEmail: function() {

		// show reloader
		flix.showReloader('Sending...','send');

		if (!$('txtEmail').value) {
			$('txtEmail').focus();
			flix.hideReloader();
			return;
		} else if(!$('txtSubject').value) {
			$('txtSubject').focus();
			flix.hideReloader();
			return;
//		} else if ($('txtEmail').value && !this._mailRx.test($('txtEmail').value)) {
//			$('txtEmail').select();
//			flix.hideReloader();
//			return;
		}

		var poster = new Ajax("/movie/mail?address="+$('txtEmail').value+"&movieId="+Common.GetMovieId()+"&subject="+$('txtSubject').value, {method: 'get', onComplete: function() {
			flix.hideIt(flix.showIndex);
			flix.hideReloader(); // hide reloader
			try {
				var status = eval(this.transport.responseXML.firstChild.getAttribute("success"));
				if (status) {
					flix.showIt("emailConfirmPanel",this);
				} else {
					flix.showIt("emailErrorPanel",this);
				}
			} catch (e) {
				alert(e.description);
			}
		}}).request();;
	},

	sendMessage: function() {

		// show reloader
		flix.showReloader('Sending...','send');

		var errors=[];
		if(!$('txtSubjectMessage').value) errors.push('Please enter a Subject');

		if (errors.length) {
			flix.hideReloader();
			alert("* "+errors.join("\n* "));
		} else {
			var poster = new Ajax('generic/post.php?action=send&movie=' + flix.id + '&txtSubject=' + $('txtSubjectMessage').value + '&content=' + $('txtContentMessage').value, {method: 'get', onComplete: function() {
				
				flix.hideIt(flix.showIndex);
				flix.showIt('SendMessageConfirmPanel',this);
				flix.hideReloader(); // hide reloader
			}}).request();
		}
	},

	// reset form
	resetSendForm:function () {
		$$("#txtEmail,#txtSubject").setProperty("value","");
	},
	
	FillShareFields: function() {                
		
         if(movie.isLive == true) return;
        var movieId = this.movieLocation.replace(/\.flv$/, "");
		$("share_url").value = Common.GetDomain()+"watch/"+Common.GetMovieId();
		//$("share_embed").value = '<object width="352" height="317"><param name="FlashVars" value="id='+Common.GetMovieId()+'&movieUrl='+movieId+'" /><param name="movie" value="'+Common.GetDomain()+'FlixwagonEmbedPlayer.swf" /><embed src="'+Common.GetDomain()+'FlixwagonEmbedPlayer.swf" FlashVars="id='+Common.GetMovieId()+'&movieUrl='+movieId+'" width="352" height="317" type="application/x-shockwave-flash" /></object>';
        $("share_embed").value = '<object width="352" height="317"><param name="FlashVars" value="id='+Common.GetMovieId()+'&movieUrl='+movieId+'" /><param name="movie" value="http://mtv.flixwagon.com.s3.amazonaws.com/flvPlayer.swf" /><param name="allowFullScreen" value="true" /><embed src="http://mtv.flixwagon.com.s3.amazonaws.com/flvPlayer.swf" allowFullScreen="true" FlashVars="id='+Common.GetMovieId()+'&movieUrl='+movieId+'" width="352" height="317" type="application/x-shockwave-flash" /></object>';
	},
    
    FillTwitter: function() 
    {
             
       //if the user is not signed in - dont display the update my account checkbox
       if(flix.isLogin() == false) 
       {
         $("update").style.display = 'none';
         $("updateLabel").style.display = 'none';
       } // End of if
       else
       {
            //if the user is signed in , and has a twitter account at flixwagon ,fill in the 
            //username/password fields.
            if(document.getElementById("shareAccounts"))
            {
               var userName  =  $("twitterU").innerHTML;
               var password  =  $("twitterP").innerHTML;
               $("twitterUserName").value = userName;
               $("twitterPassword").value = password;
               $("update").style.display = 'none';
               $("updateLabel").style.display = 'none';
            
            }
       
       }

       //when the box opens , the default text should be { I watched the flix <Title> by <Broadcaster> }
       
//       var title =  $("__Title").innerHTML;
  //     var broadcaster;
       var text = "You have to see this! I'm watching a live video";

       
//       if (typeof(myMovie) != "undefined")
//       {
//       
//         broadcaster = "me";
//       
//       }
//       else
//       {
//          broadcaster = $("UserName").innerHTML;  
//       }
       
  
//       if(title.toLowerCase() == "untitled")
//       {
//         text =  "I watched a flix taken by " + broadcaster;  
//       }
//       else
//       {
//         text =  "I watched the flix "+ title + " taken by " + broadcaster;  
//       
//       }
//      
       
       
       movie.movieLink = " www.flixwagon.com/watch/"+Common.GetMovieId();
       $("twitterText").value = text;
       
       //update the left charqcters
       var lenLeft = $("twitterCharsLeft").attributes['originVal'].value - text.length - this.movieLink.length;
       $("twitterCharsLeft").innerHTML = lenLeft; 
           
    },
    
    SendTwitter: function()
    {
      
      //check if all must fields are filled
      if($("twitterText").value && $("twitterUserName").value && $("twitterPassword").value)
      {
        var updateAccount =  ($("update").checked) ? "true" : "false";
        
        var message =  $("twitterText").value + movie.movieLink;
        flix.showReloader('Updating...','update');
        var poster = new Ajax("/movie/TwitterUpdate?userName="+$("twitterUserName").value+"&password="+$("twitterPassword").value+"&message="+message+"&updateAccount="+updateAccount, {method:'get', onComplete:function() {
            var text = this.transport.responseText;
            if(text.search("Wrong") > 0)
            {
                $("errors").innerHTML = text;
                flix.hideReloader();
                movie.errorLB.show();
                flix.hideIt($("twitterPanel")); 
            }
            else // all is ok
            {
                flix.hideReloader();
                $("status").innerHTML = text;
				$("flagButtons").style.display = 'none';
				$("closeButton").style.display = '';
                
                movie.statusLB.show();
                document.location.href = "#top";
                flix.hideIt($("twitterPanel")); 
      
            }
        }}).request();
      
      }
      else   //some must field is missing
      {   
         $("errors").innerHTML = "please fill in all the required fields";
         movie.errorLB.show();
         //hide the twitter dialogue
        flix.hideIt($("twitterPanel")); 
         
         
      
      }
    
    },
    FillYoutube: function() 
    {
             
        //if the user is signed in , and has a twitter account at flixwagon ,fill in the 
        //username/password fields.
        if(document.getElementById("shareAccounts2"))
        {
           var userName  =  $("youtubeU").innerHTML;
           var password  =  $("youtubeP").innerHTML;
           $("youtubeUserName").value = userName;
           $("youtubePassword").value = password;
           $("updateYoutube").style.display = 'none';
           $("ytLabel").style.display = 'none';
        }
    },
    
    SendYoutube: function()
    {
      
      
      //check if all must fields are filled
      if($("youtubeUserName").value && $("youtubePassword").value)
      {
        //disable the upload btn
        //$("ytbtn").disabled= true;
        
        var updateAccount =  ($("updateYoutube").checked) ? "true" : "false";
        
        flix.showReloader('Uploading flix...','update');
        var movieId = this.currentMovieId;        
        var poster = new Ajax("/frontend_dev.php/movie/YoutubeUpdate?userName="+$("youtubeUserName").value+"&password="+$("youtubePassword").value+"&movieId="+movieId+"&updateAccount="+updateAccount, {method:'get', onComplete:function() {
            var text = this.transport.responseText;
            if(text.substring(0,1) == "0")  
            {
                $("errors").innerHTML = "Uploading the flix to YouTube failed";
                flix.hideReloader();
                movie.errorLB.show();
                flix.hideIt($("youtubePanel")); 
            }
            else // all is ok
            {
                flix.hideReloader();
                $("status").innerHTML = "upload complete";
				$("flagButtons").style.display = 'none';
				$("closeButton").style.display = '';
                
                movie.statusLB.show();
                document.location.href = "#top";
                flix.hideIt($("youtubePanel")); 
            }
        }}).request();
      
      }
      else   //some must field is missing
      {   
         $("errors").innerHTML = "please fill in all the required fields";
         movie.errorLB.show();
         //hide the twitter dialogue
        flix.hideIt($("youtubePanel")); 
      
      }
    
    }
    
    
    
};

// player related functions
var jsReady = false;
function isReady() {
    return jsReady;
}
function pageInit() {
    jsReady = true;
}
function thisMovie(movieName) {
 if (navigator.appName.indexOf("Microsoft") != -1) {
     return window[movieName];
 } else {
     return document[movieName];
 }
}
function sendToActionScript(source, isLive, preview) {
    //debugger;
    var sourceMovie = source;
    var isLive = isLive;
    var bandwidthurl = "";
    var previewmovieurl = preview;
    var skinid = 1;
    var autoplay=true;
    var inportal=true;
    var urltosend = "///";
    try {
        //debugger;
        thisMovie("flvPlayer").sendToActionScript(sourceMovie, isLive, bandwidthurl, previewmovieurl, skinid, autoplay, urltosend, inportal);
    } catch (e) {
        window.setTimeout(function() {
            sendToActionScript(source, isLive, preview);
        }, 1000);
    }
    //alert('after');
}
function sendToJavaScript(value) {
    alert(value);
}

function setregscreen() {
//	document.onkeydown = null;
	thisMovie("flvPlayer").width = 352;
	thisMovie("flvPlayer").height = 317;
	$("flashcontent").style.top = "10px";
	$("flashcontent").style.left = "10px";
	movie.fullScreenLB.hide();
	
	thisMovie("flyPlayer").changeToReg();
}
function setfullscreen() {
	movie.fullScreenLB.show();
	thisMovie("flvPlayer").width = 704;
	thisMovie("flvPlayer").height = 634;
	if (document.documentElement) {
		var scrollTop = parseInt(document.documentElement.scrollTop, 10);
		var clientHeight = parseInt(document.documentElement.clientHeight, 10);
		var clientWidth = parseInt(document.documentElement.clientWidth, 10);
		var orgPosition = Common.GetPosition($("flashcontentContainer"));

		var top = (clientHeight-634)/2+scrollTop-orgPosition.y;
		var left = Math.floor((clientWidth-704)/2)-orgPosition.x;
		$("flashcontent").style.top = top+"px";
		$("flashcontent").style.left = left+"px";
	} else {
	}
	
/*	document.onkeydown = function(e) {
		e = e || event;
		if (e.keyCode == 27) setregscreen();
	}
*/
}

function LimitText(taObj, maxChars)
 {

    var totalChars = maxChars;

    var charsLeft = totalChars-taObj.value.length;


    if (taObj.value.length >= (totalChars))
    {
            taObj.value = taObj.value.substring(0, totalChars-1);
    }

}

function handleChat(movieObj) {
    
    var otherId = (movieObj.id == "chat") ? "details" : "chat";
    if (document.getElementById(movieObj.id+"Arrow").src.indexOf("Bottom") != -1) 
    {
        if (movieObj.id == "chat") 
        {
            document.getElementById(movieObj.id+"Arrow").src = document.getElementById(movieObj.id+"Arrow").src.replace("Bottom", "Right");
            document.getElementById(movieObj.id+"Box").style.display = "none";

            document.getElementById(otherId+"Arrow").src = document.getElementById(otherId+"Arrow").src.replace("Right", "Bottom");
            document.getElementById(otherId+"Box").style.display = "";            
           
        }        
    } 
    else
    {
        document.getElementById(movieObj.id+"Arrow").src = document.getElementById(movieObj.id+"Arrow").src.replace("Right", "Bottom");
        document.getElementById(movieObj.id+"Box").style.display = "";

        document.getElementById(otherId+"Arrow").src = document.getElementById(otherId+"Arrow").src.replace("Bottom", "Right");
        document.getElementById(otherId+"Box").style.display = "none";
        //movie.chatOpen = true;
    }
    
    if (movieObj.id == "chat")
    {
        document.getElementById("newComment").style.display = "none";
    }
    
    movie.chatOpen = !(movie.chatOpen);
    
}

function handleChatCursor(movieObj, type) {
	if (type == 'over') {
		if ((movieObj.id == "chat") || (movieObj.id == "details" && document.getElementById("detailsBox").style.display == "none")) {
			movieObj.style.cursor = "pointer";
		}
	} else {
		movieObj.style.cursor = "default";
	}	
}







