var styleIndex = 0;
var styleClasses = ["previewTitle", "comingSoonTitle", "outNowTitle"];
var prefs;
var searchPopout;
function init(){
	dojo.forEach(
		dojo.query(".dijitTitlePaneContentOuter"),
		function(outDivEl){
			outDivEl.style.borderStyle = "none";
		}
	);
	dojo.forEach(
		dojo.query(".dijitTitlePaneTitle"),
		function(outDivEl){
			outDivEl.id = styleClasses[styleIndex++];
		}
	);
	//change description popout
	dojo.forEach(
		dojo.query(".mbPopout"),
		function(pod){
			pod = pod.parentNode;
			var podDijit = dijit.byId(pod.id);
			podDijit.finalClose = podDijit.close;
			podDijit.close = delayPopoutClose;
			podDijit.runningTime = 0;
			podDijit.cancelClose = false;
		}
	);
	//get prefs from cookie
	var prefsString = dojo.cookie("prefs");
	if(typeof prefsString == "undefined" || prefsString == null){
		prefs = createBlankClientConfig();
	}
	else{
		prefs = dojo.fromJson(prefsString);
	}
	applyPrefs();
	initSearch();
	//the following must remain the final line
	dojo.byId("splashDiv").style.display = "none";
	dojo.byId("movieBoxContainer").style.display = "block";
}

function initSearch(){
	var divWrapper = dojo.create("div");
	var contentWrapper = dojo.create("div", {className:"dialogContent"});
	contentWrapper.appendChild(document.createTextNode("Start typing to search for a movie"));
	dojo.create("br", {}, contentWrapper);
	
	var searchInput = dojo.create("input");
	searchInput.type = "text";
	searchInput.id = "searchInput";
	searchInput.name = "searchInput";
	searchInput.value = "";
	contentWrapper.appendChild(searchInput);
	new dijit.form.TextBox({id:"searchInput", value:"", type:"text", trim:"true", onChange:updateSearch, intermediateChanges:true}, searchInput);
	
	var searchResults = dojo.create("div", {id:"searchResults"}, contentWrapper);
	
	var searchButtonContainer = dojo.create("div", {id:"searchButtonContainer"}, contentWrapper);
	var closeSearchButton = dojo.create("button", {innerHTML:"Close"}, searchButtonContainer);
	new dijit.form.Button({
		onClick:function(){
			searchPopout.hide();
			dojo.byId("searchResults").innerHTML = "";
		}
	}, closeSearchButton);
	
	searchPopout = new dijit.Dialog({
			id:"searchPopout",
			title: "Search for a Movie",
			draggable: false
		}, divWrapper);
	searchPopout.setContent(contentWrapper);
	searchPopout.onCancel = function(){
		searchPopout.hide();
		dojo.byId("searchResults").innerHTML = "";
	}
	searchPopout.startup();
}

function applyPrefs(){
	try{
		if(prefs.prefs.movieNewWindow == true){
			dijit.byId('openTypeNew').setChecked(true);
		}
		else{
			dijit.byId('openTypeSame').setChecked(true);
		}
		if(!prefs.prefs.previewsPane){
			dijit.byId('dijit_TitlePane_0').toggle();
		}
		if(!prefs.prefs.comingSoonPane){
			dijit.byId('dijit_TitlePane_1').toggle();
		}
		if(!prefs.prefs.releasedPane){
			dijit.byId('dijit_TitlePane_2').toggle();
		}
		if(purgePrefsArrays()){
			updatePrefs();
		}
		if(typeof queueItems != "undefined" && queueItems != null){
			for(var i = queueItems.length - 1; i >= 0; i--){
				var queueItem = dojo.byId(queueItems[i]);
				if(typeof queueItem != "undefined" && queueItem != null){
					var found = false;
					for(var j = 0; j < prefs.inQueue.length; j++){
						if(prefs.inQueue[j] == queueItems[i]){
							found = true;
						}
					}
					if(!found){
						prefs.inQueue.push(queueItems[i]);
					}
				}
			}
		}
		for(var i = prefs.ignored.length - 1; i >= 0; i--){
			removeIgnored(prefs.ignored[i]);
		}
		for(var i = prefs.inQueue.length - 1; i >= 0; i--){
			removeIgnored(prefs.inQueue[i]);
		}
	}catch(err){}
}

