var adMode = true;
//var clipNum;
var delayedClip = "";
var globalPid;
var defaultPlayed = false;
var playerReady = true;
var smallAdLink = "";
var bigTagsShown = false;

var _adData =
{
	url250: '',
	mode: 0
};

function checkCookie()
{
//    if (!$.cookie('videoViewed'))	
//	{	    
//		clipNum = 0;
//	}
//	else clipNum = $.cookie('videoViewed');	
	if (!$.cookie('smallAd'))
	{
		$.cookie('smallAd', '');
	}	
}
function parseLocationUrl()
{
	var url = window.location.href;
	var channelUrl = _currentChannelUrl;
	if (channelUrl == "All") channelUrl = "Home";
	if (url.search(channelUrl) == -1)
	    globalPid = url.substr(url.lastIndexOf("/") + 1, url.length);
	else globalPid = url.substr(url.search(channelUrl)+channelUrl.length + 1,url.length);
//	if (delayedClip) 
//	{
//		setPlayed();
//	}
}
// SEARCH ////////////////////////////

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, "");
}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
strTarget, // The substring you want to replace
strSubString // The string you want to replace in.
) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        strText = strText.replace(strTarget, strSubString)

        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf(strTarget);
    }

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return (strText);
}

function search(channel, keywords)
{
	if(!keywords)
	{
		keywords = $("#searchBoxInput")[0].value;
	}
	keywords = keywords.trim();
	if(keywords.length == 0)
	{
		return;
	}

	var channel = $("#searchFilterText").attr("channel");
	
	keywords = Url.encode(keywords);

	window.location.href = "/Search/" + channel + "?search=" + keywords;
}

function toggleFilter()
{
	document.onclick = null;
	var dd = $("#searchFilterDropdown")[0];
	if(dd.style.display == "block")
	{
		dd.style.display = "none";
	}
	else
	{
		$(".page").append(dd);
		dd.style.display = "block";
		document.onclick = toggleFilter;
	}
}

function selectFilter(text, value)
{
	var searchFilterText = $("#searchFilterText");
	searchFilterText.text(text);
	searchFilterText.attr("channel", value);
}


// VIDEO PLAYER //////////////////////

function createVideoPlayer(pid)
{
	vp = document.getElementById('vpObject');
	globalPid = pid;
	if(vp)
	{
		try
		{
			vp.closeSession();
			vp.sendEvent('LOAD',null);
		} 
		catch(err){}
	}
	else proceedLoading();
}

function proceedLoading()
{
	setTimeout("addPlayerToStage(globalPid)",1);
}

function setReady()
{
	playerReady = true;
}

function addPlayerToStage(pid)
{
	var container = $("#vpContainer")[0];
	if(container)
	{
		var so = new SWFObject("/flash/player.swf", "vpObject", "100%", "100%", "9");
		so.addParam("allowscriptaccess", "always");
		so.addParam("allowfullscreen", "true");
		so.addParam("allownetworking", "all");
		so.addParam("wmode", "transparent");
		so.addParam("menu", "false");
		if (!defaultPlayed)
		{
			try
			{
				so.addVariable("related", _relatedVideosAdminData);
			}
			catch(e){};
		}
		so.addVariable("functions", "setAdUrls,resizeVideoPlayer,updateClipDetails,getPlayed,setPlayed,increaseClipCounter,checkAdMode,proceedLoading,toggleViewMode");
		so.addVariable("pid", pid);
		so.addVariable("isnormal", "true");
		so.addVariable("channelurl", _currentChannelUrl);
		so.addVariable("channel", _currentChannelUrl);
		so.addVariable("wsdl", _webServiceUrl);
		so.addVariable("serviceurl", _playerDataUrl);
		so.addVariable("adreporturl", _adReportUrl);
		so.addVariable("errorreporturl", _errorReportUrl);
		so.addVariable("errormes", _errorVideoMissing);
		so.addVariable("videoreporturl", _videoViewedReportUrl);

		so.write(container);
	}
}

