var highlight;
var elementMenuButton;
var elementHighlightMenuOptions;
var menuId;
var menuTotalColors = 6;
var menuCurrentColor=null;

var mapCategoryOrder = new Array();
mapCategoryOrder["tivo:ca.413902"] = 0;
mapCategoryOrder["tivo:ca.413905"] = 1;
mapCategoryOrder["tivo:ca.413907"] = 2;
mapCategoryOrder["tivo:ca.10916167"] = 3;
mapCategoryOrder["tivo:ca.413898"] = 4;
mapCategoryOrder["tivo:ca.413899"] = 5;
mapCategoryOrder["tivo:ca.413900"] = 6;
mapCategoryOrder["tivo:ca.413901"] = 7;
mapCategoryOrder["tivo:ca.413908"] = 8;
mapCategoryOrder["tivo:ca.413896"] = 9;
mapCategoryOrder["tivo:ca.413909"] = 10;
mapCategoryOrder["tivo:ca.413903"] = 11;
mapCategoryOrder["tivo:ca.413910"] = 12;
mapCategoryOrder["tivo:ca.413904"] = 13;
mapCategoryOrder["tivo:ca.413906"] = 14;
mapCategoryOrder["tivo:ca.413897"] = 15;


function toggleMenu(obj, id, isMore)
{
	elementMenuButton = $(obj);
	elementHighlightMenuOptions = $("highlightMenuOptions");
	if (hldebug__) 
		Log.write("Selected Menu: " + id);

	hideMenu();

	menuId = id;
	repositionMenu();
	fillMenu();
	showMenu();
	updateHighlightForm(isMore);
	if (hldebug__)
		Log.write("Menu is displayed...");
	return false;	
}

function updateHighlightForm(isMore) {
	if(isMore != null) {
		
		var highlightForm = $("highlightForm");	
		highlightForm.isMore = "Y";
	}
}

function fillMenu()
{
	if(menuId)
		highlight = GetHighlight(menuId);
	
	elementHighlightMenuOptions.innerHTML = renderMenu();
	//alert(elementHighlightMenuOptions.innerHTML );
	if (hldebug__ && htmldebug__) 
		Log.write("Rendered the Menu html: " + elementHighlightMenuOptions.innerHTML);
	setColorSelected(menuCurrentColor);
}


function processHighlighForm()
{
	var highlightForm = $("highlightForm");

	var parent = highlightForm.highlightId.value;
	var color = highlightForm.highlightColor.value;
	var children = new Array();

	for(var i=0;i<highlightForm.highlightCategory.length;i++)
	{
		if(highlightForm.highlightCategory[i].checked)
		{
			children[children.length] = highlightForm.highlightCategory[i].value;
		}
	}
	if (hldebug__)  {
	    var temp = "parent: " + parent + "\ncolor: " + color + "\n\nchildren:\n";

		for(var i=0;i<highlightForm.highlightCategory.length;i++)
		{
			if(highlightForm.highlightCategory[i].checked)
			{
				temp += highlightForm.highlightCategory[i].value + "\n";
			}
		}
		Log.write("Highlight Menu selections: \n" + temp);
	}

	
	hideMenu();
	
	$(parent).className=arrcolor[color][2];
	
	handleHighlightForm(parent, children, color, highlightForm.isMore);
}


function updateMenuWithColors() {
	var selections = getCookiedSelections();
	var selection = null;
	for(var i=0; i<selections.length; i++) {
		selection = selections[i];
		if(selection != null) {
		    	if(hldebug__) 
				Log.write("Selection in update: " + selection.parent);
			var menuItem = $(selection.parent);
			if(menuItem!=null && selection.isEnabled) {
				menuItem.className=arrcolor[selection.color][2];
			}
		}
	}
}

function updateMenuWithColorsInMore() {
	var selections = getCookiedSelections();
	var selection = null;
	for(var i=0; i<selections.length; i++) {
		selection = selections[i];
		if(selection != null) {
		    	if(hldebug__) 
				Log.write("Selection in update: " + selection.parent);
			var menuItem = $(selection.parent);
			if(menuItem!=null && selection.isEnabled) {
				menuItem.className=arrcolor[selection.color][2];
				var checkbox = $("c"+selection.parent);
				if(checkbox != null) {
					checkbox.checked = true;
				}
			}
		}
	}
}



function handleHighlightOnClick(parent, color) {
	var deselections = new Array();
	//populateCategory();
	
	var order = mapCategoryOrder[parent];
	var selections = getCookiedSelections();
	var sel = selections[order] ;

	if(sel != null) {
		sel.isEnabled = !(sel.isEnabled);
	}
	else {
		sel = new Highlight(parent, new Array(), color); // default blue color
		selections[order] = sel;
		//alert("New Highlight : " + sel  );

	}
	
	if(sel.isEnabled ) {
		//$(parent).className=arrcolor[sel.color][2]; // highlight menu
		highlightCells(selections);
	}
	else {
		//$(parent).className=arrcolor[0][2];
		deselections[0] = new Highlight(parent, sel.children, 0);
		highlightCells(deselections);	
		highlightCells(selections);
	}
	//alert("Before write cookie: " + selections);
	writeCookie(selections);
}




