﻿$(function() {

	//////////////////////////////////////////////////////////////////////////////////
	//  								Main Menu									//
	//////////////////////////////////////////////////////////////////////////////////

	var searchInputText = $("#searchinput").val();
	var originalSelectedItem = $("#t_main_menu li.selected");

	// Hover over main categories: show/hide children
	$("#t_main_menu a[href^=#]").hover(function(e) {
		var cur = $(this).attr("href");
		if (cur != "/") {
			// get the relevant submenu's UL
			var ul = $("#t_main_menu_sub ul").hide().filter(cur).show();

			// calculate the submenu's width
			var submenu_w = 0; ul.find("li").each(function(i, o) { submenu_w += $(o).outerWidth(); });

			// calculate the total submenu container width
			var container_w = ul.width();

			// the calculations and logic below is applicable only to RTL reading. When implementing LTR, this logic should be extended/rewritten
			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

			// calculate position of the main category
			var right = $(this).position().left + $(this).width() - /* left margin of the body: */$(this).closest("div").position().left;

			if (right < submenu_w) {
				ul.css("margin-right", 0);
				ul.css("float", "left");
			}
			else {
				if (container_w - right > 1) // due to a CSS or jQuery bug, that causes hovering over the padding between the main category LIs to produce false container_w, that causes the submenu to "jump"
					ul.css("margin-right", container_w - right);
				ul.css("float", "");
			}

			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		}
		$(this).parents("ul").find("li").removeClass("selected").end().end().parent().addClass("selected");

		//$("#stat").html("nodeName: " + $(this)[0].nodeName + "<br />clientX: " + e.clientX + "<br />offsetX: " + e.offsetX + "<br />submenu_w: " + submenu_w + "<br />container_w: " + container_w + "<br />right: " + right); //.position().left);
		return false;
	});

	originalSelectedItem.find("a").hover();
	$("#t_main_menu_sub").show(); // the submenu will be shown in the correct position now. Flickering was prevented by setting display:none to '#t_main_menu_sub ul' CSS

	// First item (go to homepage link)
	//$("#t_main_menu a[href^=/]:not(:last)").hover(function() {
	$("#t_main_menu a[href^=/]").hover(function() {
		$("#t_main_menu_sub ul").hide();
		$(this).parents("ul").find("li").removeClass("selected").end().end().parent().addClass("selected");
	});

	// Click on main category - go to the first child's link
	$("#t_main_menu a[href^=#]").click(function() {
		var cur = $(this).attr("href");
		//var link = $("#t_main_menu_sub ul").hide().filter(cur).attr("href");
		var link = $("#t_main_menu_sub ul").hide().filter(cur).find("a").attr("href");
		location.href = link;
	});

	$("#t_main_menu_wrapper").mouseleave(function() {
		if (originalSelectedItem.length > 0) {
			originalSelectedItem.parents("ul").find("li").removeClass("selected");
			originalSelectedItem.addClass("selected");
			var cur = originalSelectedItem.find("a").attr("href");
			if (cur.substring(0, 1) == "#")
				$("#t_main_menu_sub ul").hide().filter(cur).show();
			else
				$("#t_main_menu_sub ul").hide();
		}
	});

	$("#searchinput")
		.focus(function() {
			if (this.value == searchInputText) { this.value = ''; }
		})
		.blur(function() {
			if (this.value == '') { this.value = searchInputText; }
		})

	$("#t_main_menu form")
		.submit(function() {
			alert('The search function is not active yet');
			return false;
		});


	//////////////////////////////////////////////////////////////////////////////////
	//  								Vertical Menu								//
	//////////////////////////////////////////////////////////////////////////////////
	subItems = $("#t_main_menu_sub ul:not(:hidden) li");
	if (subItems.length > 0)
		$("#t_v_menu div").append(subItems.clone());
	else
		$("#t_v_menu").hide();



	//////////////////////////////////////////////////////////////////////////////////
	//  								Utility Menu								//
	//////////////////////////////////////////////////////////////////////////////////

	if (typeof readCookie == 'function') {
		var tab = readCookie("tab");
		if (tab != undefined) {
			toggleTab($("a[href=" + tab + "]"));
		}
		else
			toggleTab($("#t_utility_menu a[href=#tabs-1]"));
	}


	$("#t_utility_menu a[href^=#]").click(function() {
		toggleTab(this);
		return false; // we virtually cancel the click event, because we don't want it to change the URL in the browser
	});

	function toggleTab(anchor) {
		var cur = $(anchor).attr("href");
		createCookie("tab", cur);
		$("#t_utility_menu_wrapper > div").filter(":not(:first)").hide().filter(cur).show();
		$(anchor).parents("ul").find("li").removeClass("selected").end().end().parent().addClass("selected");
	}


	//////////////////////////////////////////////////////////////////////////////////
	//  							Search textbox: Operation						//
	//////////////////////////////////////////////////////////////////////////////////

	var mainSearchBox = $('#searchinput'); // define now to avoid more than 1 search on document

	mainSearchBox.keyup(function(e) {
		if (e.keyCode === 13) {
			goToSearch();
		}
	});

	mainSearchBox.keyup(function() {
		showSearchBox();
	});

	$('#MainSearchBtn').click(function() {
		goToSearch();
	});

	$(document).click(function(event) {
		if (event.target.id !== 'MainSearchBox') {
			hideBox($('#SearchResultBox'));
		}
	});

	$('#SearchResultBox').mouseleave(function(event) {
		if (event.target.id !== 'MainSearchBox' && event.target.id !== 'SearchResultBox') {
			hideBox($('#SearchResultBox'));
		}
	});

	$(document.body).focus();
});

