/*
	there are 3 sizes of the player: regular, large and full screen
	called when user switches b/w regular and large size
	TODO: should NOT pass in W, H. just regular/large so that there is only one place to change dimensions of the player
*/
function resizeVideoPlayer(w, h)
{
	$("#vpContainer")
		.css(
			{
				width: w + "px",
				height: h + "px"
			}
		);

	if (w < 650)	//* this give us flexibitlity if we need to increase the size of the player, we will not need to update JS
	{
		$("#adContainer").show();
		$("#vpContainer")
			.css( {left: "60px"} );
			
		$("#modalBg")
			.animate(
				{
					"opacity" : "0"
				}, 500, function()
				{
					$(this).css({"display" : "none"})
				}
			)
	}
	else	//* large size
	{
		//* ad contain IFRAMES and they were interfering with Video Player buttons
		$("#adContainer").hide();
		
		var centeredLeft = ($("#header").width() - $("#vpContainer").width()) / 2;
		
		if (($.browser.msie) && ($.browser.version < 7)) 
		{
		
		}
		else 
		{
		
			$("#modalBg")
				.css(
					{
						"display": "block",
						"width": $(document).width(),
						"height": $(document).height()
					})
				.animate(
					{
						"opacity": ".8"
					}, 1000);
		}

		$("#vpContainer")
			.css(
				{
					left: centeredLeft + "px"
				}
			);
	}
}

//function onVideoPlayerReady(obj)
//{
//	player = document.getElementById(obj.id);
//	player.addModelListener('STATE', 'monitorVideoPlayerState');
//}

//function monitorVideoPlayerState(obj)
//{
//	if(obj.newstate == 'COMPLETED')
//	{
//		if (adMode)
//		{
//			clipNum = 0;
//			//$.cookie('clipNum', 0);
//			//toggleViewMode();
//			if (delayedClip.length > 0) 
//			{
//				//playClip(delayedClip);
//				delayedClip = "";
//			}
//		}
//	}
//}

//function getPlayed()
//{
//	return defaultPlayed;
//}

function setPlayed()
{
	defaultPlayed = true;
}

//function increaseClipCounter()
//{
//	clipNum++;
//	$.cookie('clipNum', clipNum);
//}

//function setDelayedClip(clipId)
//{
//	delayedClip = clipId;
//}


// MICRO NAV /////////////////////////

function createMicroNav()
{
	var container = $("#microNavContainer")[0];
	if(container)
	{
		var so = new SWFObject("/flash/micronav.swf", "microNavObject", "100%", "100%", "9");
		so.addParam("allowscriptaccess", "always");
		so.addParam("allowfullscreen", "true");
		so.addParam("allownetworking", "all");
		so.addParam("wmode", "transparent");
		so.addParam("menu", "false");

		so.addVariable("dataUrl", _mnDataUrl);
		so.addVariable("noVideosMessage", _errorNoVideos);
		so.addVariable("playClipFunc", "playClip");

		so.write(container);
	}
}

function playClip(clipId)
{    
    $("#clipInfoTagsBig").hide();
    $("#clipInfoBlock").hide();    
	if (playerReady)
	{
		$('#channel-comments').hide();
		if ((!adMode)||(!defaultPlayed))
		{
		    setPlayed();
		    createVideoPlayer(clipId);
		}
		else
		{
			delayedClip = clipId;
		}		
	}
	$.scrollTo(0, 400);
}

//function checkAdMode(clipId)
//{
//	playerReady = false;
//	setTimeout(setReady,1000);
//	if (clipNum >= _numberOfVideosBeforeAds)
//	{
//		//toggleViewMode();
//		//delayedClip = clipId;
//		//GetDoubleClickUrlForVideo();
//		playClip(clipId);
//		return true;
//	}

//	return false;
//}

function playDelayed() 
{
    if (delayedClip.length > 0) 
			{
				playClip(delayedClip);
				delayedClip = "";
			}}

//function changeCookiesAdMode(mode) 
//{
//    $.cookie('adMode', mode);    
//}

function toggleViewMode(mode)
{    
        adMode = mode;

        // show/hide header content		
        if (adMode) {
            $("#searchBlock").hide();
            $("#clipInfoBlock").hide();
            $("#channelMenu").hide();
            $("#microNav").hide();
            setAdMode(0);                        
        }
        else {
            $("#searchBlock").show();
            $("#clipInfoBlock").show();
            $("#channelMenu").show();
            $("#microNav").show();
            setAdMode(100);            
            playDelayed();
        }    
}