/**
*
* Saves the items selected in the Highlight form
*/
function handleHighlightForm(parent, arrchild, color, isMore) {
	
	if(isMore == "Y") {
		handleHighlightFormInMore(parent, arrchild, color);	
	}
	else {
		handleHighlightFormInTvListings(parent, arrchild, color);
	}
}

// no need to save in the cookie. it's saved for the whole page.
function handleHighlightFormInMore(parent, arrchild, color) {
	
	var order = mapCategoryOrder[parent];
	var selections = getCookiedSelections();
	var sel = selections[order] ;
	var hl = new Highlight(parent, arrchild, color);
	if(hl.color != 0) {
		selections[order] = hl;
	}
	var checkbox = $("c"+parent);
	if(checkbox != null) {
		checkbox.checked = true;
	}
	
}

// no need to save in cookie
function handleHighlightOnClickInMore(parent) {
	var order = mapCategoryOrder[parent];
	var color = 0;
	var selections = getCookiedSelections();
	var sel = selections[order] ;

	if(sel != null) {
		sel.isEnabled = !(sel.isEnabled);
	}
	else {
		sel = new Highlight(parent, new Array(), 1); // default blue color
		selections[order] = sel;
	}
	
	if(sel.isEnabled ) {
		
		$(parent).className=arrcolor[sel.color][2]; // highlight menu
	}
	else {
		$(parent).className=arrcolor[0][2];
	}
}

function submitMoreForm() {
	writeCookie(getCookiedSelections());
	$("tvlistings_form").submit(); 
	return true;
	
}


function handleHighlightFormInTvListings(parent, arrchild, color) {

	// 1. update the cookie value in the memory 
	// 2. highlight the cells.
	// 3. store the value in cookie
	var deselections = new Array();
	var hl = new Highlight(parent, arrchild, color);
	var order = mapCategoryOrder[parent];
	var selections = getCookiedSelections();
	
	var sel = selections[order] ;
	if(hl.children.length == allHighlights[order].children.length) {
		hl.children = new Array();		
	}			
	
	if(hl.color != 0) {
		selections[order] = hl;
	}
	else {
		// needs to be revisited to make combine with the selections.
		// this logic makes the fetching of cells and iterating thru them twice
		// one for the un checked highlights and other for selected highlights.
		// need to improve the performance.
		if (hldebug__)  
			Log.write("Menu is de selected: " + hl.parent);
		hl.color = 0;
		hl.children = new Array();
		deselections[0] = hl;
		selections[order] = null;
		highlightCells(deselections);	
	}
	if(sel != null && (sel.children.length != hl.children)) {
		var ch = new Array();
		var dhl = new Highlight(parent, ch, 0);
		deselections[0] = dhl;
		highlightCells(deselections);	
	}
	highlightCells(selections);
	writeCookie(selections);
	
	if(hldebug__)
		Log.write("Kuki selections: " + selections);
	
}



function showMenu()
{
	elementHighlightMenuOptions.style.display='block';
}

function hideMenu()
{
	menuCurrentColor=null;
	menuId=null;
	elementHighlightMenuOptions.style.display='none';
	
}


function repositionMenu()
{
	if(elementMenuButton != null) {
		var elementY = findPosY(elementMenuButton);
		var elementX = findPosX(elementMenuButton);
		var elementHeight = elementMenuButton.offsetHeight;
		var elementHighlightMenuOptionsHeight = elementHighlightMenuOptions.offsetHeight;
	
		elementHighlightMenuOptions.style.left = elementX + "px"
		elementHighlightMenuOptions.style.top = (elementY + elementHeight + 2) + "px"
	}
}

function GetHighlight(highlightId)
{
	if(mapCategoryOrder[highlightId] >= 0 )
		return allHighlights[ mapCategoryOrder[highlightId] ];
	else
		return null;
}


function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function setColorSelected(color)
{
	for(var i=0;i<menuTotalColors;i++)
	{
		$("filter" + i).className = null;
	}
	if(hldebug__) {
		Log.write("Color selected " + color);
		Log.write("Element of Color selected " + $("filter" + color));
	}
	$("filter" + color).className = "selected"; // select color in the drop down menu
	$("highlightColor").value = color;  //update hidden form val.
}


