/*
    Lookup Control
*/
ninemsn.AP.Util.LookupControl = function(elCont, strHelpText, fncSearch, fncCancel, fncSelect, lWidth)
{
    var me = this;
    
    me.elContainer = elCont;
    me.divCont = null;
    me.divList = null;
    me.img = null;
    me.ef = null;
    me.strHelp = strHelpText;
    me.idTimer = null;
    me.idCloseTimer = null;
    me.aHits = null;
    me.state = "init";
    me.lTimeout = 500;
    me.strFocus = null;
    me.strSearch = null;
    me.fncS = fncSearch;
    me.fncC = fncCancel;
    me.fncSel = fncSelect;
    me.lWidth = lWidth;
    me.strBorderColor = "#6593cf";
    
    this.setEnabled = function(fEnable)
    {
        me.ef.disabled = !fEnable;
        me.img.style.display = fEnable ? "block" : "none";
        me.divCont.style.borderColor = fEnable ? me.strBorderColor : "#ccc";
    };
    
    this.setTip = function(strTip)
    {
        me.ef.title = strTip;
    };
    
    this.setHits = function(aHits)
    {
        me.aHits = aHits;
        me.state = "gothits";
        process();
    };
    
    this.getContainer = function()
    {
        return me.divCont;
    };
    
    this.hideLookup = function()
    {
        me.state = "clear";
        process();
    };
    
    function process()
    {
        var fContinue = false;
        
        do
        {
            switch(me.state)
            {
                case "init":
                    me.divCont = me.elContainer.appendChild(document.createElement("div"));
                    me.divCont.className = "lookup_container";
                    me.divCont.style.width = me.lWidth + "px";
                    
                    me.img = me.divCont.appendChild(document.createElement("img"));
                    utl.attachEvent(me.img, "onclick", handleClick);
                    
                    me.ef = document.createElement("input");
                    me.ef.type = "text";
                    me.ef.style.width = (me.lWidth - 31) + "px";
                    utl.attachEvent(me.ef, "onmousedown", function() { me.strFocus = "input"; } );
                    utl.attachEvent(me.ef, "onfocus", handleFocus);
                    utl.attachEvent(me.ef, "onblur", handleInputBlur);
                    utl.attachEvent(me.ef, "onkeyup", handleKeyup);
                    me.divCont.appendChild(me.ef);
                    
                    me.state = "clear";
                    
                    fContinue = true;
                    break;
                    
                case "clear":
                    me.img.src = "img/lookup_idle.gif";
                    me.img.className = "imageIdle";
                    me.ef.value = me.strHelp;
                    me.ef.style.color = "#acacac";
                    try { me.ef.blur(); } catch(ex) {}
                    stopTimer();
                    stopCloseTimer();
                    hideList();
                    if (me.fncC)
                        me.fncC();
                    
                    fContinue = false;
                    break;
                    
                case "typestart":
                    me.ef.value = "";
                    me.ef.style.color = "#000";
                    
                    if (!me.idCloseTimer)
                        me.idCloseTimer = setInterval(handleCloseTimer, 1000);
                    
                    fContinue = false;
                    break;
                    
                case "gothits":
                    renderHits();
                    
                    me.img.src = "img/lookup_close.gif";
                    me.img.className = "imageClose";
                    
                    fContinue = false;
                    break;
                    
                    
                case "searchstart":
                    fContinue = false;
                    
                    if (me.ef.value.trim())
                    {
                        if (!me.divList)
                        {
                		    me.divList = document.createElement("div");
		                    me.divList.className		= "lookup_listbox";
                        
                            utl.attachEvent(me.divList, "onfocus", function() { me.strFocus = "list"; });
                            utl.attachEvent(me.divList, "onmousedown", function() { me.strFocus = "list"; });
                            utl.attachEvent(me.divList, "onblur", handleListBlur);
                            
		                    var pos = utl.calcAbsolutePos(me.divCont);

		                    utl.setElementPos(me.divList, pos.x, pos.y + me.divCont.offsetHeight - 1, 300, 120);
    		
                		    document.body.appendChild(me.divList);
                        }
                    
                        me.divList.innerHTML = "";
                        
                        me.img.src = "img/lookup_searching.gif";
                        me.img.className = "imageSearching";
                        
                        var div = me.divList.appendChild(document.createElement("div"));
                        div.className = "lookup_searchtext";
                        div.innerHTML = "<img src='img/animated_loading.gif'/>&nbsp;Searching for \"" + me.ef.value + "\"...";
                        
                        if (me.fncS)
                        {
                            me.strSearch = me.ef.value;
                            
                            // If hits returned show immediate
                            me.aHits = me.fncS(me.strSearch);
                            
                            if (me.aHits)
                            {
                                me.state = "gothits";
                                fContinue = true;
                            }
                        }
                    }
                    
                    break;                  
            }
        }
        while(fContinue);
    }
    
    function handleCloseTimer()
    {
        if (me.strFocus == "")
        {
            me.state = "clear";
            process();
        }
    }
    
    function stopCloseTimer()
    {
        if (me.idCloseTimer)
        {
            clearInterval(me.idCloseTimer);
            me.idCloseTimer = null;
        }
    }
    
    function stopTimer()
    {
        if (me.idTimer)
        {
            clearTimeout(me.idTimer);
            me.idTimer = null;
        }
    }
    
    function hideList()
    {
        if (me.divList)
        {
            //me.divList.removeNode();
            me.divList.style.display = "none";
            me.divList.innerHTML = "";
            me.divList = null;
        }
    }
    
    function handleFocus()
    {
        me.strFocus = "input";
        me.state = "typestart";
        
        process();
    }
    
    function handleListBlur()
    {
        if (me.strFocus == "list")
            me.strFocus = "";
    }
    
    function handleInputBlur()
    {
        if (me.strFocus == "input")
            me.strFocus = "";
    }
    
    
    function handleTimeout()
    {
        me.state = "searchstart";
        process();
    }
    
    function handleKeyup()
    {
        if (window.event.keyCode == 27)
        {
            me.state = "clear";
            
            process();
        }
        else if (window.event.keyCode == 13)
        {
            stopTimer();
            me.state = "searchstart";
            process();
        }
        else
        {
            stopTimer();
        
            me.idTimer = setTimeout(handleTimeout, me.lTimeout);

            if (!me.ef.value.trim())
            {
                hideList();
                me.img.src = "img/lookup_idle.gif";
                me.img.className = "imageIdle";
            }
        }
    }
    
    function handleClick()
    {
        if (me.state != "idle")
        {
            me.state = "clear";
            process();
        }
    }
    
    function handleItemClick(d)
    {
        me.fncSel(d);
        me.state = "clear";
        process();
    }
    
    function renderHits()
    {
        if (!me.divList)
            return;
            
        me.divList.innerHTML = "";

        if (me.aHits.length == 0)
        {        
            var div = me.divList.appendChild(document.createElement("div"));
            div.className = "lookup_searchtext";
            div.innerHTML = "No matches found for \"" + me.strSearch + "\"";
            
            return;
        }
        
        for(var i=0; i < me.aHits.length; i++)
        {
    		var div = document.createElement("div");
	    	me.divList.appendChild(div);
	    	
		    div.className = "lookup_item";
		    div.innerHTML = me.aHits[i].label;
		
		    utl.attachEvent(div, "onmouseenter", function()
		    {
			    window.event.srcElement.className = "lookup_itemover";
		    });
		    utl.attachEvent(div, "onmouseleave", function()
		    {
			    window.event.srcElement.className = "lookup_item";
		    });
		    
		    utl.attachEvent(div, "onclick", utl.createCallback(handleItemClick, me.aHits[i].data));
        }
    }
    
    process();    
};


