﻿var http;
var jsonVideoPreviews;
var flagAsInappropriate;
var favorite;

//load yedda and gigya in the end
window.onload = function() {

	//load taboola
	TRC.drawRBox();

	//load yedda
	if (moreFromThisCreator.categoryID == 8) {
		$('yedda-header').style.display = 'none';
		$('yedda-container').removeClass('inner-yedda');
		$('yedda-container').set('html', '<iframe id="gadget" scrolling="no" frameborder="no" width="300" height="250" src="http://www.gmodules.com/ig/ifr?up_ad=0&url=http://gadgets.justanswer.com/ja/gahealth/live/300x250-ad.xml?nocache=0&&r=5minlive"></iframe>');
	}
	else
		$('yedda-container').set('html', '<iframe src="Yedda.aspx?videoID=' + videoInfo.videoID + '" scrolling="no" frameborder="0" class="yedda-container"></iframe>');

	//load gigya
	var pconf = {
		defaultContent: 'txtEmbed',
		UIConfig: '<config><display showEmail="false" useTransitions="true" showBookmark="true" codeBoxHeight="auto" showCodeBox="true" showCloseButton="false" postToSidebarChecked="false" networksWithCodeBox="" networksToShow="facebook, orkut, bebo, blogger, friendster, myspace, tagged, hi5, piczo, freewebs, livejournal, wordpress, blackplanet, livespaces, myyearbook, vox, typepad, xanga, multiply, igoogle, netvibes, pageflakes, migente, yahoo, ameba, livedoor, eons, *"></display><body><background frame-color="#BFBFBF" background-color="#FFFFFF" gradient-color-begin="#ffffff" gradient-color-end="#F4F4F4" corner-roundness="4;4;4;4"></background><controls color="#202020" corner-roundness="4;4;4;4" gradient-color-begin="#EAEAEA" gradient-color-end="#F4F4F4" bold="false"><snbuttons type="textUnder" frame-color="#D5D5D5" over-frame-color="#60BFFF" color="#808080" gradient-color-begin="#FFFFFF" gradient-color-end="d4d6d7" size="10" bold="false" down-frame-color="#60BFFF" down-gradient-color-begin="#6DDADA" over-gradient-color-end="#6DDADA" down-gradient-color-end="#F4F4F4" over-color="#52A4DA" down-color="#52A4DA" over-bold="false"><more frame-color="#A4DBFF" over-frame-color="#A4DBFF" gradient-color-begin="#F4F4F4" gradient-color-end="#BBE4FF" over-gradient-color-begin="#A4DBFF" over-gradient-color-end="#F4F4F4"></more><previous frame-color="#BBE4FF" over-frame-color="#A4DBFF" gradient-color-begin="#FFFFFF" gradient-color-end="#A4DBFF" over-gradient-color-begin="#A4DBFF" over-gradient-color-end="#F4F4F4"></previous></snbuttons><textboxes frame-color="#CACACA" color="#757575" gradient-color-begin="#ffffff" bold="false"><codeboxes color="#757575" frame-color="#DFDFDF" background-color="#FFFFFF" gradient-color-begin="#ffffff" gradient-color-end="#FFFFFF" size="10"></codeboxes><inputs frame-color="#CACACA" color="#757575" gradient-color-begin="#F4F4F4" gradient-color-end="#ffffff"></inputs><dropdowns list-item-over-color="#52A4DA" frame-color="#CACACA"></dropdowns></textboxes><buttons frame-color="#CACACA" gradient-color-begin="#F4F4F4" gradient-color-end="#CACACA" color="#000000" bold="false" over-frame-color="#60BFFF" over-gradient-color-begin="#BBE4FF" down-gradient-color-begin="#BBE4FF" over-gradient-color-end="#FFFFFF" down-gradient-color-end="#ffffff"><post-buttons frame-color="#CACACA" gradient-color-end="#CACACA"></post-buttons></buttons><listboxes frame-color="#CACACA" corner-roundness="4;4;4;4" gradient-color-begin="#F4F4F4" gradient-color-end="#FFFFFF"></listboxes><checkboxes checkmark-color="#00B600" frame-color="#D5D5D5" corner-roundness="3;3;3;3" gradient-color-begin="#F4F4F4" gradient-color-end="#FFFFFF"></checkboxes><servicemarker gradient-color-begin="#ffffff" gradient-color-end="#D5D5D5"></servicemarker><tooltips color="#6D5128" gradient-color-begin="#FFFFFF" gradient-color-end="#FFE4BB" size="10" frame-color="#FFDBA4"></tooltips></controls><texts color="#202020"><headers color="#202020"></headers><messages color="#202020"></messages><links color="#52A4DA" underline="false" over-color="#353535" down-color="#353535" down-bold="false"></links></texts></body></config>'
	};
	Wildfire.initPost('12451', 'divWildfirePost', 120, 370, pconf);
}