function updatePrefs(){
	dojo.cookie("prefs", dojo.toJson(prefs), {expires : 90});
}

function restoreHidden(){
	prefs.ignored = new Array();
	prefs.inQueue = new Array();
	updatePrefs();
	location.reload(true);
}

function updateSectionsOpen(){
	prefs.prefs.previewsPane = dijit.byId('dijit_TitlePane_0').open;
	prefs.prefs.comingSoonPane = dijit.byId('dijit_TitlePane_1').open;
	prefs.prefs.releasedPane = dijit.byId('dijit_TitlePane_2').open;
	updatePrefs();
}

function updateMovieWindowPref(){
	if(dijit.byId('openTypeNew').checked){
		prefs.prefs.movieNewWindow = true;
	}
	else{
		prefs.prefs.movieNewWindow = false;
	}
	updatePrefs();
}

function removeIgnored(divId){
	var parentTable = dojo.byId(divId);
	if(typeof parentTable == "undefined" || parentTable == null){
		return;
	}
	while(parentTable.nodeName != "TABLE"){
		parentTable = parentTable.parentNode;
	}
	if(dojo.byId(divId).parentNode.className == "mbTop"){		
		var hiddenMBs = dojo.query("td.mbHiddenRight", parentTable);
		if(hiddenMBs.length > 0){
			hiddenMBs[0].className="mbTop";
		}
	}
	dojo.destroy(dojo.byId(divId).parentNode);
	updateButtons(parentTable.id.replace("Inner", ""));
}

function carouselNext(tableId){
	var nextButton = dojo.byId(tableId + "next");
	if(nextButton.src.indexOf("nextDis.png") != -1){
		return;
	}
	var carouselTable = dojo.byId(tableId);
	var firstVisibleTd = dojo.query("td.mbTop", carouselTable)[0];
	var firstVisible = dojo.query("> div", firstVisibleTd)[0];
	hideMB(firstVisible.id, false);
}

function carouselPrev(tableId){
	var prevButton = dojo.byId(tableId + "prev");
	if(prevButton.src.indexOf("prevDis.png") != -1){
		return;
	}
	var carouselTable = dojo.byId(tableId);
	var allInvisibleTd = dojo.query("td.mbHiddenLeft", carouselTable);
	var firstInvisible = allInvisibleTd[allInvisibleTd.length - 1];
	var invisibleDiv = dojo.query("> div", firstInvisible)[0];
	var toHideTds = dojo.query("td.mbTop", carouselTable);
	var toHideTd = toHideTds[toHideTds.length - 1];
	var toHideDiv = dojo.query("> div", toHideTd)[0];
	//hideMB(invisibleDiv.id, false);
	var removeMBFunction = new Function("var divTemp = dojo.byId('" + toHideDiv.id + "');divTemp.parentNode.className='mbHiddenRight';updateButtons('" + tableId.replace("Inner", "") + "');");
	toHideTd.className="";
	var wipeOutMB = dojox.fx.wipeTo({
		node: toHideDiv.id,
		duration: 300, 
		width:1, 
		onEnd:removeMBFunction}
	);
	var anims = new Array();
	anims.push(wipeOutMB);
	var clearMBStyleFunction = new Function('dojo.byId("' + invisibleDiv.id + '").removeAttribute("style");dojo.byId("' + invisibleDiv.id + '").parentNode.className="mbTop"');
	dojo.removeClass(firstInvisible, "mbHiddenLeft");
	invisibleDiv.style.width = "1px";
	var wipeInMB = dojox.fx.wipeTo({
		node: invisibleDiv.id,
		duration: 300, 
		width:204,
		onEnd:clearMBStyleFunction}
	);
	anims.push(wipeInMB);
	var combinedAnim = dojo.fx.combine(anims);
	combinedAnim.play();
}