/**
 * Calculates the position of an element relative to upper left of the page
 *
 * @param {Element} el Element of which to calculate absolute position
 * @return {Object} An object with the following properties: source,x,y,top,left,bottom,right,width,height
 */
ninemsn.AP.Util.calcAbsolutePos = function(el)
{
	var o = new Object;
	
	o.source = el;
	o.x = 0;
	o.y = 0;
	while(el != null)
	{
		o.x += el.offsetLeft;
		o.y += el.offsetTop;
		
		el = el.offsetParent;
	}
	
	o.top = o.y;
	o.left = o.x;
	
	o.height = o.source.offsetHeight;
	o.width = o.source.offsetWidth;
	
	if (document.compatMode=="CSS1Compat")
	{
		o.contentWidth = o.source.offsetWidth - o.borderLeft - o.borderRight - o.paddingLeft - o.paddingRight - o.marginLeft - o.marginRight;
		o.contentHeight = o.source.offsetHeight - o.borderTop - o.borderBottom - o.paddingTop - o.paddingBottom - o.marginTop - o.marginBottom;
	}
	else
	{
		o.contentWidth = o.source.offsetWidth;
		o.contentHeight = o.source.offsetHeight;
	}
	o.bottom = o.top + o.height;
	o.right = o.left + o.width;
	
	
	return o;
};