function move5minCompanion() {
	var fiveMinComapnion = $('fiveMinAdaptvCompanionDiv');
	fiveMinComapnion.inject($('wrapperRight'), 'top');
	fiveMinComapnion.style.display = 'block';
}

function FiveMin_canRenderAd() {
	return !!$('wrapperRight');
}

function FiveMin_onBeforeAdRender() 
{
	move5minCompanion();
}

function selectTab(img_relatedOn, img_relatedOff, img_creatorOn, img_creatorOff, showRelated, divRelated, divCreator)
{
    if(showRelated)
    {
        $(img_relatedOn).className = 'invisible noBorder';
        $(img_relatedOff).className = 'visible noBorder';

        $(img_creatorOn).className = 'visible noBorder';
        $(img_creatorOff).className = 'invisible noBorder';
        
        $(divRelated).style.cursor = 'pointer';
        $(divCreator).style.cursor = 'default';        
    }
    else
    {
        $(img_relatedOn).className = 'visible noBorder';
        $(img_relatedOff).className = 'invisible noBorder';

        $(img_creatorOn).className = 'invisible noBorder';
        $(img_creatorOff).className = 'visible noBorder';

        $(divRelated).style.cursor = 'default';
        $(divCreator).style.cursor = 'pointer';
    }        
}

function initPlayerForAdapTV(divName, paramMovieUrl, width, height , objectID)
{
    //Mockup for google test
    if (document.location.href.toLowerCase().indexOf('watchgoogle') >= 0)
    {
        paramMovieUrl += "&sid=142";
    }
    var hasReqestedVersion = DetectFlashVer('9','0','48'); 

    var theDiv = $(divName);
    
    var strPlayer = "";
    
    if(hasReqestedVersion)
    {
        strPlayer = "<div id='adaptvDiv'>";
    }
    
    strPlayer = strPlayer + "<object id='" + objectID + "' width='" + width +"' height='" + height +"' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'>" +
        "<param name='allowfullscreen' value='true'>" + 
        "<param name='allowScriptAccess' value='always'>" +
        "<param name='movie' value='" + paramMovieUrl +"'>" +
        "<param name='wmode' value='" + (hasReqestedVersion ? 'opaque' : 'window') +"'>" + 
        "<embed src='" + paramMovieUrl + "' type='application/x-shockwave-flash' width='" + width + "' height='" + height +"' allowfullscreen='true' " +
        "allowScriptAccess='always' wmode='" + (hasReqestedVersion ? 'opaque' : 'window') + "'>";
    
    if(hasReqestedVersion)
    {
        strPlayer = strPlayer + "</div>";
    }
    
    theDiv.innerHTML = strPlayer;
}

function initMoreFrom(studioID,videoID,categoryID) {
    moreFromThisCreator = new MoreFromThisCreator(studioID,videoID,categoryID);
    moreFromThisCreator.getMoreFromVideos(studioID, 'studio', 1, videoID);
}

