/*
	name : globalHeader
	file : jquery.globalheader.js
	author : Ali Hasan
	(c) Copyright 2009 AOL LLC
	$LastChangedDate: 2009-11-24 08:30:32 -0500 (Tue, 24 Nov 2009) $
	$Rev: 134091 $
*/
(function (a) {
    a.fn.globalHeader = function (d) {
        var c = {
            activeTab: null,
            moreLinks: [],
            morePromoCount: 2,
            moreText: "You might also like:",
            moreAnd: "and",
            moreMore: "More",
            moreTextHeadline: "More Sites You Might Like",
            uiHat: "#GH_hat",
            uiHatLinks: "#GH_hat_links",
            uiHatTools: "#GH_hat_tools",
            uiNavLi: "li.GH_nav_LI",
            uiNavADd: ".GH_nav_dd_A",
            auth: {
                doAuth: false,
                authenticated: false,
                authState: null,
                unauthState: null
            },
            search: {
                uiSearch: "#GH_search",
                params: {}
            },
            fn: {}
        },
            e = {},
            h = this,
            g = {},
            f = {
            activeTab: null,
            moreLinksBuilt: false
        },
            b = {
            init: function (i) {
                g.$d = a(document);
                g.$c = a(i);
                g.hat = a(e.uiHat)[0];
                g.hatLinks = a(e.uiHatLinks)[0];
                g.$hatTools = a(e.uiHatTools);
                g.$search = a(e.search.uiSearch);
                g.$searchInput = g.$search.find("input:first");
                g.$searchSubmit = g.$search.find("input:last");
                g.$navLi = g.$c.find(e.uiNavLi);
                g.$navADd = g.$c.find(e.uiNavADd);
                b.setActiveTab(null, e.activeTab);
                if (e.auth.doAuth) {
                    b.buildAuth()
                }
                b.buildMoreLinks();
                b.buildDropDowns();
                g.$c.bind("setActiveTab", function (k, j) {
                    b.setActiveTab(k, j)
                });
                g.$c.bind("setAuthState", function (k, j) {
                    b.buildAuth(k, j)
                });
                if (e.search.params.initFocus !== undefined && e.search.params.initFocus) {
                    g.$search.globalSearchBox(e.search.params)
                } else {
                    g.$searchInput.bind("focus.GH", function (j) {
                        b.buildSearch(j)
                    }).attr("autocomplete", "off");
                    g.$searchSubmit.bind("mouseover.GH", function (j) {
                        b.buildSearch(j)
                    });
                    if (e.search.params.searchText !== undefined && e.search.params.searchText !== "") {
                        g.$searchInput.val(e.search.params.searchText)
                    }
                }
            },
            getVars: function () {
                return {
                    options: e,
                    ui: g,
                    local: f
                }
            },
            buildSearch: function (i) {
                g.$searchInput.unbind("focus.GH");
                g.$searchSubmit.unbind("mouseover.GH");
                if (i.target === g.$searchInput[0]) {
                    g.$searchInput.addClass("GH_search_active").attr("value", "")
                }
                g.$search.globalSearchBox(e.search.params)
            },
            buildAuth: function (j, i) {
                if (i !== undefined) {
                    a.extend(true, e.auth, i)
                }
                g.$hatTools.empty().append((e.auth.authenticated) ? e.auth.authState : e.auth.unauthState)
            },
            buildMoreLinks: function () {
                var p = e.moreLinks, n = 0, j = p.length;
				
                if (j >= e.morePromoCount) {
                    var k = a("#GH_hat_more"), o, m;
					
                    if (!k.length) {
                        m = a("<li />").addClass("GH_hat_LI").append(o = a("<ul />").attr("id", "GH_hat_more").addClass("GH_hat_UL").append(a("<li />").addClass("GH_hat_LI").text(e.moreText + "\xa0 ")));
                        for (; n < e.morePromoCount; n++) {
                            o.append(a("<li />").addClass("GH_hat_LI").append(a("<a />").attr({
                                href: p[n][1],
                                target: (p[n][2] !== undefined) ? p[n][2] : "_self"
                            }).addClass("GH_hat_A GH_hat_more_A").text(p[n][0])).append((n < e.morePromoCount - 1) ? ",\xa0" : ""))
                        }
                        if (j > e.morePromoCount) {
                            o.append(g.$hatLIMore = a("<li />").addClass("GH_hat_LI GH_hat_LI_more").append("\xa0" + e.moreAnd + "\xa0").append(g.$hatMoreLink = a("<a />").attr({
                                id: "GH_hat_more_link",
                                href: "#"
                            }).addClass("GH_hat_A GH_hat_more_A").text(e.moreMore)))
                        }
                        m.appendTo(g.hatLinks)
                    } else {
                        g.$hatMoreLink = a("#GH_hat_more_link");
                        g.$hatLIMore = g.$hatMoreLink.parent()
                    }
                    g.$hatMoreLink.bind("mouseover.GH", function (i) {
                        b.showMoreLinks(i)
                    })
                }
            },
            showMoreLinks: function (p) {
                p.preventDefault();
                if (f.moreLinksBuilt === false) {
                    var n = e.moreLinks.slice(e.morePromoCount),
                        o = 0,
                        m = n.length,
                        j = Math.ceil(m / 3),
                        k = Math.ceil(m / 3 * 2),
                        s, r, q, t;
                    g.$hatMoreList = a("<div />").attr("id", "GH_more_list").append(a("<b />").attr("id", "GH_more_list_lab").text(e.moreTextHeadline)).append(s = a("<ul />").addClass("GH_more_list_UL")).append(r = a("<ul />").addClass("GH_more_list_UL")).append(q = a("<ul />").addClass("GH_more_list_UL"));
                    for (; o < m; o++) {
                        t = a("<li />").append(a("<a />").attr({
                            href: n[o][1],
                            target: (n[o][2] !== undefined) ? n[o][2] : "_self"
                        }).text(n[o][0]));
                        if (o < j) {
                            t.appendTo(s)
                        } else {
                            if (o < k) {
                                t.appendTo(r)
                            } else {
                                t.appendTo(q)
                            }
                        }
                    }
                    g.$hatMoreList.css("left", g.$hatLIMore.offset().left - g.$c.offset().left + 14).appendTo(g.hat);
                    f.moreLinksBuilt = true
                }
                if (g.$hatMoreList.css("display") === "none") {
                    g.$d.bind("mousemove.GHTEMP", function (i) {
                        b.kill(i)
                    });
                    g.$hatMoreList.fadeIn("fast")
                }
            },
            kill: function (j) {
                var i = a(j.target);
                if (i.closest("#GH_hat_more_link").length === 0 && i.closest("#GH_more_list").length === 0) {
                    g.$d.unbind("mousemove.GHTEMP");
                    g.$hatMoreList.fadeOut("fast")
                }
            },
            setActiveTab: function (j, i) {
                if (i !== undefined && i !== null) {
                    if (f.activeTab !== null) {
                        f.activeTab.removeAttr("id");
                        if (f.activeTab.hasClass("GH_nav_list")) {
                            a("#GH_nav_act_B").removeAttr("id")
                        }
                    }
                    f.activeTab = g.$navLi.eq(i).attr("id", "GH_nav_act");
                    f.activeTab.children().eq(0).css("clear", "both");
                    if (f.activeTab.hasClass("GH_nav_list")) {
                        f.activeTab.children().eq(0).wrapInner('<b id="GH_nav_act_B"></b>')
                    }
                }
            },
            buildDropDowns: function () {
                g.$navLi.each(function () {
                    var i = a(this);
                    if (i.hasClass("GH_nav_list")) {
                        i.mouseover(function () {
                            if (i.showtimer) {
                                clearInterval(i.showtimer);
                                i.showtimer = null
                            }
                            i.addClass("GH_nav_list_open").find("ul").fadeIn("fast")
                        }).mouseout(function () {
                            i.showtimer = setTimeout(function () {
                                if (i.showtimer) {
                                    clearInterval(i.showtimer);
                                    i.showtimer = null
                                }
                                i.removeClass("GH_nav_list_open").find("ul").fadeOut("fast")
                            },
                            250)
                        })
                    }
                })
            }
        };
        a.extend(true, e, c, d);
        a.extend(true, b, e.fn);
        b.init(h);
        return h
    }
})(jQuery);

