/*
* Handle flash on home page
*/
tilt.attachEvent(document, "contentreceived", function(){
	var body = document.body;
	var bodyClassName = body.className;

	if (!document.getElementsByTagName || !Array.prototype.push || !document.createAttribute)
	{
		body.className = "Unsupported";
		return;
	}

	var flashContainer = document.getElementById("FrontFlashHolder");
	if (flashContainer) {
		var flashImage = document.getElementById("FrontFlash");
		if (flashImage) {
			flashContainer.appendChild(flashImage);
		}
		
	
	}
	
	flashHandler.process();
	
	/*
	* Configure 'Classify Page' link to display classify in new window
	*/
	var authoringConsole = document.getElementById("authoring");
	if (authoringConsole) {
		var links = authoringConsole.getElementsByTagName("a");
		if (links.length > 0) {
			for (var i = 0; i < links.length; i++) {
				if (links[i].className.indexOf("Popup") >= 0) {
					var href = links[i].getAttribute("href");
					links[i].setAttribute("href", "javascript:void(0)");
					tilt.attachEvent(links[i], "click", function() {
						window.open(href, "ClassifyPage", "width=450,height=650,scrollbars=1");
						return false;
					});
				}
			}
		}
	}
	
	/*
	* Configure the Classify Page 'OK' and 'Cancel' buttons (links)
	* to close popup window
	*/
	var classifyPage = document.getElementById("ClassifyPage");
	if (classifyPage) {
		document.body.className = "ClassifyPage";
		if (window.opener) {
			var divs = classifyPage.getElementsByTagName("div");
			var commands = null;
			for (var i = 0; i < divs.length; i++) {
				if (divs[i].className.indexOf("Commands") >= 0) {
					commands = divs[i];
					break;
				}
			}
			if (commands) {
				var links = commands.getElementsByTagName("a");
				if (links.length > 0) {
					links[0].setAttribute("href", "javascript:void(0)");
					tilt.attachEvent(links[0], "click", function() {
							self.close();
						});
						
				}
				var inputs = commands.getElementsByTagName("input");
				if (inputs.length > 0) {				
					tilt.attachEvent(inputs[0], "click", function() {
						self.close();
						return true;
					});

				}
			}
		}
	}
	
	/*
	var printLink = document.getElementById("PrintLink");
	if (printLink) {
		printLink.setAttribute("href", "javascript:void(0)");
		tilt.attachEvent(printLink, "click", function() {
			window.print();
			return false;
		});
	}
	*/
	
});