function hideMB(divId, isRemove, section){
	dojo.byId(divId).parentNode.className="";
	var removeMBFunction;
	var parentTable = dojo.byId(divId);
	while(parentTable.nodeName != "TABLE"){
		parentTable = parentTable.parentNode;
	}
	if(isRemove){
		logAction(divId, "hide", section);
		prefs.ignored.push(divId);
		updatePrefs();
		removeMBFunction = new Function("dojo.destroy(dojo.byId('" + divId + "').parentNode);updateButtons('" + parentTable.id.replace("Inner", "") + "');");
	}
	else{
		removeMBFunction = new Function("var divTemp = dojo.byId('" + divId + "');divTemp.parentNode.className='mbHiddenLeft';updateButtons('" + parentTable.id.replace("Inner", "") + "');");
	}
	var wipeOutMB = dojox.fx.wipeTo({
		node: divId,
		duration: 300, 
		width:1, 
		onEnd:removeMBFunction}
	);
	var anims = new Array();
	anims.push(wipeOutMB);
	//find next movie to show if applicable
	var hiddenMBs = dojo.query("td.mbHiddenRight", parentTable);
	if(hiddenMBs.length == 0){
		hiddenMBs = dojo.query("td.mbHiddenLeft", parentTable);
		if(hiddenMBs.length > 0){
			hiddenMBs[0] = hiddenMBs[hiddenMBs.length - 1];
		}
	}
	if(hiddenMBs.length > 0){
		dojo.removeClass(hiddenMBs[0], "mbHiddenRight");
		var divToKeyOff = dojo.query("> div", hiddenMBs[0])[0];
		divToKeyOff.style.width = "1px";
		var clearMBStyleFunction = new Function('dojo.byId("' + divToKeyOff.id + '").removeAttribute("style");dojo.byId("' + divToKeyOff.id + '").parentNode.className="mbTop"');
		var wipeInMB = dojox.fx.wipeTo({
			node: divToKeyOff,
			duration: 300, 
			width:204,
			onEnd:clearMBStyleFunction}
		);
		anims.push(wipeInMB);
	}
	
	var combinedAnim = dojo.fx.combine(anims);
	combinedAnim.play();
	//updateButtons(parentTable.id);
}

function updateButtons(tableId){
	setTimeout("updateButtonsJump('" + tableId + "')", 100);
}

function updateButtonsJump(tableId){
	var carouselTable = dojo.byId(tableId);
	var lInvisibleTds = dojo.query("td.mbHiddenLeft", carouselTable);
	var prevButton = dojo.byId(tableId + "prev");
	if(lInvisibleTds.length == 0){
		prevButton.src = "img/prevDis.png";
		dojo.removeClass(prevButton, "slideEnabled");
		dojo.addClass(prevButton, "slideDisabled");
	}
	else{
		prevButton.src = "img/prev.png";
		dojo.addClass(prevButton, "slideEnabled");
		dojo.removeClass(prevButton, "slideDisabled");
	}
	var rInvisibleTds = dojo.query("td.mbHiddenRight", carouselTable);
	var nextButton = dojo.byId(tableId + "next");
	if(rInvisibleTds.length == 0){
		nextButton.src = "img/nextDis.png";
		dojo.removeClass(nextButton, "slideEnabled");
		dojo.addClass(nextButton, "slideDisabled");
	}
	else{
		nextButton.src = "img/next.png";
		dojo.addClass(nextButton, "slideEnabled");
		dojo.removeClass(nextButton, "slideDisabled");
	}
	var visibleTdsNodes = dojo.query("td.mbTop", carouselTable);
	var visibleTds = visibleTdsNodes.length;
	var widthDiv = dojo.byId(tableId + "div");
	widthDiv.style.width = ((visibleTds > 5 ? 5 : visibleTds) * 204) + 12 + "px";
	if(visibleTds == 0){
		dojo.forEach(
				dojo.query("input.slideDisabled", carouselTable),
				function(navButton){
					navButton.style.display = "none";
				}
		);
		var emptySectionMsgs = dojo.query("td.emptySection", carouselTable);
		if(emptySectionMsgs.length == 0){			
			var msgTR = carouselTable.insertRow(-1);
			var msgTD = dojo.create("td", {className:"emptySection", innerHTML:"All movies for this section have been added or hidden."}, msgTR);
		}
	}
}

var savedNoHide = new Array();
function logAction(nfId, action, section){
	try{
		if(action == "queue"){
			savedNoHide.push(nfId);
		}
		if(action == "hide" && savedNoHide.contains(nfId)){
			return;
		}
		var xhrArgs = {
	            url: "MovieAction",
	            content: {nfId:nfId, action:action, section:section},
	            handleAs: "text"
	        };
		dojo.xhrPost(xhrArgs);
	}catch(err){}
}

