﻿var player;
var currentSelectedVideoID = 0;
var controller = new MTVNPlayerController('player1','onPlayerLoaded');
var URL_WORD_FILTER     = "/dynamo/wordfilter/index.jhtml?name=";
var ERROR_FIRST_NAME_INVALID = "Please enter a valid first name\n";
var ERROR_FRIEND_NAME_INVALID = "Please enter a valid friend's name\n";
var errorMsg ="";
var formSubmitting = false;
var goodWordsCounter =0;
var isFirstTime = true;

function onPlayerLoaded(controller){
   player = controller.player;
   player.addEventListener('READY','onReady');
   player.addEventListener('METADATA','onMetaData');
   player.addEventListener('STATE_CHANGE','onStateChange');
   player.addEventListener('PLAYHEAD_UPDATE','onPlayheadUpdate');
   player.addEventListener('NO_AD','onNoAd');
   player.addEventListener('AD_PACKAGE_LOADED','onAdPackageLoaded');
   player.addEventListener('MEDIA_ENDED','onMediaEnded');
   player.addEventListener('PLAYLIST_COMPLETE','onPlaylistComplete');
   player.addEventListener('PLAYLIST_ERROR','onPlaylistError');   
   //alert("LOADED");   

}

function thisMovie(movieName) {
 if (navigator.appName.indexOf("Microsoft") != -1) {
	 return window[movieName];
 } else {
	 return document[movieName];
 }
}

function onReady() {		 
	if(isFirstTime){
	    isFirstTime = false;
   	    //thisMovie("playlistFlash").playerReady("true");
    }
    updatePlaylist(player.getPlaylist().index);

	//var api = $("div.scrollable:first").scrollable(); 
	//alert("onReady playing index: " + player.getPlaylist().index);
	//alert("onReady playing length: " + player.getPlaylist().length);
	//alert("onReady playing items: " + player.getPlaylist().items[0]);
	
	//focusCurrentPlayingVideo(player.getPlaylist().index);
	//loadRC();
	//loadRateThis();	
}  

function updatePlaylist(value) {
    if(thisMovie("playlistFlash")){
        thisMovie("playlistFlash").updatePlaylist(value);
    }
};

function onMetaData( metadata ){
   //alert("Now watching: " + metadata.title + ":" + player.getTempPlaylist());
   //alert("player.metadata.isAd" + player.getMetadata().isAd);
   //focusCurrentPlayingVideo(player.getPlaylist().index);
	//var output = metadata.title + "</br>" + metadata.description + "</br>" + metadata.duration + "</br>" + metadata.url + "</br>id: " + getCMSIDfromGUID(player.getMetadata().guid);
	//document.getElementById("fpVideoInfo").innerHTML = output;
}

function onStateChange(playState) {
	//alert("playstate change");
}

function onPlayheadUpdate(info) {
	//alert("playhead update");
}

function onNoAd( info ) {
	//alert("no ad");
   // info.metadata
   // info.adUrl
   // info.counters
} 

function onAdPackageLoaded(info) {
	//alert("onAdPackageLoaded");
}

function onMediaEnded(info) {
	//alert("onMediaEnded");
}

function onPlaylistComplete(info) {
	//alert("onPlaylistComplete");
	thisMovie("playlistFlash").playNextEpisode("true");
	player.playIndex(0)
}

function onPlaylistError(info) {
	//alert("onPlaylistError");
}	

function pauseVideo() {
	player.pause();
}	

function nextVideo() {
	if (!player.getMetadata().isAd) {	
		player.next();
	}
}

function prevVideo() {
	if (!player.getMetadata().isAd) {
		player.previous();
	}
}

function getCMSIDfromGUID(guid) {
	var a=guid.split(":");
	return(a[4]);
}

//playlist
function focusCurrentPlayingVideo(cmsid) {
	//unselect current video	
	if (index >= 0) {
		document.getElementById(currentSelectedVideoID).className = 'videoNotSelected';		
		//select video playing
		currentSelectedVideoID = getCMSIDfromGUID(player.getMetadata().guid);
		document.getElementById(currentSelectedVideoID).className = 'videoSelected';		
	}	
}

function playVideo(index) {
	//alert("I should be paying index "+ index)
	if (!player.getMetadata().isAd) {
		player.playIndex(index, 0);
	}
}	

