﻿var lastTime;

function setTime()
{
	lastTime = new Date();
}

function showTime(funcName)
{
	dbg("Time:" + funcName + ":" + (new Date() - lastTime));
	lastTime = new Date();
}

$(function() {
    //$('.htmlResults').show();

    if ($("#vpContainer")[0]) {
        checkCookie();
        parseLocationUrl();
        generateSmallAdLink();
        //GetDoubleClickUrlForVideo();
        if (!globalPid) playClip("");
        else playClip(globalPid);        
    }
    createMicroNav();

    $('#clipInfoRatingInterior').stars(
	{
	    inputType: "select",
	    cancelShow: false,
	    callback: setClipRating
	});
});

function GetResults(container, showContentFunc, beforeDataProcessFunc, afterDataProcessFunc, noItemsRetrieveFunc) {
	if (container.data('resultsData') == null) {

		var fake2 = container.find("#fake2");
		if (fake2.length == 0)
			fake2 = container;
		
		var messageHeight = Math.max(container.innerHeight(), 18);
		if($.browser.msie)
		{
			if(container.attr("id").substring(0, 5) == "small")
			{
				messageHeight = 182;
			}
			else
			{
				messageHeight = _currentChannel == "Search" ? 300 : 70;
			}
		}
		var messageWidth = Math.max(container.innerWidth(), 100);
		var message = $("<div></div>").attr("class", "msg-updating").text("Please wait, loading...");
		fake2.prepend(message);
		
		message
			.width(messageWidth)
			.height(messageHeight)
			.css({"line-height": messageHeight+"px", opacity: 0.9, display: "block" });
				
		try
		{
			var offset = fake2.position();
			message.css({"top":offset.top, "left":offset.left})
		}
		catch(e){}
		
		$.ajax({
			type: "POST",
			url: container.data('webMethodUrl'),
			data: container.data('webMethodData'),
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(data) {
				ShowResults(this.jsContainer, data.d, showContentFunc, beforeDataProcessFunc, afterDataProcessFunc, noItemsRetrieveFunc);
			},
			error: GenericAjaxFailure,
			jsContainer: container
		});
		
		for(i = 0; i < 10; i++)
		{
			message
				.animate({"opacity": ".7"}, 1500)
				.animate({"opacity": ".95"}, 500);
		}
	} 
	else 
	{
		if (afterDataProcessFunc != null) afterDataProcessFunc(container);
	}
}

function GenericAjaxFailure(XMLHttpRequest, textStatus, errorThrown) 
{
    this.jsContainer.find(".msg-updating").text("ajax call failed: " + XMLHttpRequest.statusText);
}