function openMovie(nfUrl){
	if(dojo.byId("openTypeNew").checked){
		window.open(nfUrl);
	}
	else{
		window.location.href = nfUrl;
	}
}

function addMovieWrapper(nfId, offX, offY, custKey, queueType, domEl, buttonId, section){
	logAction(nfId, "queue", section);
	if(typeof prefs != "undefined" && prefs != null){
		prefs.inQueue.push(nfId);
		updatePrefs();
	}
	nflx.addToQueue(nfId, offX, offY, custKey, queueType, domEl);
	dijit.byId(buttonId).setLabel("Saved");
	dijit.byId(buttonId).setDisabled(true);
	dijit.byId(buttonId).setAttribute("iconClass", "addedMovieIcon");
}

function createBlankClientConfig(){
	var rv = {};
	rv.prefs = {};
	rv.prefs.previewsPane = true;
	rv.prefs.comingSoonPane = true;
	rv.prefs.releasedPane = true;
	rv.prefs.movieNewWindow = false;
	rv.ignored = new Array();
	rv.inQueue = new Array();
	return rv;
}

function purgePrefsArrays(){
	var rv = false;
	for(var i = prefs.ignored.length - 1; i >= 0; i--){
		var testEl = dojo.byId(prefs.ignored[i]);
		if(typeof testEl == "undefined" || testEl == null){
			arrayRemove(prefs.ignored, i);
			rv = true;
		}
	}
	for(var i = prefs.inQueue.length - 1; i >= 0; i--){
		var testEl = dojo.byId(prefs.inQueue[i]);
		if(typeof testEl == "undefined" || testEl == null){
			arrayRemove(prefs.inQueue, i);
			rv = true;
		}
	}
	return rv;
}

function showSearch(){
	rebuildSearchIndex();
	dijit.byId("searchInput").setValue("");
	dojo.byId("searchResults").innerHTML = "";
	if(navigator.userAgent.indexOf("MSIE") == -1){
		//searchPopout._relativePosition = { t: 50 };
	}
	searchPopout.show();
}

var searchItems;
function rebuildSearchIndex(){
	searchItems = new Array();
	var allMovieBoxes = dojo.query(".mbTop, .mbHiddenRight, .mbHiddenLeft");
	for(var i = 0; i < allMovieBoxes.length; i++){
		var aMovieBox = allMovieBoxes[i];
		var descId = dojo.query("img.moviePoster", aMovieBox)[0].id.replace("mov", "movTT");
		var item = {};
		item.title = dojo.query("span.mbTitleLink", aMovieBox)[0].innerHTML;
		item.image = dojo.query("img.moviePoster", aMovieBox)[0].src;
		//item.description = dojo.query("div.mbPopout", aMovieBox)[0].innerHTML;
		item.description = dojo.byId(descId).innerHTML;
		item.release = dojo.query("span.mbReleaseDate", aMovieBox)[0].innerHTML;
		item.id = dojo.query("div.MBDiv", aMovieBox)[0].id;
		searchItems.push(item);
	}
}

function updateSearch(newVal){
	for(var i = 0; i < toolTipIds.length; i++){
		try{
			dijit.byId(toolTipIds[i]).close();
		}catch(err){}
	}
	toolTipIds = new Array();
	
	dojo.byId("searchResults").innerHTML = "";
	if(newVal.length < 3){
		return;
	}
	var searchSplashMsg = dojo.create("img", {id:"searchSplashMsg", src:"img/loading.gif"}, dojo.byId("searchResults"));
	var matching = new Array();
	var searchTerms = newVal.split(" ");
	for(var i = 0; i < searchItems.length; i++){
		var matchCount = 0;
		for(var j = 0; j < searchTerms.length; j++){
			if(searchItems[i].title.toLowerCase().indexOf(searchTerms[j].toLowerCase()) != -1){
				matchCount++;
			}
		}
		if(matchCount == searchTerms.length){
			matching.push(searchItems[i]);			
		}
	}
	if(matching.length == 0){
		dojo.byId("searchResults").innerHTML = "";
		var searchSplashMsg = dojo.create("span", {id:"searchSplashMsg", className:"searchSplashMsg", innerHTML:"No results found"}, dojo.byId("searchResults"));
		return;
	}
	var searchResultWrapper = dojo.create("div");
	searchResultWrapper.style.display = "none";
	dojo.byId("searchResults").appendChild(searchResultWrapper);
	
	var searchResultTable = dojo.create("table");
	searchResultWrapper.appendChild(searchResultTable);
	var currentRow;
	var rowCount = 0;
	for(var i = 0; i < matching.length; i++){
		
		if(i % 3 == 0){
			currentRow = searchResultTable.insertRow(-1);
			rowCount++;
		}
		var td = dojo.create("td");
		td.className = "mbTop";
		td.align = "center";
		td.appendChild(buildMovieBox(matching[i]));
		currentRow.appendChild(td);
		
	}
	if(rowCount > 2){
		searchResultWrapper.style.height = (209 * 3 - 100) + "px";
		searchResultWrapper.style.overflowY = "scroll";
		searchResultWrapper.scrollTop = "0px";
	}
	searchSplashMsg.style.display = "none";
	searchResultWrapper.style.display = "block";
	searchPopout.layout();
}