function updateClipDetails(vi)
{
    globalPid = vi.pid;
    $("#clipInfoTagsBig").hide();
    $("#clipInfoBlock").show();
    if (vi.title.length > 50) vi.title = vi.title.substring(0, 50) + "...";
	$("#clipInfoTitle").text(vi.title);
	$("#clipInfoDescription").text(vi.description);
	$("#clipInfoDate").text(vi.publishingDate);
	$("#clipInfoViews").text(vi.numberOfViews + " Views");
	applyRating(vi.rating);
	parseKeywords(vi.keyWords);	
	
	if (typeof(getSmallComment) != "undefined")
		getSmallComment(vi.pid);
    
	function applyRating(rating)
	{
		$('#clipInfoRatingInterior').stars('select', rating);
		$('#clipInfoRating').show();
	}
	
	function parseKeywords(keywords)
	{	   
		if(keywords.length > 0)
		{		    
		    $("#clipInfoTagsSmall").find(".clipInfoTag").remove();
		    $("#clipInfoTagsBig").find(".clipInfoTag").remove();		    
			$("#clipInfoTagsSmall").show();			
			var tags = keywords.split(',');
			var totalWidth = 0;
			var bigTagsAvaible = false;
			for(i = 0; i < tags.length; i++)
			{
			    var tag = tags[i].trim();			    
				if(tag.length > 0)
				{				    
					var tagElement = $("<span></span>").attr("class", "clipInfoTag")
						.append($("<a></a>").attr("href", "javascript:search('" + _currentChannel + "','\"" + tag.trim() + "\"')").text(tag));
					var tagElementBig = $("<span></span>").attr("class", "clipInfoTag")
						.append($("<a></a>").attr("href", "javascript:search('" + _currentChannel + "','\"" + tag.trim() + "\"')").text(tag));
					$("#clipInfoTagsSmall").append(tagElement);
					$("#clipInfoTagsBig").append(tagElementBig);
					var tagElementWidth = tagElement.innerWidth() + 5; // +margin
					if (totalWidth + tagElementWidth > 280)
					{
					    tagElement.remove();
					    bigTagsAvaible = true;					    
					}
					else
					{
						totalWidth += tagElementWidth;
					}
				}
			}
			if (bigTagsAvaible) 
			{
			    var tagElement = $("<span></span>").attr("class", "clipInfoTag")
						.append($("<a>&#9658</a>").attr("href", "javascript:showBigTags()"));
			    $("#clipInfoTagsSmall").append(tagElement);
			}
		}
		else
		{
			$("#clipInfoTagsSmall").hide();
		}
	}
}

function showBigTags() 
{    
    $("#clipInfoBlock").fadeOut(500);
    $("#clipInfoTagsBig").fadeIn(500);
}

function showSmallTags() 
{
    $("#clipInfoTagsBig").fadeOut(500);
    $("#clipInfoBlock").fadeIn(500);  
}

function setClipRating(ui, type, value)
{
	$.ajax({
		type: "POST",
		url: "/Services/Service.asmx/VoteRating",
		data:
		"{" + 
			"'pid': '" + globalPid + "', " +
			"'rating': '" + value + "'" +
		"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: done,
		failure: GenericAjaxFailure
	});

	function done(data)
	{
	}
}


// COMPANION AD //////////////////////

function setAdUrls(url100, url250)
{
	$.cookie('smallAd', url100);
	_adData.url250 = url250;
	setAdMode(250);
}

function setAdMode(mode)
{
	_adData.mode = mode;

	// hide ad at first
	$("#adContainer").css({ top: "-9999px" });
	// load requested url into the ad's frame
	var adFrame = $("#adContainerFrame")[0];
	switch(mode)
	{
		case 250:
		{
			adFrame.src = _adData.url250;
			break;
		}	
		case 100:
		{
			adFrame.src = smallAdLink + $.cookie('smallAd').substr( $.cookie('smallAd').search("s2"),$.cookie('smallAd').length );
			break;
		}
	}
}


function onAdFrameLoaded()
{
	// resize container basing on the ad mode
	switch(_adData.mode)
	{
		case 250:
		{
			$("#adContainer").css({
				"background-image": "url(" + _assetsBaseUrl + "Images/ad250_bg.png)",
				height: "250px",
				top: "110px"
			});
			$("#adContainerFrame").css({
				height: "250px"
			});
			break;
		}
		case 100:
		{
			$("#adContainer").css({
				"background-image": "url(" + _assetsBaseUrl + "Images/ad100_bg.png)",
				height: "100px",
				top: "445px"
			});
			$("#adContainerFrame").css({
				height: "100px"
			});
			break;
		}
	}
}