var MoreFromThisCreator = new Class({

	initialize: function(studioID, videoID, categoryID) {
		this.studioID = studioID;
		this.videoID = videoID;
		this.categoryID = categoryID;
		this.index = null;
		this.http = null;
	},
	changeTab: function(index) {
		var tabs = $("divMoreFrom_Tabs").getElements(".tab");
		tabs.each(function(tab, i) {
			if ((i + 1) == index) {
				tab.style.cursor = 'default';
				tab.getElement(".left").removeClass("leftSideOff").addClass("leftSideOn");
				tab.getElement(".middle").removeClass("unSelectedTab").addClass("selectedTab");
				tab.getElement(".right").removeClass("rightSideOff").addClass("rightSideOn");
				$('gallery_container' + (i + 1)).removeClass("invisible").addClass("visible");

			}
			else {
				tab.style.cursor = 'pointer';
				tab.getElement(".left").removeClass("leftSideOn").addClass("leftSideOff");
				tab.getElement(".middle").removeClass("selectedTab").addClass("unSelectedTab");
				tab.getElement(".right").removeClass("rightSideOn").addClass("rightSideOff");
				$('gallery_container' + (i + 1)).removeClass("visible").addClass("invisible");
			}
		});
	},
	getMoreFromVideos: function(entityID, type, index, currentVideoID) {
		this.index = index;
		if (!$('thumb_container' + this.index).retrieve("images:loaded")) {
			$('thumb_container' + this.index).store("images:loaded", true);
			this.changeTab(this.index);
			this.http = new Request({

				method: 'post',
				url: 'Handlers/VideoHandler.ashx',
				data: 'method=CreateJsonPreviewVideo&entityID=' + entityID + '&type=' + type + '&currentVideoID=' + currentVideoID,
				onComplete: this.getMoreFromVideosComplete.bind(this),
				onFailure: this.getMoreFromVideosFailed.bind(this)

			}).send();
		}
		else
			this.changeTab(this.index);

	},
	getMoreFromVideosComplete: function() {
		var reply = JSON.decode(this.http.response.text);
		//case videos exist
		if (reply.success) {
			jsonVideoPreviews = JSON.decode(reply.message);
			if (jsonVideoPreviews) {
				for (var i = 0; i < jsonVideoPreviews.length; i++) {
					$('thumbs' + this.index).innerHTML += this.createThumbnailElements(jsonVideoPreviews[i]);
				}
			}
			if (!$('thumb_container' + this.index).retrieve("no:images"))
				initSlider('gallery_container' + this.index, true);
		}
		else {
			$('thumb_container' + this.index).store("no:images", true);
			//case studio tab is missing videos
			if (reply.message == "studio") {
				$('thumb_container' + this.index).innerHTML = "Currently this creator has 1 video on 5min.com";
				//case user has only one video move to category tab.
				this.getMoreFromVideos(this.categoryID, 'category', 2, this.videoID);
			}
			else {
				$('thumb_container' + this.index).innerHTML = "Videos are currently unavailable";
			}
		}

	},

	createThumbnailElements: function(jsonVideoPreview) {
		var thumbContent = '<div class="thumbnail">' + '<a class="anchor-img" href="' + jsonVideoPreview.WatchPageUrl + '">' +
                            '<img width="124" height="92" hiddensrc="' + jsonVideoPreview.PreviewImageURL + '" title="' + jsonVideoPreview.CompleteTitle + '" alt="' + jsonVideoPreview.CompleteTitle + '" width="124" height="92"></img></a>' +
                            '<a class="title" href="' + jsonVideoPreview.WatchPageUrl + '">' + jsonVideoPreview.Title + '</a>' +
                            '</div>';
		return thumbContent;
	},

	getMoreFromVideosFailed: function() {
		$('thumb_container' + this.index).innerHTML = "Error Creating Images";
	}
});