//coad
function mtvnSetCoad(adObject){ 
	var src = adObject.url; 
	var w = adObject.width; 
	var h = adObject.height;
	var clickTag = adObject.clickUrl; 
	var output = "<a href='" + clickTag + "'>" + "<img border='0' width='" + w + "' height='" + h + "' src='" + src + "' /></a>";
	document.getElementById("fpCoadContainer").innerHTML = output;	
} 



function checkBadWord(word, field){
	//alert("Checking word "+ word);
	try {
		$.ajax({
			type: "GET",
			url: URL_WORD_FILTER+word,
			name: word,
			success: function(msg){
				if(msg.substring(6,7)=="b"){
					if(field=="yourName"){
						$("#yourName").attr("value",ERROR_FIRST_NAME_INVALID)
					}else{
						$("#friendsName").attr("value", ERROR_FRIEND_NAME_INVALID)
					}
				}else{
					goodWordsCounter++;
					//alert("goodWordsCounter "+ goodWordsCounter);
				}
				if(goodWordsCounter==2){
					//alert("Good words ==2");
					goodWordsCounter = 0;
					sendEmail();
				}
			},
			error:function(msg){
				doLog("check filter: " + msg);
			}
		});
	} catch (error) {
		doLog("Exception: "+error);
	}
}

function sendEmail(){
	var folderPath = window.location.pathname;
	var targetsEmail = $("#friendsEmail").val();
	var usersName = $("#yourName").val();
	var targetsName = $("#friendsName").val();
	var videoID = $("#videoID").val();
	var isFullEp = $("#isFullEp").val();
	var videoCMSID = getCMSIDfromGUID(player.getMetadata().guid);			  
		jQuery.post("/shows/wolverine-and-the-x-men/droplets/sendToFriend_mailer.jhtml",{	 
		id: videoCMSID,
		contenttype: "video",
		email: targetsEmail,
		sendername: usersName,
		friendsname: targetsName,
		etype: "videoEmail",
		URLpath: folderPath,
		videoID:videoID,
		isFullEp:isFullEp
		}, function(data) {
			$("#yourName").attr("value","")
			$("#friendsName").attr("value","")
			$("#friendsEmail").attr("value","")
			formSubmitting = false;
		//alert('Send to a Friend Successful');
		$('#sendToFriend').hide();
		});		
}

function showSendToFriend(){
		if($('#sendToFriend').css("display") == "none"){
	   		$('#sendToFriend').show();
				player.pause();
		}else{
	   		$('#sendToFriend').hide();
		}
	
}

$(document).ready(function() {

    //sendtoafriend
    $('#sendToFriend').hide();
    $('#videoPlayer').show();
    $("#sendThis").click(function() {
        if ($('#sendToFriend').css("display") == "none") {
            $('#sendToFriend').show();
            player.pause();
        } else {
            $('#sendToFriend').hide();
        }
    });


    $("form#sendToFriendForm").submit(function() {

        $("#sendToFriendForm").validate();

        var formIsValid = $("#sendToFriendForm").valid();
        if (formIsValid && !formSubmitting) {
            player.pause();
            //alert("Form is valid, checking words");
            formSubmitting = true;
            checkBadWord($("#yourName").attr("value"), "yourName");
            checkBadWord($("#friendsName").attr("value"), "friendsName");

        }


        return false;
    });

    //sendtoafriend
    //initiate validator on load
    //$(function() {
    // validate contact form on keyup and submit
    if ($("#sendToFriendForm").validate) {
        $("#sendToFriendForm").validate({
            //set the rules for the field names
            rules: {
                yourName: {
                    required: true,
                    minlength: 2
                },
                friendsEmail: {
                    required: true,
                    email: true
                },
                friendsName: {
                    required: true,
                    minlength: 2
                }
            },
            //set messages to appear inline
            messages: {
                name: "Please enter your first name",
                email: "Please enter a valid email address",
                message: "Please enter your friends first name"
            }
        });
    }
});  

function openGameWindow(){
	doTakeover('http://www.nick.com/games/common/syndicated.jhtml?game=wolverine-sentinel', 150, 30, 450, 620, 'no', 'true', 0);
		   pauseVideo();
}