function ShowResults(container, searchResults, showContentFunc, beforeDataProcessFunc, afterDataProcessFunc, noItemsRetrieveFunc)
{
	setTime();
	
	container.find(".htmlResults").hide();
	
	container.data("resultsData", searchResults);
	
	if (beforeDataProcessFunc != null) beforeDataProcessFunc(container);
	
	container.find(".msg-updating").remove();
	
	var content = container.find("#contentHolder");
	content.empty();
	
	if (searchResults.length > 0)
	{
		content.append($("<div></div>").attr("id", "tabs-container")
			.append($("<div></div>").attr("id", "list-thumbs"))
			.append($("<div></div>").attr("class", "navig")
				.append($("<ul></ul>").attr("id", "tabs-shorcuts")
				)
			)
		);
	
		var pageSize = container.data("pageSize");
		var fragment, fragmentCount = 1;
	
		for (var i = 0; i < searchResults.length; i++)
		{
			var video = searchResults[i];

			if (i % pageSize == 0)
			{
				fragment = $("<div>").attr("id", "fragment-" + container.attr("id") + fragmentCount);
				content.find("#list-thumbs").append(fragment);

				var shortcut = $("<li></li>")
					.append(
						$("<a></a>")
							.attr("href", "#fragment-" + container.attr("id") + fragmentCount)
							.append($("<span>&#8226;</span>"))
					)
				content.find("#tabs-shorcuts").append(shortcut);

				fragmentCount++;
			}
			
			fragment.append(showContentFunc(container, video));
		}
		
		//* this initiates tabs
		if (searchResults.length > 0)
		{
			var tabsRef = container.find("#tabs-shorcuts");
			tabsRef.tabs({ fx: { opacity: 'toggle'} });
			container.find("#list-thumbs").css({ opacity: 0 }).animate({ opacity: 1 }, 500);
		}
	}
	else
	{
		if (noItemsRetrieveFunc != null) noItemsRetrieveFunc(container);
	}

	if (afterDataProcessFunc != null) afterDataProcessFunc(container);

	showTime("selectStars");
}
function ShowPager(container, totalCount, pageSize, pageIndex, pagerLength, onclickFuncStr)
{
	var pagesCount = (totalCount - (totalCount % pageSize)) / pageSize;
	pagesCount = (totalCount % pageSize != 0) ? pagesCount + 1 : pagesCount;
	
	var leftPageNumber = pageIndex - Math.round(pagerLength / 2) + 1;
	if (leftPageNumber < 0) leftPageNumber = 0;
	
	var rightPageNumber = leftPageNumber + pagerLength - 1;
	if (rightPageNumber >= pagesCount) rightPageNumber = pagesCount - 1;
	
	leftPageNumber = rightPageNumber - pagerLength + 1;
	if (leftPageNumber < 0) leftPageNumber = 0;
	
	var itemsOnPage = totalCount - pageIndex * pageSize;
	if (itemsOnPage > pageSize) itemsOnPage = pageSize;
	
	var paging = $("<div></div>").attr("class", "search-navigation-paging")
		.append($("<span></span>").attr("class", "search-videos-showing")
			.append("Showing " + itemsOnPage + " of " + totalCount + " Items")
		);
	
	container.find(".search-navigation-paging").remove();
	container.prepend(paging);
	
	if(pagesCount > 1)
	{
		var prevPage;
		if (pageIndex > 0)
		{
			prevPage = $("<a></a>")
				.attr("href", "#")
				.attr("class", "view-all roundedLightBlueGrayBg")
				.click(new Function(onclickFuncStr.replace("#currentPage", (pageIndex - 1))))
				.append("<span>&laquo; Previous</span>");
		}
		else
		{
			prevPage = $("<a></a>")
				.attr("class", "view-all roundedGrayBg")
				.append("<span>&laquo; Previous</span>");
		}
		paging.append(prevPage);
		
		var pageLinks = $("<span></span>").attr("class", "page-link-block").css({"margin-top":"3px"});
		for (var i = leftPageNumber; i <= rightPageNumber; i++)
		{
			pageLinks.append($("<a></a>")
				.attr("href", "#")
				.attr("class", "page-link" + (i == pageIndex ? " active" : ""))
				.click(new Function(onclickFuncStr.replace("#currentPage", i)))
				.append( ((i == leftPageNumber && i > 0) || (i == rightPageNumber && i < pagesCount - 1)) ? "..." : i + 1)
			);
		}
		paging.append(pageLinks);

		var nextPage;
		if(pageIndex + 1 < pagesCount)
		{
			nextPage = $("<a></a>")
				.attr("href", "#")
				.attr("class", "view-all roundedLightBlueGrayBg")
				.click(new Function(onclickFuncStr.replace("#currentPage", (pageIndex + 1))))
				.append("<span>Next &raquo;</span>");
		}
		else
		{
			nextPage = $("<a></a>")
				.attr("class", "view-all roundedGrayBg")
				.append("<span>Next &raquo;</span>");
		}
		paging.append(nextPage);
	}
}
function ShowPagerSmall(container, totalCount, pageSize, pageIndex, onclickFuncStr, index)
{
	var pagesCount = (totalCount - (totalCount % pageSize)) / pageSize;
	pagesCount = (totalCount % pageSize != 0) ? pagesCount + 1 : pagesCount;
	
	container.find(".navAnchor").remove();
	
	if(pagesCount <= 1)
	{
		container.find(".navigation-small-expand").hide();
	}
	
	if (pagesCount > pageIndex + 1) {
		container.prepend($("<a></a>")
			.attr("class", "navAnchor")
			.attr("href", "#")
			.click(new Function(onclickFuncStr.replace("#currentPage", (pageIndex + 1))))
			.append($("<img>")
			    .attr("align", "absmiddle")
				.attr("border", "0")
				.attr("src", _assetsBaseUrl + "Images/channel_next.jpg")
			)
		);
	}
	
	if (pageIndex > 0) {
		container.prepend($("<a></a>")
			.attr("class", "navAnchor")
			.attr("href", "#")
			.click(new Function(onclickFuncStr.replace("#currentPage", (pageIndex - 1))))
			.append($("<img>")
			    .attr("align", "absmiddle")
				.attr("border", "0")
				.attr("src", _assetsBaseUrl + "Images/channel_prev.jpg")
			)
		);
	}
}