var toolTipIds = new Array();
function buildMovieBox(mbMetaData){
	var topDiv = dojo.create("div", {className:"MBDiv"});
	var tt = dojo.create("table");
	topDiv.appendChild(tt);
	var tr = tt.insertRow(-1);
	var td = dojo.create("td", {className:"mbTitle", align:"center"}, tr);
	dojo.create("span", {className:"mbTitleLink", innerHTML:mbMetaData.title}, td);
	tr = tt.insertRow(-1);
	td = dojo.create("td", {align:"center"}, tr);
	var toolTipId = getNextSearchTooltipId();
	var moviePoster = dojo.create("img", {src:mbMetaData.image, id:"img_" + toolTipId}, td);
	toolTipIds.push(toolTipId);
	new dijit.Tooltip({
		id: toolTipId,
        connectId: [moviePoster],
        label: '<div class="mbPopout">' + mbMetaData.description + '</div>'
    });
	tr = tt.insertRow(-1);
	td = dojo.create("td", {align:"center"}, tr);
	dojo.create("span", {className:"mbReleaseDate", innerHTML:mbMetaData.release}, td);
	
	tr = tt.insertRow(-1);
	td = dojo.create("td", {className:"mbButtons"}, tr);
	var origMB = dojo.byId(mbMetaData.id);
	var origSaveButton = dojo.query("td.mbButtons span", origMB)[0];
	origSaveButton = dijit.byNode(origSaveButton);
	var newSaveButtonEl = dojo.create("button", {innerHTML:"Save to Queue"}, td);
	
	var buttonClick = new Function("addMovieWrapper('" + mbMetaData.id + "', 10, -50, '" + nfConsumerId + "','disc', 'searchInput', '" + origSaveButton.id + "', 'search');searchPopout.hide();dojo.byId('searchResults').innerHTML = '';");
	var newSaveButton = new dijit.form.Button({
		iconClass:"addMovieIcon",
		onClick:buttonClick
	}, newSaveButtonEl);
	return topDiv;
}

var nextSearchTooltipId = 0;
function getNextSearchTooltipId(){
	return ("nextSearchTooltipId" + (nextSearchTooltipId++));
}

function arrayRemove(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);
}

function showToaster(toastMsg){
	dijit.byId('toasterMsg').setContent(toastMsg, 'fatal', 3000);
    dijit.byId('toasterMsg').show();
}
var POPOUT_CLOSE_DELAY = 900;
function delayPopoutClose(dijitId){
	var theDijit;
	if(typeof this == "undefined" || this == window){
		theDijit = dijit.byId(dijitId);
	}
	else{
		theDijit = this;
	}
	if(theDijit.runningTime < POPOUT_CLOSE_DELAY || theDijit.cancelClose){
		theDijit.runningTime += 100;
		setTimeout("delayPopoutClose('" + theDijit.id + "');", 100);
	}
	else{
		theDijit.finalClose();
		theDijit.runningTime = 0;
		theDijit.cancelClose = false;
	}
}

function cancelPopoutClose(dijitId){
	var theDijit = dijit.byId(dijitId);
	theDijit.cancelClose = true;
}
function resumePopoutClose(dijitId){
	var theDijit = dijit.byId(dijitId);
	theDijit.cancelClose = false;
}