//////////////////////////////////////////////////////////////////////////////////
//  							Search textbox: Functions						//
//////////////////////////////////////////////////////////////////////////////////

//Important: the AJAX result of the search box must be HTMLEncoded for 3 symbols: " , < and >.
//All other symbols are allowed. just use &gt; and &lt; and &quot; for these three illegal characters in the JSON result.

var isWaiting = false;
var searchTimer;
var lastSearch = '';
var lastResult = '';

function hideBox(elm) {
	//jQuery bug 1: on IE first right-click (context menu) will not close the box but only the second time. 
	//				I looked into JQuery code, and found the problem. on line 255 you need to chage the order of the elements !! 
	//				I can easly fix it, but if we use this fix we can't use Google to host the JS file, so we loss the advantage of Google hosting JQuery.js...
	//jQuery bug 2: on IE after the slideUp finished sometimes there is flickering. the whole box appears again for a millisec and disappeared. 
	//				I looked into JQuery code, and found the problem. on line 297 and 315 they started from 0 instead of 1 !! 
	//				In both lines you can write "this.prop == "width" || this.prop == "height" ? 1 : 0" instead of "0" and it will solved the bug!
	//				I can easly fix it, but if we use this fix we can't use Google to host the JS file, so we loss the advantage of Google hosting JQuery.js...

	if (elm.is(':visible')) {
		elm.slideUp('fast');
	}
}

function setSearchBoxLocation() {
	//jQuery bug 3: on FireFox the movement of the box on window resize is slow. IE is OK.
	//jQuery bug 5: on FireFox version 2.0 with screen resulution over 1024, the location is incorrect!! the position.left is much lower than what is should be.

	var searchBoxResult = $('#SearchResultBox');
	var mainSearchBox = $('#searchinput');
	var position = mainSearchBox.offset();

	if (isHebrewDocument())
		searchBoxResult.css({ top: position.top + mainSearchBox.outerHeight(), width: 270, left: position.left + mainSearchBox.width() - 270 });
	else
		searchBoxResult.css({ top: position.top + mainSearchBox.outerHeight(), left: position.left - 3, width: 270 });
}

function getTalentIcon(talents, color) {
	return "i";
}

function goToSearch() {
	location.href = 'Search.aspx?text=' + encodeURIComponent($('#searchinput').val());
}

function printSearchResult(html) {
	var searchBoxResult = $('#SearchResultBox');

	searchBoxResult.html(html);
	$('#SearchResultBox TR')
		.mouseover(function() {
			$(this).css('background-color', '#FCF5E2');
		})
		.mouseout(function() {
			$(this).css('background-color', '');
		});
	lastResult = html;

	isWaiting = false;
}

function pharseSearchResult(searchResults) {
	var searchBoxResult = $('#SearchResultBox');
	//var arrJson = JSON.parse(json);
	var html = '<table>';

	for (var i = 0; i < searchResults.length; i++) {
		html += '<tr onclick="location.href=\'' + searchResults[i].Link + '\'">';

		//html += '<td class="SearchBoxTD"><img width="46" height="60" src="images/Thumb/' + searchResults[i].Picture + '" /></td>';

		html += '<td><div class="caption">' + searchResults[i].Caption + '</div>';
		if (searchResults[i].Subheading!=null)
			html += '<div>' + searchResults[i].Subheading + '</div>';
		html += '</td>';

		html += '<td align="right">';
		var d = Date(searchResults[i].Date);
		html += '<div class="small">' + d + '</div>';
		html += '</td>';


		html += '</tr>';
	}
	html += '</table>';

	var moreResults = isHebrewDocument() ? "עוד תוצאות" : "More Results";
	var moreResultsIcon = "/Images/moreResultsIcon" + (isHebrewDocument() ? "He" : "") + ".gif";
	
	html += '<div onclick="goToSearch()" class="MoreResults">' + moreResults + ' <img src="' + moreResultsIcon + '" width="15" height="15" align="absmiddle"></div>';

	printSearchResult(html);
	lastResult = html;
	lastSearch = $('#searchinput').val();
}

function makeSearch() {
	var thisSearch = $('#searchinput').val();
	var searchBoxResult = $('#SearchResultBox');

	if (thisSearch !== lastSearch) {
		lastSearch = thisSearch;
		var o = { input: thisSearch };
		$.service("Search", o, function(result) { pharseSearchResult(result) }, function(xhr, textStatus, errorThrown) { searchBoxResult.html('Error'); /* TODO: handle error */ });
	}
	else {
		printSearchResult(lastResult);
	}
}

function showSearchBox() {
	var searchBoxResult = $('#SearchResultBox');
	var thisSearch = $('#searchinput').val();
	var waitHtml = '<div id="WaitDiv"><img src="/Images/ajax-loader.gif" id="Wait" width="32" height="32"><br />Searching...</div>';

	clearTimeout(searchTimer);

	if (lastSearch !== thisSearch && !isWaiting) {
		searchBoxResult.html(waitHtml);
		isWaiting = true;
	}

	if (searchBoxResult.is(':hidden')) {
		setSearchBoxLocation();
		searchBoxResult.slideDown('fast');
	}

	searchTimer = setTimeout(makeSearch, 1000);
}

$(window).resize(function() {
	if ($('#SearchResultBox').is(':visible')) {
		setSearchBoxLocation();
	}
});


//////////////////////////////////////////////////////////////////////////////////
//		  							Misc functions								//
//////////////////////////////////////////////////////////////////////////////////

function isHebrewDocument() {
	return $(document.body).css("direction") == "rtl";
}