function ShowSearchResultsPage(containerId, index)
{
	var container = $('#' + containerId);
	container.data("pageIndex", index);
	container.data("pageSize", 10);
	container.data("onclickFuncStr", "ShowSearchResultsPage('" + containerId + "',#currentPage);return false;");
	GetResults(container, ShowClip, null, ChangePage, NoVideosRetrieve);
}

function ShowClip(container, video)
{
	var channelUrl = container.data("channelUrl");
	var jsMethod = container.data("jsMethod");
    
	/*var selectStars = $("<div></div>").attr("class", "stars-rating");
	for (var i=1; i<6; i++)
	{
		selectStars.append($('<input type="radio" value="' + i + '" />'));
	}
	selectStars.stars({ cancelShow: false, disabled: true });
	selectStars.stars('select', video.Rating);*/

	var videoHtml = $(
	"<div class='clip' style='position:relative'>" +
		"<div class='thumb' style='background-image:url(" + video.ThumbnailUrl + ");'>" +
			"<a href='" + channelUrl.replace("#pid#", video.PID) + "' onclick='" + jsMethod.replace("#pid#", video.PID) + "'>" +
				"<img src='/Images/blank.gif' width='95' height='55' />" +
			"</a>" +
		"</div>" +
		"<a class='title hixed-width' href='" + channelUrl.replace("#pid#", video.PID) +"' onclick='" + jsMethod.replace("#pid#", video.PID) + "'>" + video.Title + "</a>" +
		"<div class='info'><div class='stars-rating'><img src='/Images/star" + video.Rating + ".jpg' /></div></div>" + 
	"</div>");
	
	/*var videoHtml = $("<div></div>")
		.attr("class", "clip")
		.append
		(
			$("<div></div>")
			.attr("class", "thumb")
			.attr("style", "background-image:url(" + video.ThumbnailUrl + ");")
			.append
			(
				$("<a></a>")
				.attr("href", channelUrl.replace("#pid#", video.PID))
				.append
				(
					$("<img>")
					.attr("src", _assetsBaseUrl + "Images/blank.gif")
					.width(95).height(55)
				)
			)
		)
		.append
		(
			$("<a></a>")
			.attr("class", "title hixed-width")
			.attr("href", channelUrl.replace("#pid#", video.PID))
			.append(video.Title)
		)
		.append
		(
			$("<div></div>")
			.attr("class", "info")
			.append(selectStars)
		);*/
				
		return videoHtml;
}

function NoVideosRetrieve(container)
{
    var content = container.find("#contentHolder");
    content.append(container.find('#noItems').clone().removeClass("display-none"));
	container.find('.navigation-small').hide();
}

function ChangePageSmall(container)
{
	var pageIndex = container.data("pageIndex");
	if (pageIndex == null) pageIndex = 0;

	var tabsRef = container.find("#tabs-shorcuts");
	if (tabsRef != null)
		tabsRef.tabs('select', pageIndex);
	
	ShowPagerSmall(
		container.find("#pager"),
		container.data("resultsData").length,
		container.data("pageSize"),
		pageIndex,
		container.data("onclickFuncStr"),
		container.data("index"));
}
function ChangePage(container)
{
	var pageIndex = container.data("pageIndex");
	
	var tabsRef = container.find("#tabs-shorcuts");
	tabsRef.tabs('select', pageIndex);
	
	ShowPager(
		container.find("#pager"),
		container.data("resultsData").length,
		container.data("pageSize"),
		pageIndex,
		10,
		container.data("onclickFuncStr"));
}

function dbg(str)
{
	if (typeof console != "undefined" && console.log)
	{
		console.log(str);
	}
}

Array.remove = function(array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};

Array.contains = function(array, item) {
  for (i in array) if (array[i] == item) return true;
  return false;
};

Array.insert = function(array, index, item) {
  array.splice(index, 0, item);
};