function initVideoInfo(studioID,currentUserRate, videoId) {
    
    rating = new Rating(currentUserRate,videoId);
    rating.paintStar(currentUserRate,true);
    videoInfo = new VideoInfo(studioID,videoId);
    flagAsInappropriate = new FlagAsInappropriate(videoId);
    favorite = new Favorite();
    sendToFriend = new SendToFriend(videoId);    
}

var VideoInfo = new Class({

	initialize: function(studioID, videoID) {
		this.studioID = studioID;
		this.videoID = videoID;
	},
	changeSubscription: function() {
		if ($('divSubscribe').get('class') == 'subscribeButton') {
			this.subscribe(this.studioID, 'Subscribe');
		}
		else if ($('divSubscribe').get('class') == 'unSubscribeButton') {
			this.subscribe(this.studioID, 'unSubscribe');
		}
	},
	subscribe: function(studioID, action) {
		http = new Request({

			method: 'post',

			url: 'Handlers/MemberHandler.ashx',

			data: 'method=Subscribe&studioID=' + studioID + '&action=' + action,

			onComplete: this.subscribedComplete.bind(this, action)

		}).send();
	},

	subscribedComplete: function(action) {
		var reply = http.response.text;
		if (reply == "OK") {
			if (action == 'Subscribe')
				$('divSubscribe').className = 'unSubscribeButton';
			else
				$('divSubscribe').className = 'subscribeButton';
		}
		else {
			alert("Error contacting server");
		}
	},
	//change video info expansion format
	changeStatus: function() {
		if ($('divExpand').className == "invisible") {
			$('divExpand').className = "visible";
			$('divCollapse').className = "invisible";
			$('lnkSlideMore').innerHTML = "Less";
		}
		else {
			$('divExpand').className = "invisible";
			$('divCollapse').className = "visible";
			$('lnkSlideMore').innerHTML = "More";
		}
	},
	
	changeUserAction: function(value, isLoggedIn) 
	{
		var videoID = this.videoID;
		var userActions = $("divRatingUserActions").getElements(".userAction");
		
		var moreFromInnerContainer = $('divMoreFromThisCreator_InnerContainer');

		//moreFromInnerContainer lines remarked by Nir due to relocating moreFrom and 
		//videoInfo controls (valid only when videoInfo is on top of moreFrom)
		userActions.each(function(userAction, i)
		{
			if ((i + 1) == value) 
			{
				if (userAction.hasClass('visible')) 
				{
					userAction.removeClass('visible').addClass('invisible');
//					if(value != 2)
//						moreFromInnerContainer.removeClass('container_z_index');
				}
				else 
				{
					if (isLoggedIn != undefined)
						favorite.favoriteAction(isLoggedIn, videoID);
						
					userAction.removeClass('invisible').addClass('visible');
//					if (value != 2)
//						moreFromInnerContainer.addClass('container_z_index');
				}
			}
			else {
				userAction.removeClass('visible').addClass('invisible');
				
//				if(value == 'x' && (moreFromInnerContainer.hasClass('container_z_index')))
//					moreFromInnerContainer.removeClass('container_z_index');
			}

		});
	}


});

var Rating = new Class({

    initialize: function(currentUserRate, videoId) {
        var classRef = this;
        this.http = null;
        this.videoId = videoId;
        this.currentUserRate = currentUserRate
        this.hasRated = (currentUserRate > 0) ? true : false;

    },
    paintStar: function(value, isInit) {

        if (isInit || !this.hasRated) {
            for (var i = 1; i <= 5; i++) {
                if (i <= value) {
                    $('rating' + i).className = 'ratingStar' + i + 'On';
                }
                else {
                    $('rating' + i).className = 'ratingStar' + i + 'Off';
                }

            }
            if (isInit && value != 0)
                $('ratingText').innerHTML = 'You Rated: ' + value;
        }
    },
    chooseStar: function(value) {
        if (!this.hasRated) {
        $('ratingText').innerHTML = 'Sending your Vote...';
            this.http = new Request({
                method: 'post',
                url: 'Handlers/xmlRating.aspx',
                data: 'function=UpdateRating&videoID=' + this.videoId + '&value=' + value,
                onSuccess: this.updateRatingSucceeded.bind(this, value),
                onFailure: this.updateRatingFailed.bind(this)
            }).send();
        }
    },
    updateRatingSucceeded: function(value) {

        this.hasRated = true;
        this.paintStar(value, true);
    },
    updateRatingFailed: function() {
        $('ratingText').innerHTML = 'Rating Failed';
    }
});