/**
 * Sets the position of an element, if element is not visible it is made visible.
 *
 * @param {Element} el Element to position
 * @param {Number} x Horizontal position of element
 * @param {Number} y Vertical position of element
 * @param {Number} width Width of element
 * @param {Number} height Height of element
 * @param {Number} z (optional) Z index element
 */
ninemsn.AP.Util.setElementPos = function(el, x,y,width,height,z)
{
	el.style.pixelLeft		= x;
	el.style.pixelTop		= y;
	el.style.pixelWidth		= width;
	el.style.pixelHeight	= height;
	
	if (z != undefined)
		el.style.zIndex			= z;     
	el.style.display		= "block";
};

/**
 * Implements the insertAdjacentHTML method as described by IE in other browsers
 *
 * @param {Element} el The element that is receiving the new HTML
 * @param {String} sWhere Name of location for HTML insertion point
 * @param {String} sHTML Text of the HTML to insert
 */
ninemsn.AP.Util.insertAdjacentHTML = function (el, sWhere, sHTML)
{
	if (fIE)
	{
		el.insertAdjacentHTML(sWhere, sHTML);
		return;
	}
	
	var df;	// : DocumentFragment
	var r = el.ownerDocument.createRange();
	
	switch (String(sWhere).toLowerCase())
	{
		case "beforebegin":
			r.setStartBefore(el);
			df = r.createContextualFragment(sHTML);
			el.parentNode.insertBefore(df, el);
			break;
		
		case "afterbegin":
			r.selectNodeContents(el);
			r.collapse(true);
			df = r.createContextualFragment(sHTML);
			el.insertBefore(df, el.firstChild);
			break;
		
		case "beforeend":
			r.selectNodeContents(el);
			r.collapse(false);
			df = r.createContextualFragment(sHTML);
			el.appendChild(df);
			break;
		
		case "afterend":
			r.setStartAfter(el);
			df = r.createContextualFragment(sHTML);
			el.parentNode.insertBefore(df, el.nextSibling);
			break;
	}	
};
/**
 * Implements the insertAdjacentHTML method as described by IE in other browsers
 *
 * @param {Element} elParent The element to be created
 * @param {String} strType Element type
 * @param {String} strClass css class to be assigned to the element
 */
ninemsn.AP.Util.createElement = function(elParent, strType, strClass)
{
	var el = elParent.appendChild(document.createElement(strType));
	if (strClass)
		el.className = strClass;
		
	return el;
};
/**
 * Implements the insertAdjacentText function as described by IE in other browsers
 *
 * @param {Element} el The text to HTML encode
 * @param {String} sWhere The location name of where to insert
 * @param {String} sText The text to insert
 */
ninemsn.AP.Util.insertAdjacentText = function (el, sWhere, sText)
{
	utl.insertAdjacentHTML(el, sWhere, utl.convertTextToHTML(sText));
};