function getFunctionName(fn)
{
	var name=/\W*function\s+([\w\$]+)\(/.exec(fn);
	if(!name)return 'No name';
	return name[1];
}


//function GetDoubleClickUrlForVideo()
//{
//	if ((!delayedClip) && (!defaultPlayed))
//	{
//		try
//		{
//			delayedClip = _relatedVideosAdminData[0];
//		}
//		catch(e){};
//	}
//	$.ajax({
//		type: "POST",
//		url: "/Services/Service.asmx/GetReleaseInfo",
//		data: "{'PID' : '" + delayedClip + "'}",
//		contentType: "application/json; charset=utf-8",
//		dataType: "json",
//		success: done,
//		failure: GenericAjaxFailure
//	});
//	
//	function done(data)
//	{
//		var title = (data.d) ? data.d.Title : "";
//		while (title.search("\"")!=-1)
//			title = title.replace("\"","%22");
//		while (title.search(" ")!=-1)
//			title = title.replace(" ","%20");
//		while (title.search("&")!=-1)
//			title = title.replace("&","%26");

//		var clip = (delayedClip) ? delayedClip : "";

////		var searchStr = "";
//		//* this allows Ad team test certain ads only in dev environment
////		if (location.hostname == "dev.video.msg.com") 
////		{
////			searchStr = "test";
////		}

////		var url = "http://ad.doubleclick.net/pfadx/video.thegarden/{zone1};" +
////					"s1={s1};s2=;pos=video;" +
////					"vid={PID};msg=ad;kw={searchStr};tile=1;sz=1000x1000;";

////		PopulateDoubleClickValues();
////					
////		url = url.replace("{zone1}", _doubleClickZone1)
////					.replace("{s1}", _doubleClickS1)
////					.replace("{PID}", clip)
////					.replace("{videoTitle}", title)
////					.replace("{searchStr}", searchStr);
//		
////		if ((clipNum == 0) || (clipNum >= _numberOfVideosBeforeAds))
////		{
////		    playclip(clip);
////		}
////		else 
////		{
////			//toggleViewMode();
////
//		//		}
//		playClip(globalPid);
//	}
//	
//}

function generateSmallAdLink()
{
	smallAdLink = "http://ad.doubleclick.net/adi/video.thegarden/{zone1};s1={s1};";
	
	PopulateDoubleClickValues();
	smallAdLink = smallAdLink.replace("{zone1}", _doubleClickZone1)
								.replace("{s1}", _doubleClickS1);
}

//* dcopt=ist should only happen once per page
//* it controls "expandable" ads and there should only be one
function GetDoubleClickUrlForDisplayAd(size, tile, showDCOPT)
{
	var url = "http://ad.doubleclick.net/adj/video.thegarden/{zone1};s1={s1};s2=;pos=top;msg=ad;" +
				"kw={searchStr};" +
				"tile={tile};" +
				"sz={size};" + 
				(showDCOPT ? "dcopt=ist;" : "") +
				"ord=" + _doubleClickOrd;

	PopulateDoubleClickValues();

	var searchStr = ($("#searchBoxInput").length > 0) ? $("#searchBoxInput")[0].value.replaceAll("\"", "") : "";

	//* this allows Ad team test certain ads only in dev environment
	if (location.hostname == "dev.video.msg.com")
	{
		searchStr = "test";
	}

	url = url.replace("{zone1}", _doubleClickZone1)
			.replace("{s1}", _doubleClickS1)
			.replace("{tile}", tile)
			.replace("{size}", size)
			.replace("{searchStr}", searchStr);
	
	return url;
}
function PopulateDoubleClickValues()
{
	if (location.href.toLowerCase().indexOf("/search/") != -1)
	{
		_doubleClickZone1 = "search";
		_doubleClickS1 = "search";
		return;
	}

	switch (_currentChannelUrl.toLowerCase())
	{
		case "All".toLowerCase():
			_doubleClickZone1 = "homepage";
			_doubleClickS1 = "homepage";
			break;

		case "MSG-Local-Sports".toLowerCase():
			_doubleClickZone1 = "local";
			_doubleClickS1 = "local";
			break;

		case "MSG-Networks".toLowerCase():
			_doubleClickZone1 = "msg_networks";
			_doubleClickS1 = "msg_networks";
			break;

		case "New-York-Liberty".toLowerCase():
			_doubleClickZone1 = "nyliberty";
			_doubleClickS1 = "nyliberty";
			break;

		case "New-York-Rangers".toLowerCase():
			_doubleClickZone1 = "nyrangers";
			_doubleClickS1 = "nyrangers";
			break;

		case "New-York-Knicks".toLowerCase():
			_doubleClickZone1 = "nyknicks";
			_doubleClickS1 = "nyknicks";
			break;
	}
}