function renderMenu()
{
	var highlightName = highlight.parent.name;
	var highlightId = highlight.parent.id;
	var highlightColor = highlight.color;

	var order = mapCategoryOrder[highlightId];
	var ch = null;
	var color = 1;
	var kukiHls = getCookiedSelections();
	var selection = kukiHls[order];
	if (hldebug__)  {
	
		Log.write("Cookie value : "  + kukiHls);
		Log.write("Order of Highlight : "  + order);
		Log.write("Selected Item in Cookie: "  + selection);
	}
	var selectAllChildren = true;
	
	if(selection != null) {
		color = selection.color;
		if ( selection.children.length > 0 ) {
			selectAllChildren = false;
		}
	}

	var menuHtml = "<div class=\"dropdown\">\n";
	menuHtml += "	<form id=\"highlightForm\" class=\"categoryForm\" action=\"#\">\n";
	menuHtml += "	<img id=\"closeBtn\" src=\"/tivo-tco/i/4.0/tco.gridGuide.closeX.gif\" value=\"X\" onclick=\"hideMenu();\">\n";
	menuHtml += "	<h4>Show <em>" + highlightName + "</em> in color:</h4>\n";
	menuHtml += "		<table cellpadding=\"0\" cellspacing=\"0\" class=\"filter\">\n";
	menuHtml += "			<tr valign=top>\n";
	menuHtml += "				<td id=\"filter0\"><input src=\"i/4.0/filters/tco.gridGuide.filter0.gif\" onclick=\"setColorSelected('0');return false;\" type=\"image\"><br/>none</td>\n";
	menuHtml += "				<td id=\"filter1\"><input src=\"i/4.0/filters/tco.gridGuide.filter2.gif\" onclick=\"setColorSelected('1');return false;\" type=\"image\"></td>\n";
	menuHtml += "				<td id=\"filter2\"><input src=\"i/4.0/filters/tco.gridGuide.filter5.gif\" onclick=\"setColorSelected('2');return false;\" type=\"image\"></td>\n";
	menuHtml += "				<td id=\"filter3\"><input src=\"i/4.0/filters/tco.gridGuide.filter1.gif\" onclick=\"setColorSelected('3');return false;\" type=\"image\"></td>\n";
	menuHtml += "				<td id=\"filter4\"><input src=\"i/4.0/filters/tco.gridGuide.filter3.gif\" onclick=\"setColorSelected('4');return false;\" type=\"image\"></td>\n";
	menuHtml += "				<td id=\"filter5\"><input src=\"i/4.0/filters/tco.gridGuide.filter4.gif\" onclick=\"setColorSelected('5');return false;\" type=\"image\"></td>\n";
	menuHtml += "			</tr>\n";
	menuHtml += "		</table>\n";
	menuHtml += "		<hr>\n";
	menuHtml += "			<input type=\"hidden\" id=\"highlightId\" name=\"highlightId\" value=\"" + highlightId + "\" />\n";
	menuHtml += "			<input type=\"hidden\" id=\"highlightColor\" name=\"highlightColor\" value=\"" + highlightColor + "\" />\n";
	menuHtml += "			<input type=\"hidden\" id=\"inMore\" name=\"inMore\" value=\"N\" />\n";
	menuHtml += "			<fieldset>\n";  
	menuHtml += "				<legend>Which types of " + highlightName + "?</legend>\n";
	menuHtml += "				<dl>\n";


	
	if(selectAllChildren) {
		if (hldebug__)
			Log.write("all sub categories selected");
		for(var i=0;i<highlight.children.length;i++)
		{
			var child = highlight.children[i];
			menuHtml += renderSubcategory (child, true);
		}
	}
	else {
		var selChildren = selection.childrenToString();
		if (hldebug__)
			Log.write("Few  sub categories selected: " + selChildren);
		for(var i=0; i<highlight.children.length; i++) {
			var child = highlight.children[i];
			var matched = selChildren.match(child.id);
			if(matched) {
				menuHtml += renderSubcategory (child, true);
			}
			else {
				menuHtml += renderSubcategory (child, false);
			}
		}
	}
	menuHtml += "				</dl>\n";
	menuHtml += "			</fieldset>\n";
	
	menuHtml += "			<img src=\"/tivo-tco/i/4.0/tco.highlightMenu.saveBtn.gif\" value=\"Save\" onclick=\"processHighlighForm();\">\n";
	
	menuHtml += "		</form>";
	menuHtml += "	</div>";
	
	menuCurrentColor = color;
	return menuHtml;

}

function renderSubcategory (child, selected) {
	var html =  "					<dt>\n";
		html += "						<label for=\"highlightCategory\">" + child.name + "</label>\n";
		html += "					</dt>\n";
		html += "					<dd>\n";
		if(selected) {
			html += "						<input name=\"highlightCategory\" type=\"checkbox\" checked value=\"" + child.id + "\">\n";
		}
		else {
			html += "						<input name=\"highlightCategory\" type=\"checkbox\" value=\"" + child.id + "\">\n";
		}
		html += "					</dd>\n";
		
	return html;
}


function fetchMoreHighlights() {
	if(gridDisplay != null) {
		var form = $("tvlistings_form");
		//form.offset = gridDisplay.offset;
		//var tmp = (gridDisplay.startTime/1000)
		//form.requested_showing_start = tmp;

		form.submit();
	}
}