/*
* Generic flash handler functionality
*/
window.flashHandler = new function()
{
	var version = 4;
	var useNetscapePlugins = navigator.plugins && navigator.mimeTypes.length;
	
	this.createMovieHtml = function(movie, id, width, height)
	{
		var sizeAttributes = "width=\"" + width + "\" height=\"" + height + "\"";
		return useNetscapePlugins ?
			"<embed type=\"application/x-shockwave-flash\" src=\"" + movie + "\" " + sizeAttributes + "></embed>"
			:
			"<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" " + sizeAttributes + "><param name=\"movie\" value=\"" + movie + "\" /></object>";
	}
	
	this.process = function()
	{
		foreach(map(document.getElementsByTagName("img")), function(img) {
			 var src = img.src;
			 if (src && src.indexOf(".swf") > 0) {
				replaceWithFlash(img);
			 }
		});
	}
	
	function replaceWithFlash(img)
	{
		var width = img.currentStyle ? img.currentStyle.width.replace(/px/, "") : img.width;
		var height = img.currentStyle ? img.currentStyle.height.replace(/px/, "") : img.height;
		var src = img.src;
		if (width && height && src) {
			var movie = src.replace(/\.swf.+/, ".swf");
			var version = 4;
			var useNetscapePlugins = navigator.plugins && navigator.mimeTypes.length;
			if (detectFlash())
			{
				var parent = img.parentNode;
				if (parent.nodeName.toUpperCase() == "A") {
					parent = parent.parentNode;
				}
				parent.innerHTML = createMovieHtml();
			}
			
		}
		
		function createMovieHtml()
		{
			var sizeAttributes = "width=\"" + width + "\" height=\"" + height + "\"";
			return useNetscapePlugins ?
				"<embed type=\"application/x-shockwave-flash\" src=\"" + movie + "\" " + sizeAttributes + "></embed>"
				:
				"<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" " + sizeAttributes + "><param name=\"movie\" value=\"" + movie + "\" /></object>";
		}
	}
	
	function detectFlash()
	{
		return getFlashVersion() >= version;

		function getFlashVersion()
		{
			if (useNetscapePlugins)
			{
				var plugin = navigator.plugins["Shockwave Flash"];
				if(plugin && plugin.description)
				{
					var description = plugin.description;
   					return description.charAt(description.indexOf('.')-1);
				}
			} 
			else
			{
				var version = 0;
				for(var i = 4; i >= 3; i--)
				{
					var testObject;
					try
					{
						testObject = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." +  i);
					}
					catch(e)
					{
						continue;
					}
					return i;
   				}
			}
			return 0;
		}
	}
	
	function filter(col, func) {
		var result = [];
		var length = col.length;
		if (length) {
			if (!func) {
				func = function() {
					return true;
				}
			}
			for(var i = 0; i < length; i++) {
				var item = col[i];
				if (func(item, i, col)) {
					result.push(item);
				}
			}
		}
		return result;
	}
	
	function foreach(col, func) {
		var length = col.length;
		if (length) {
			for(var i = 0; i < length; i++) {
				if (func(col[i], i, col)) {
					return true;
				}
			}
		}
		else {
			var child = col.firstChild;
			while(child) {
				if (child.nodeType == 1 && func(child)) {
					return true;
				}
				child = child.nextSibling;
			}
		}
	}
	
	function map(col, func) {
		var result = [];
		var length = col.length;
		if (length) {
			if (!func) {
				func = function(item) {
					return item;
				}
			}
			for(var i = 0; i < length; i++) {
				result.push(func(col[i], i, col));
			}
		}
		else {
			var child = col.firstChild;
			while(child) {
				if (child.nodeType == 1) {
					result.push(child);
				}
				child = child.nextSibling;
			}
		}
		return result;
	}
}