/*
	name : globalSearchBox
	file : jquery.globalsearchbox.js
	author : Ali Hasan
	(c) Copyright 2009 AOL LLC
	$LastChangedDate: 2009-11-20 14:21:28 -0500 (Fri, 20 Nov 2009) $
	$Rev: 133745 $
	///////////////////////////		
	dependencies : jQuery 1.3.2
	///////////////////////////
	description: 
	Build global search box.
*/

(function($){
$.fn.globalSearchBox = function( customOptions ) {
		/* default options */
	var defaultOptions = {
			apiUrl : 'http://autocomplete.search.aol.com/autocomplete/get', // api url
			apiIt : 'ops-test', // internal tracking channel id
			apiOutput : 'json',  // data format for api to return
			apiCount : 8, // # of results for api to return
			apiQueryParam : 'q',
			apiDictionary : '',
			ui_form : '#GH_search_form', // search form
			ui_input : '#GH_search_field', // ui input field
			ui_submit : '#GH_search_button', // ui submit button
			ui_output : '#GH_search_results', // ui output container
			initSmartSearch : true,
			searchText : '',
			preserveGhostText : false,
			initFocus : false,
			fn : { } // functions to be overridden
		},
	
		/* merged options */
		options = {},
		
		/* target jQuery collection */
		$this = this,
	
		/* ui model*/
		ui = {},
	
		/* local data store */
		local = {
			ghostText : '',
			query : '',
			results : [],
			highlight : -1,
			$highlight : null,
			timer : null
		},
			
		/* private functions */
		core = { 
			/* create ui model, attach events */
			init : function(container) {
				ui.$c = $(container);
				ui.$input = $(options.ui_input);
				ui.$output = $(options.ui_output);
				ui.form = $(options.ui_form)[0];
				ui.submit = $(options.ui_submit)[0];
				
				local.ghostText = ui.$input.attr('defaultValue'); // save initial ghost text value
				ui.$input.attr('autocomplete','off').bind('focus.GH', function(e) { core.processInputFocus(e); }).bind('blur.GH', function(e) { core.processInputBlur(e); });
				$(ui.form).bind('submit.GH', function(e) { core.selectSuggestion(e); });

				// initialize type ahead functionality
				if (options.initSmartSearch) {
					// create api url
					options.apiUrl = options.apiUrl + '?it=' + options.apiIt + '&count=' + options.apiCount + '&output=' + options.apiOutput;
					if (options.apiDictionary !== '') {
						options.apiUrl = options.apiUrl + '&dict='+ options.apiDictionary;
					}
					// attach events
					ui.$input.bind('keyup.GH', function(e) { core.processKeyPress(e); });
					ui.$output.bind('mouseover.GH', function(e) { core.moveHighlightMouse(e); }).bind('mouseover.GH', function(e) { core.suspendBlurDetection(e); }).bind('mouseleave.GH', function(e) { core.resumeBlurDetection(e); }).bind('click.GH', function(e) { core.selectSuggestion(e); });	
				}
				// initial focus
				if (options.initFocus) {
					ui.$input.focus();
				}
				// preserve ghost text
				if (options.preserveGhostText) {
					ui.$label = $('<label />').attr('id','GH_search_label').text(local.ghostText).appendTo(ui.form);
					ui.$label.bind('click.GH_SL', function(e) { core.preserveGhostText(true); } );
					ui.$input.bind('keyup.GH_SL', function(e) { core.preserveGhostText(e); }).bind('click.GH_SL', function(e) { core.preserveGhostText(e); }).bind('blur.GH_SL', function(e) { setTimeout(function() { core.preserveGhostText(e); },250); });
				}
				// preset search text
				if (options.searchText !== '') {
					ui.$input.val(options.searchText);
				}
			},

			/* helper function to return private variables to extended functions */
			getVars : function() {
				return {
					options : options,
					ui : ui,
					local : local							
				};					
			},
						
			/* clear out text, primed for user's input */
			processInputFocus : function(e) {				
				ui.$input.addClass('GH_search_active').val((ui.$input.val() === local.ghostText) ? '' : ui.$input.val());			
			},
			
			/* close out flyout, restore text */
			processInputBlur : function(e) {
				ui.$input.removeClass('GH_search_active').val((ui.$input.val() === '') ? local.ghostText : ui.$input.val());
				core.displaySuggestions();
			},
			
			preserveGhostText : function(labelClick) {
				if (typeof labelClick === 'boolean' && labelClick) {
					ui.$input.focus();
				}
				ui.$input.unbind('keyup.GH_SL').unbind('click.GH_SL').unbind('blur.GH_SL');
				ui.$label.remove();
			},
			
			/* capture key press and determine if it is a navigation action or a query action */
			processKeyPress : function(e) {
				var kc = e.keyCode;
				if (kc === 38) {
					core.moveHighlightKey(-1);
				}
				else if (kc === 40) {
					core.moveHighlightKey(1);
				}
				else {
					var input = e.target,
						query = $.trim(input.value);
					
					if (query !== '') {	
						/* create delay to reduce number of api calls */
						if (local.timer !== null) { clearTimeout(local.timer); }
						local.timer = setTimeout(function(){ core.getSuggestions(query); },200);
					}
					else {
						core.displaySuggestions();
					}
				}
			},
				
			/* handle keyboard actions */
			moveHighlightKey : function(i) {
				if (local.$highlight !== null ) { local.$highlight.removeClass('GH_highlight'); }
				local.highlight = local.highlight + i;
				if (local.highlight >= local.results.length || local.highlight === -1) {
					local.highlight = -1;
					ui.$input.val(local.query);
				}
				else if (local.highlight < -1) {
					local.highlight = local.results.length - 1;						
				}
				if (local.highlight > -1) {
					local.$highlight = $(local.results[local.highlight]);
					local.$highlight.addClass('GH_highlight');
					ui.$input.val(local.$highlight.text());
				}
			},
			
			/* handle mouse actions */
			moveHighlightMouse : function(e) {
				var target = e.target;
				if (target.nodeName === 'B') { target = target.parentNode; }
				if (local.$highlight !== null ) { local.$highlight.removeClass('GH_highlight'); }
				local.highlight = local.results.index(target);
				local.$highlight = $(target).addClass('GH_highlight');
			},	
			
			/* submit form on mouse click */
			selectSuggestion : function(e) {
				e.preventDefault();
				if (e !== undefined && e.type === 'click') {
					var target = e.target;
					if (target.nodeName === 'B') { target = target.parentNode; }
					ui.$input.val($(target).text());
				}
				
				ui.$input.val($.trim(ui.$input.val()));
				
				if (ui.$input.val() !== '' && ui.$input.val() !== local.ghostText) {
					ui.form.submit();
				}
			},
			
			/* make api call */
			getSuggestions : function(query) {
				var url = options.apiUrl + '&' + options.apiQueryParam + '=' + query;
	
				$.ajax({
					dataType : 'jsonp',
					url: url,
					jsonp : 'cb',
					success: function ( jsonp ) {
						core.displaySuggestions(jsonp);
					}, 
					error : function () {
						core.displaySuggestions();
					}
				});	
			},
			
			suspendBlurDetection : function() { ui.$input.unbind('blur.GH'); },
			
			resumeBlurDetection : function() { ui.$input.bind('blur.GH', function(e) { core.processInputBlur(e); }); },
			
			/* render search results drop down */
			displaySuggestions : function(data) {
				// Clear out old data
				local.highlight = -1;
				local.$highlight = null;
				
				// Populate new data 
				if (data !== undefined && data[1].length > 0) {
					local.query = data[0];
					var s = data[1],
						suggestions = $('<ul />'),
						i, l = s.length,
						re = new RegExp(local.query,'i'),
						rex = "<b>"+local.query+"</b>";
					
					for (i = 0; i < l; i++) {
						$('<li />').html(s[i].replace(re,rex)).appendTo(suggestions);
					}
					local.results = suggestions.find('li');
					ui.$output.empty().append(suggestions).fadeIn('fast');
				}
				else {
					local.query = '';
					local.results = [];
					ui.$output.fadeOut('fast').empty();
				}
			}
		};//end core

		/* extend default options to include user's custom options */
		$.extend( true, options, defaultOptions, customOptions );	
		
		/* apply any overrides to core */
		$.extend( true, core, options.fn );
			
		/* begin */
		core.init($this);
		
		/* jQuery default behavior, return container */
		return $this;
	};
})(jQuery);

jQuery(function($){
	var fVal = $('#GH_search_field').val();
	if(typeof fVal =='undefined') return false;
	$('#GF_search_field').val(fVal).attr('autocomplete','off').click(function(){
		$(this).addClass('GF_search_active').val('');
	}).blur(function(){
		$(this).removeClass('GF_search_active');
	}).parent().submit(function(){
		var cNode = $(this).children(0);
		if(cNode.val() == fVal){
			cNode.val('');
		}
	});
	/* Used for the multi col header menu if needed */
	var $mcolObj = $('#GH_nav_list_ul_col2'), iC;
	if($mcolObj){
		for (iC=0;iC<$mcolObj.length;iC++){
			var liFlag =$mcolObj.eq(iC).children('li').length%2;
			if(liFlag==1)$mcolObj.eq(iC).append("<li class='GH_nav_list_r'><a>&nbsp; &nbsp;</a></li>");
		}
	}
});