ninemsn.AP.Util.toBoolean = function(val)
{
	if (val == undefined || val == null)
		return false;
    if (isBoolean(val))
        return val;
    else if (val.toLowerCase() == "true") 
        return true;
        
    return false;
};

function isBoolean(a) 
 {
      return typeof a == 'boolean';
 }
 
/**
* HTML encodes the given text
*
* @param {String} s The text to HTML encode
* @return {String} The encoded text
*/
ninemsn.AP.Util.convertTextToHTML = function(s)
{
	s = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<BR>");
    while (/\s\s/.test(s))
		s = s.replace(/\s\s/, "&nbsp; ");
		
    return s.replace(/\s/g, " ");
};

/**
 * Implements the insertAdjacentElement function as described by IE in other browsers
 *
 * @param {Element} el The text to HTML encode
 * @param {String} sWhere The location name of where to insert
 * @param {String} sText The text to insert
 */
ninemsn.AP.Util.insertAdjacentElement = function(oParent, sWhere, oElement)
{
	if (fIE)
		oParent.insertAdjacentElement(sWhere, oElement);
	else
	{
		switch (sWhere.toLowerCase())
		{
			case "beforebegin":
				oParent.parentNode.insertBefore(oElement,oParent);
				break;
			case "beforeend":
				oParent.appendChild(oElement);
				break;
			case "afterbegin":
				oParent.insertBefore(oElement,oParent.firstChild);
				break;				
			case "afterend":
				if (oParent.nextSibling) 
					oParent.parentNode.insertBefore(oElement,oParent.nextSibling);
				else 
					oParent.parentNode.appendChild(oElement);
				break;
			default:
				throw "Invalid Argument"; // TODO - see if I can get the error number set to 201 (match IE)
				break;
		}
	}
};


ninemsn.AP.Util.alphaCSSBackgrounds = function(elContainer)
{
	if (fMozilla)
		return;

	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
	if (!itsAllGood)
		return;
		
	for (i=0; i<elContainer.all.length; i++)
	{
		var bg = elContainer.all[i].currentStyle.backgroundImage;
		if (bg && bg.match(/\.png/i) != null)
		{
			var mypng = bg.substring(5,bg.length-2);
			elContainer.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+mypng+"', sizingMethod='scale')";
			elContainer.all[i].style.backgroundImage = "url('/external/img/s.gif')"; // doesn't seem to matter / overdrawn
		}
	}
};

ninemsn.AP.Util.showLoading = function()
{
	try
	{
		elContainer=document.getElementById("ajaxloading");
		elContainer.style.display="block";
	}
	catch(ex)
	{
	}
};
ninemsn.AP.Util.hideLoading = function()
{
	try
	{
		elContainer=document.getElementById("ajaxloading");
		elContainer.style.display="none";
	}
	catch(ex)
	{
	}
};

function fmtDatetoday()
{
	var day=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    var month=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var _dt=new Date();
    _dtPrint=day[_dt.getDay()] + ", " + _dt.getDate() + " " + month[_dt.getMonth()] + " " + _dt.getFullYear() ;
    return _dtPrint;
}

$(function() {
	var hlArray = new Array();

	hlArray[0] = "169883";
	hlArray[1] = "169802";
	hlArray[2] = "169807";
	hlArray[3] = "169818";
	hlArray[4] = "169808";
	hlArray[5] = "169816";
	hlArray[6] = "173029";

	for (i = 0; i < hlArray.length; i++) {
		applyLIClass(hlArray[i], "search");
		applyLIClass(hlArray[i], "video");
		applyLIClass(hlArray[i], "slideshow");
	}

	function applyLIClass(highlight, type) {
		var ico = $("#cat_hl_" + highlight + " span ." + type);
		for (var i = 0; i < ico.length; i++) {
			var icoParent = ico[i].parentNode.parentNode.className;
			ico[i].parentNode.parentNode.className = icoParent + "li" + type;
		}
	}
});			