/*
* Configure the dropdown menus
*/
tilt.attachEvent(document, "contentreceived", function()
{
	var element = document.getElementById("Dropdown");
	if (element)
	{
		element.menuControls = InitializeMenuControls();
		SetLoadingTimer();
	}
	
	function InitializeMenuControls()
	{
		var controls = [];
		var li = element.firstChild;
		var count = 0;
		while(li)
		{
			var pageId = ParsePageId();
			if (pageId)
			{
				if (count > 0)
				{
					controls[count - 1].currentChild = pageId;
				}
				controls[count++] = new MenuControl(li, pageId);
			}
			li = li.nextSibling;
		}
		return controls;
		
		function ParsePageId()
		{
			if (li.firstChild.firstChild)
			{
				var href = li.firstChild.getAttribute("href");
				if (href)
				{
					var queryString = GetQueryString();
					return (queryString.pid ? queryString.pid : null);
				}
			}
			return null;

			function GetQueryString()
			{
				//var list = href.split("?")[1].split("&");
				var list = href.split("?");
				if (list.length > 1) {
					list = list[1].split("&");
				}
				var queryString = new Object();
				if (list) {
					for(var i = 0; i < list.length; i ++)
					{
						var pair = list[i].split("=");
						queryString[pair[0].toLowerCase()] = pair[1];
					}
				}
				return queryString;
			}
		
		}
	}
	
	function SetLoadingTimer()
	{
		setTimeout(LoadMenus, 100);	
	}
	
	function LoadMenus()
	{
		for(var i = 0; i < element.menuControls.length; i++)
		{
			element.menuControls[i].Load();
		}		
		window.status = defaultStatus;
	}
	
	function MenuControl(li, pageId)
	{
		this.li = li;
		this.pageId = pageId;
	}
	
	MenuControl.prototype.Load = function()
	{
		var li = this.li;
		var currentChild = this.currentChild;
		var pageId = this.pageId;
		var doc = null;
		if (document.parentWindow)
		{
			doc = document.parentWindow.document;
		}
		else {
			doc = document;
		}
		li.menu = FindMenu();
		if (li.menu)
		{
			tilt.attachEvent(li, "mouseover", ItemMouseOver);
			tilt.attachEvent(li, "mouseout", ItemMouseOut);
			li.verticalIndent = FindVerticalIndent(li.menu);
		}
		
		function FindMenu()
		{
			var nestedLists = li.getElementsByTagName("ul");
			return nestedLists.length > 0 ? nestedLists[0] : null;
		}
		
		function FindVerticalIndent(list)
		{
			var li = list.firstChild;
			var count = 0;
			while(li)
			{
				var child = li.firstChild;
				if (child && child.tagName != "A")
				{
					return count;
				}
				count++;
				li = li.nextSibling;
			}
			return -1;
		}
		
		function ItemMouseOver(ev, el) {
			//alert("ItemMouseOver:" + li.mouseOut + ", " + el.nodeName + ", " + el.firstChild.getAttribute("href"));
			li.mouseOut = false;
			window.setTimeout(function() {MenuHandler();}, 500);
		}
		
		function ItemMouseOut(ev, el) {
			if (li.mouseOut || (el.nodeName != 'LI')) return;
			//alert(ev);
			var reltg = (ev.relatedTarget) ? ev.relatedTarget : ev.toElement;
			//alert(reltg.nodeName + "," + el.nodeName);
			while (reltg != el && reltg.nodeName != 'BODY')
				reltg = reltg.parentNode
			if (reltg == el) return;

			//alert("ItemMouseOut:" + el.nodeName);
			li.mouseOut = true;
			CloseMenu(li.menu);
			
		}
		
		function MenuHandler()
		{
			if (li.mouseOut) {
				return;
			}
			if (element.currentMenu)
			{
				if (element.currentMenu == li.menu)
				{
					return;
				}
				CloseMenu(element.currentMenu);
			}
			OpenMenu(li.menu);
			if (window.event) {
				window.event.cancelBubble = true;
			}
		}
		
		function OpenMenu(menu)
		{
			with(menu.style)
			{
				//left = (li.offsetLeft+5) + "px";
				left = (GetRealLeft(li)+5) + "px";
				top = GetAdjustedTop(li.verticalIndent) + "px";
			}
			element.currentMenu = li.menu;
			//HideSelects();

			function GetAdjustedTop(verticalIndent)
			{
				var liTop = GetRealTop(li);
				var docScrollTop = doc.documentElement.scrollTop;
				var absoluteTop = (verticalIndent >= 0 ? liTop - 3 - (verticalIndent * 20) : liTop + li.offsetHeight);
				//var absoluteTop = (verticalIndent >= 0 ? liTop - 3 - (verticalIndent * 20) : liTop - (li.menu.offsetHeight / 2) + 8);
				return absoluteTop <= docScrollTop ? docScrollTop + 5 : absoluteTop;
			}
		}
		
		function CloseMenu(menu)
		{
			menu.style.top = "-1000px";
			element.currentMenu = null;
			//ShowSelects();
		}
		
		function HideSelects()
		{
			selects = doc.getElementsByTagName("SELECT");
			for(var i = 0; i < selects.length; i++)
			{
				with(selects[i].style)
				{
					if (visibility == "visible" || visibility == "")
					{
						visibility = "hidden";
					}
				}
				selects[i].IHidIt = true;
			}
		}
		
		function ShowSelects()
		{
			selects = doc.getElementsByTagName("SELECT");
			for(var i = 0; i < selects.length; i++)
			{
				if (selects[i].IHidIt)
				{
					selects[i].style.visibility = "visible";
				}
			}
		}
		
		function Body__OnClick()
		{
			CloseMenu(li.menu);
		}
	}
});

/*
* Configure the dropdown select on the home page
*/
tilt.attachEvent(document, "contentreceived", function ()
{
	var quickLinks = document.getElementById("quickLinks");
	var selectTag = quickLinks.getElementsByTagName("select");
	if (selectTag.length == 0) return;
	tilt.attachEvent(selectTag[0], "change", function()
	{
		if (selectTag[0].selectedIndex > 0) {
			var host = location.protocol + "//" + location.host;
			var newHref = selectTag[0].options[selectTag[0].selectedIndex].value;
			selectTag[0].selectedIndex = 0;
			regxStr = new RegExp("(^(?!http)|^" + host + "|^javascript)|.*estrada3.dll.*");
			if (!regxStr.test(newHref)) {
				window.open(newHref,"","");
			}
			else {
				location.href = newHref;
			}
			//location.href = selectTag[0].options[selectTag[0].selectedIndex].value;
		}
	});
});