////----------------------
// FLAG AS INAPPROPRIATE
//----------------------
var FlagAsInappropriate = new Class(
{
    initialize: function(videoID) {
        //Store references to client controls
        var classRef = this;
        this.ddl = $('ddlReasons');
        this.flagSendButton = $('img_send_flag');
        this.spinner = $('img_spinner_flag');
        this.msg = $('tdMsg_flag');
        this.videoID = videoID;
        this.inProcess = false;
        this.http = null;

        //Define "click" event on send
        this.flagSendButton.addEvent('click',
        function(e) {
            e = new Event(e);
            classRef.send();
            e.stop();
        });
    },

    send: function() {
    this.msg.className = "text_3 text_red tdMsg_user_action";

        if (this.inProcess) {
            this.msg.innerHTML = 'Operation still in process';
            return;
        }

        if (this.ddl.value == "-1") {
            this.msg.innerHTML = 'Please Choose a Reason.';
            return;
        }

        this.inProcess = true;

        this.spinner.style.display = "";
        this.msg.className = "text_3 text_black tdMsg_user_action";
        this.msg.innerHTML = 'Sending...';

        this.http = new Request(
        {
            method: 'post',

            url: 'Handlers/UserActionsHandler.ashx',

            data: 'Action=FlagAsInappropriate&EntityType=Video&EntityID=' + this.videoID + '&Reason=' + this.ddl.value,

            onSuccess: this.sendSucceeded.bind(this),

            onFailure: this.sendFailed.bind(this)

        }).send();
    },

    sendSucceeded: function() {
        this.spinner.style.display = "none";
        var reply = this.http.response.text;
        if (reply == "OK") {
            this.ddl.value = "-1";
            this.msg.className = "text_3 text_blue tdMsg_user_action";
            this.msg.innerHTML = 'Video flagged successfully.';
            this.inProcess = false;
        }
        else {
            this.msg.className = "text_3 text_red tdMsg_user_action";
            this.inProcess = false;            
        }
    },

    sendFailed: function() {
    this.msg.className = "text_3 text_red tdMsg_user_action";
        this.inProcess = false;
        this.spinner.style.display = "none";
        this.msg.innerHTML = 'Video was not flagged, Please try again later';
    }
});

//---------------
// Favorite
//---------------
var Favorite = new Class(
{
    initialize: function() {
        //Store references to client controls
        this.divFavorite = $('divFavorite');
        this.divUnFavorite = $('divUnFavorite');
        this.divAuthentication = $('divAuthentication');
    },

    showMsg: function(msg) {
        switch (msg) {
            case 'Authentication':
                this.divFavorite.setStyle('display', 'none');
                this.divUnFavorite.setStyle('display', 'none');
                this.divAuthentication.setStyle('display', 'block');
                break
            case 'Favorite':
                this.divFavorite.setStyle('display', 'none');
                this.divUnFavorite.setStyle('display', 'block');
                this.divAuthentication.setStyle('display', 'none');
                break
            case 'UnFavorite':
                this.divFavorite.setStyle('display', 'block');
                this.divUnFavorite.setStyle('display', 'none');
                this.divAuthentication.setStyle('display', 'none');
                break
        }
    },
    favoriteAction: function(isLoggedIn,videoID){
        
        if(isLoggedIn == "False")
        {
            favorite.showMsg('Authentication');            
        }
        else
        {               
            //write to DB favorite/unfavorite
            this.http = new Request({
                method: 'post',            	    	                                
                url: 'Handlers/UserActionsHandler.ashx',
                data: 'Action=Favorite&EntityType=Video&EntityID=' + videoID,        	    
                onSuccess: this.favoriteSucceeded.bind(this),        	    
                onFailure: this.favoriteFailed.bind(this)        	    
            }).send();            
        }
    },
    
    favoriteSucceeded: function() 
    {
        var reply = this.http.response.text;
        if (reply == "OK")
        {
        	var favoriteElement = $('userActionFavoriteImage');
            
            if(favoriteElement.innerHTML == "Favorite")
            {
                favoriteElement.innerHTML = "Unfavorite";    
                
                favorite.showMsg('UnFavorite');                
            }
            else
            {
                favoriteElement.innerHTML = "Favorite";
                
                favorite.showMsg('Favorite');                
            }            
        }
    },

    favoriteFailed: function() 
    {        
    }
});