/*
* Configure links (anchors) to external links to open in new window
*/
tilt.attachEvent(document, "contentreceived", function()
{
	window.status = "Making external links open in new window...";
	var anchors = document.getElementsByTagName("A");
	var host = location.protocol + "//" + location.host;
	var href;
	for(var i = 0; i < anchors.length; i ++)
	{
		href = anchors[i].getAttribute("href");
		regxStr = new RegExp("(^(?!http)|^" + host + "|^javascript)|.*estrada3.dll.*");
		if (!regxStr.test(href)) {
			anchors[i].setAttribute("target", "_blank");
		}
	}
	window.status = window.defaultStatus;
});

/*
* Configure search result links to add query=<search text> to the query string.  This
* will drive the search highlighting on the results pages.
* First, need to get the query search text from the search box.  Then add the query string
* to each result link.
*/
tilt.attachEvent(document, "contentreceived", function() {
	var query = "";
	var divList = document.getElementsByTagName("div");
	for (var j = 0; j < divList.length; j++) {
		if (divList[j].className == "Search") {		
			var inputs = divList[j].getElementsByTagName("input");
			if (inputs[0].value.length > 0) {
				query = inputs[0].value;
			}
			break;
		}
	}
	if (query.length > 0) {
		var match = new RegExp('');
		match.compile('"(.+)"');
		var results = match.exec(query);
		if (results) {
			results.shift();
		}
		else {
			results = query.split(/\s/);
		}
		if (results) {
			query = results.join(",");
			/*
			for (var i = idx; i < results.length; i++) {
				alert(i + ":" + results[i]);
			}
			*/
		}
		var result = null;
		var ulList = document.getElementsByTagName("ul");
		for (var j = 0; j < ulList.length; j++) {
			if (ulList[j].className == "Result") {
				result = ulList[j];
				break;
			}
		}
		if (result) {
			var liList = result.getElementsByTagName("li");
			for (var j = 0; j < liList.length; j++) {
				if (liList[j].className == "Page") {
					var link = liList[j].childNodes[1].firstChild;
					if (link && link.href) {
						link.href += "&query=" + encodeURIComponent(query)
					}
				}
			}
		}
		return;
	}
});

/*
* Highlighting functionality for finding and highlighting the text on the search
* results pages.
*/
Hilite = {
    /**
     * Element ID to be highlighted. If set, then only content inside this DOM
     * element will be highlighted, otherwise everything inside document.body
     * will be searched.
     */
    elementid: 'content',
    
    /**
     * Whether we are matching an exact word. For example, searching for
     * "highlight" will only match "highlight" but not "highlighting" if exact
     * is set to true.
     */
    exact: false,

    /**
     * Maximum number of DOM nodes to test, before handing the control back to
     * the GUI thread. This prevents locking up the UI when parsing and
     * replacing inside a large document.
     */
    max_nodes: 1000,

    /**
     * Whether to automatically hilite a section of the HTML document, by
     * binding the "Hilite.hilite()" to window.onload() event. If this
     * attribute is set to false, you can still manually trigger the hilite by
     * calling Hilite.hilite() in Javascript after document has been fully
     * loaded.
     */
    onload: true,

    /**
     * Name of the style to be used. Default to 'hilite'.
     */
    style_name: 'hilite',
    
    /**
     * Whether to use different style names for different search keywords by
     * appending a number starting from 1, i.e. hilite1, hilite2, etc.
     */
    style_name_suffix: true,

    /**
     * Set it to override the document.referrer string. Used for debugging
     * only.
     */
    debug_referrer: ''
};

Hilite.search_engines = [
    ['^http://(www)?\\.?google.*', 'q='],              // Google
    ['^http://search\\.yahoo.*', 'p='],                // Yahoo
    ['^http://search\\.msn.*', 'q='],                  // MSN
    ['^http://search\\.aol.*', 'userQuery='],          // AOL
    ['^http://(www\\.)?altavista.*', 'q='],            // AltaVista
    ['^http://(www\\.)?feedster.*', 'q='],             // Feedster
    ['^http://search\\.lycos.*', 'query='],            // Lycos
    ['^http://(www\\.)?alltheweb.*', 'q=']             // AllTheWeb
];

/**
 * Decode the referrer string and return a list of search keywords.
 */
Hilite.decodeReferrer = function(referrer) {
    var query = null;
    var match = new RegExp('');

    for (var i = 0; i < Hilite.search_engines.length; i ++) {
        match.compile(Hilite.search_engines[i][0], 'i');
        if (referrer.match(match)) {
            match.compile('^.*'+Hilite.search_engines[i][1]+'([^&]+)&?.*$');
            query = referrer.replace(match, '$1');
            if (query) {
                query = decodeURIComponent(query);
                query = query.replace(/\'|"/, '');
                query = query.split(/[\s,\+\.]+/);
                return query;
            }
        }
    }
    return null;
};

Hilite.getQuery = function() {
	var match = new RegExp('');
	match.compile('^.*query=([^&]+)&?.*$');
	var query = location.search.replace(match, '$1');
	if (query) {
        query = decodeURIComponent(query);
        query = query.replace(/\'|"/g, '');
        query = query.split(",");
        /*
        for (var i = 0; i < query.length; i++) {
			query[i] = decodeURIComponent(query[i]).replace(/\'|"/g, '');
        }
        */
        return query;
    }
    return null;
}

/**
 * Highlight a DOM element with a list of keywords.
 */
Hilite.hiliteElement = function(elm, query) {
	//alert("[" + elm.childNodes.length + "] [" + query + "]");
    if (!query || elm.childNodes.length == 0)
	return;

    var qre = new Array();
    for (var i = 0; i < query.length; i ++) {
        query[i] = query[i].toLowerCase();
        if (Hilite.exact)
            qre.push('\\b'+query[i]+'\\b');
        else
            qre.push(query[i]);
    }

    qre = new RegExp(qre.join("|"), "i");
    var stylemapper = {};
    for (var i = 0; i < query.length; i ++)
        stylemapper[query[i]] = Hilite.style_name+(i+1);

    var textproc = function(node, data) {
        var match = qre.exec(data);
        if (match) {
            var val = match[0];
            var k = '';
            var node2 = node.splitText(match.index);
            var node3 = node2.splitText(val.length);
            var span = node.ownerDocument.createElement('SPAN');
            node.parentNode.replaceChild(span, node2);
            span.className = stylemapper[val.toLowerCase()];
            span.appendChild(node2);
            return span;
        } else {
            return node;
        }
    };
    
    Hilite.walkElements(elm.childNodes[0], 1, textproc);
};

/*
 *
 */
Hilite.hilite = function() {
    var e = null;
	var  q = Hilite.getQuery();
    if (q && ((Hilite.elementid && 
               (e = document.getElementById(Hilite.elementid))) || 
              (e = document.body)))
    {
	Hilite.hiliteElement(e, q);
    }
};

Hilite.walkElements = function(node, depth, textproc) {
    var skipre = /^(script|style|textarea)/i;
    var count = 0;
    while (node && depth > 0) {
        count ++;
        if (count >= Hilite.max_nodes) {
            var handler = function() {
                Hilite.walkElements(node, depth, textproc);
            };
            setTimeout(handler, 50);
            return;
        }

        if (node.nodeType == 1) { // ELEMENT_NODE
            if (!skipre.test(node.tagName) && node.childNodes.length > 0) {
                node = node.childNodes[0];
                depth ++;
                continue;
            }
        } else if (node.nodeType == 3) { // TEXT_NODE
            node = textproc(node, node.data);
        }

        if (node.nextSibling) {
            node = node.nextSibling;
        } else {
            while (depth > 0) {
                node = node.parentNode;
                depth --;
                if (node.nextSibling) {
                    node = node.nextSibling;
                    break;
                }
            }
        }
    }
};

/*
* Wire up the search text highlighting
*/
tilt.attachEvent(document, "contentreceived", function() {
	Hilite.hilite();
	/*
	wait(30000, 100);

	function wait(timeout, delta) {
		var interval = window.setInterval(function() {
			if (PopoutProcessed || (timeout < 0)) {
				Hilite.hilite();
				window.clearInterval(interval);
			}
			timeout -= delta;
			
		}, delta);
	}
	*/
});