//---------------
// SEND TO FRIEND
//---------------
var SendToFriend = new Class(
{
    initialize: function(videoID) {
        //Store references to client controls
        this.txtFriendsEmails = $('txtFriendsEmails');
        this.txtYourName = $('txtYourName');
        this.txtYourEmail = $('txtYourEmail');
        this.txtMessage = $('txtMessage_sendToFriend');
        this.sendButton = $('img_sendToFriend');
        this.spinner = $('img_spinner_sendToFriend');
        this.sendMsg = $('tdMsg_sendToFriend');
        this.videoID = videoID;
        this.inProcess = false;
        this.http = null;

        //Define "click" event on send
        this.sendButton.addEvent('click',
        function(e) {
            e = new Event(e);
            sendToFriend.send();
            e.stop();
        });
    },

    send: function() {
    this.sendMsg.className = "tdMsg_user_action text_3 text_red";

        //Avoid sending same video twice
        if (this.inProcess) {
            this.sendMsg.innerHTML = 'Operation still in process';
            return;
        }

        //Must enter at least one email.
        if (this.txtFriendsEmails.value == "") {
            this.sendMsg.innerHTML = 'Please Enter Email Addresses.';
            return;
        }

        if (this.txtYourName.value == "") {
            this.sendMsg.innerHTML = 'Please Enter Your Name.';
            return;
        }

        if (this.txtYourEmail.value == "") {
            this.sendMsg.innerHTML = 'Please Enter Your Email.';
            return;
        }

        this.inProcess = true;

        this.spinner.style.display = "";
        this.sendMsg.className = "tdMsg_user_action text_3 text_black";
        this.sendMsg.innerHTML = 'Sending...';

        this.http = new Request({

            method: 'post',

            url: 'Handlers/UserActionsHandler.ashx',

            data: 'Action=SendToFriend&EntityType=Video&EntityID=' + this.videoID + '&FriendsEmails=' + this.txtFriendsEmails.value + '&YourName=' + this.txtYourName.value + '&YourEmail=' + this.txtYourEmail.value + '&Message=' + this.txtMessage.value,

            onSuccess: this.sendSucceeded.bind(this),

            onFailure: this.sendFailed.bind(this)

        }).send();
    },

    sendSucceeded: function() {
        this.spinner.style.display = "none";
        var reply = this.http.response.text;
        if (reply == "OK") {
            this.sendMsg.className = "tdMsg_user_action text_3 text_blue";
            this.sendMsg.innerHTML = 'Video sent successfully.';
            this.inProcess = false;
            this.txtMessage.value = "";
            this.txtFriendsEmails.value = ""

        }
        else {
            this.sendMsg.className = "tdMsg_user_action text_3 text_red";
            this.inProcess = false;
            this.sendMsg.innerHTML = 'Video not sent. Please verify email address is correct.';
        }
    },

    sendFailed: function() {
        this.sendMsg.className = "tdMsg_user_action text_3 text_red";
        this.inProcess = false;
        this.spinner.style.display = "none";
        this.sendMsg.innerHTML = 'Video not sent. Please verify email address is correct.';
    }
});
