var AOL = AOL || {};
AOL.Search = AOL.Search || {};
AOL.Search.Helpers = {
        addEvent: function (o, type, fn) {
            if (o.attachEvent) {
                o["e" + type + fn] = fn;
                o[type + fn] = function () {
                    o["e" + type + fn](window.event)
                };
                o.attachEvent("on" + type, o[type + fn])
            } else {
                o.addEventListener(type, fn, false)
            }
        },
    getPos: function (o) {
        var l = t = 0;
        if (o.offsetParent) {
            do {
                l += o.offsetLeft;
                t += o.offsetTop
            } while (o = o.offsetParent);
            return {
                y: t,
                x: l
            }
        }
    },
    htmlEntityDecode: function (str) {
        this._EL.TA.innerHTML = str;
        return this._EL.TA.value
    },
	Anim: {
            tween: function (o, attr, stopAt, step, cb) {
                clearInterval(o["intVal" + attr]);
                var intervaledTask, intMs = 5,
                    unit = "px",
                    current = parseInt(o.style[attr]) || 0,
                    dir = (current < stopAt) ? 1 : -1,
                    hasReachedEnd = (dir == 1) ?
                function () {
                    return (current >= stopAt)
                } : function () {
                    return (current <= stopAt)
                };
                var intervaledTask = function () {
                        if (hasReachedEnd()) {
                            (document.all) ? o.style.setAttribute(attr, stopAt + unit) : o.style[attr] = stopAt + unit;
                            clearInterval(o["intVal" + attr]);
                            if (cb) {
                                cb(o)
                            }
                        } else {
                            current += dir * step;
                            (document.all) ? o.style.setAttribute(attr, current + unit) : o.style[attr] = current + unit
                        }
                    };
                o["intVal" + attr] = setInterval(intervaledTask, intMs)
            }
	},
    Http: {
        _load: function (url, isCss) {
            var s;
            if (isCss) {
                s = document.createElement("link");
                s.type = "text/css";
                s.rel = "stylesheet";
                s.href = url
            } else {
                s = document.createElement("script");
                s.src = url
            }
            AOL.Search.Helpers._EL.HEAD.appendChild(s)
        },
        loadCss: function (url) {
            this._load(url, true)
        },
        jsonp: function (url) {
            this._load(url)
        }
    }
};
try {
    AOL.Search.Helpers._EL = {
        TA: document.createElement("textarea"),
        HEAD: document.getElementsByTagName("head")[0]
    }
} catch (e) {};
var AOL = AOL || {};
AOL.Search = AOL.Search || {};
AOL.Search.AutoComplete = {
    inst: [],
    Construct: function (inputBox, conf, attach) {
        try {
            AOL.Search.AutoComplete.inst.push(this);
            var tmp = AOL.Search.AutoComplete.inst.length - 1;
            AOL.Search.AutoComplete.inst[tmp].globalId = tmp;
            this.init(inputBox, conf);
            return AOL.Search.AutoComplete.inst[tmp]
        } catch (e) {}
    }
};
AOL.Search.AutoComplete.Construct.prototype = {
    EL: {},
    CONF: {},
    ENV: {
        ua: navigator.userAgent
    },
    noMatchStrLen: 999,
    lastRequest: false,
    update: function (q) {
        q = q.replace(/^\s+(.*)$/, "$1");
        if (q.length < this.noMatchStrLen && q.length >= 1) {
            if (q != this.lastRequest) {
                AOL.Search.Helpers.Http.jsonp(this.CONF.serviceUrl + escape(q.toLowerCase()))
            }
            this.lastRequest = q
        } else {
            this.reset()
        }
    },
    cb: function (data) {

        this.typedQuery = data[0];
        if (data[1].length > 0) {
            var c = this.EL.acList;
            data[0] = data[0].replace(/([\.\<\>\{\}\[\]\*\+])/g, "\\$1");
            if (this.CONF.showAbove) {
                c.innerHTML = ("<li style='display:none'>" + data[0] + "</li><li>" + data[1].slice(0,this.CONF.numSuggestions-1).reverse().join("</li><li>")).replace(new RegExp(">(" + data[0] + ")", "gi"), "><strong>$1</strong>") + "</li>";
                this.realignY(true)
            } else {
                c.innerHTML = ("<li style='display:none'>" + data[0] + "</li><li>" + data[1].slice(0,this.CONF.numSuggestions-1).join("</li><li>")).replace(new RegExp(">(" + data[0] + ")", "gi"), "><strong>$1</strong>") + "</li>"
            }
			c.innerHTML=c.innerHTML.replace(/,\d+<\/li>/mig,"</li>");
            this.suggestions = c.getElementsByTagName("li");
            c.style.visibility = "visible";
            c.style.display = "block";
            var self = this;
            for (var i = 0; i < this.suggestions.length; i++) {
                this.suggestions[i].onclick = function () {
                    try {
                        self.CONF.invType = self.EL.form.s_it.value || self.EL.form.invocationType.value
                    } catch (e) {
                        self.CONF.invType = d[self.CONF.searchType.toLowerCase()][1] || "temp_" + self.CONF.searchType
                    }
                    self.EL.form.s_it.value = self.CONF.invType.replace(/(\.a)+$/, "") + ".a";
                    self.EL.inputBox.value = AOL.Search.Helpers.htmlEntityDecode(this.innerHTML.replace(/<.*?>/g, ""));
                    self.EL.form.submit()
                };
                this.suggestions[i].onmouseover = function () {
                    self.browse(this)
                }
            }
            this.noMatchStrLen = 999
        } else {
            this.reset(data[0].length + 1)
        }
    },
    browse: function (o, updateSearchBox) {
        for (var i = 0; i < this.suggestions.length; i++) {
            this.suggestions[i].className = " "
        }
        if (o) {
            (typeof (o) == "object") ? this.current = o : this.current = (o == "+1") ? this.current.previousSibling || this.suggestions[this.suggestions.length - 1] : this.current.nextSibling || this.suggestions[1];
            this.current.className = "over";
            if (updateSearchBox) {
                try {
                    this.CONF.invType = this.EL.form.s_it.value || this.EL.form.invocationType.value
                } catch (e) {
                    this.CONF.invType = d[this.CONF.searchType.toLowerCase()][1] || "temp_" + this.CONF.searchType
                }
                this.EL.form.s_it.value = this.CONF.invType.replace(/(\.a)+$/, "") + ".a";
                this.EL.inputBox.value = this.current.innerHTML.replace(/<.*?>/g, "")
            }
            if (this.EL.inputBox.value.match(/&/)) {
                this.EL.inputBox.value = AOL.Search.Helpers.htmlEntityDecode(this.EL.inputBox.value)
            }
        }
    },
    realignX: function () {
        this.EL.acList.style.left = this.EL.inputBox.pos.x + this.CONF.adjust.x + "px"
    },
    realignY: function (showAbove) {
        this.EL.acList.style.top = (showAbove) ? this.EL.inputBox.pos.y - this.EL.acList.offsetHeight + this.CONF.adjust.y + "px" : this.EL.inputBox.pos.y + this.EL.inputBox.offsetHeight + this.CONF.adjust.y + "px"
    },
    reset: function (noMatchStrLen, resetQuery) {
        this.lastRequest = false;
        this.EL.inputBox.pos = AOL.Search.Helpers.getPos(this.EL.inputBox);
        this.EL.acList.style.visibility = "hidden";
        this.realignX();
        this.realignY(this.CONF.showAbove);
        this.noMatchStrLen = noMatchStrLen || this.noMatchStrLen;
        this.current = false;
        if (resetQuery) {
            this.EL.inputBox.value = this.typedQuery || ""
        }
    },
    disable: function () {
        this.reset();
        this.EL.inputBox.onkeyup = null
    },
    enable: function () {
        var self = this;
        this.EL.inputBox.onkeyup = function (e) {
            var key = (typeof event != "undefined") ? window.event.keyCode : e.keyCode;
            switch (key) {
            case (27):
                self.reset(false, true);
                break;
            case (40):
                self.browse("-1", true);
                break;
            case (38):
                self.browse("+1", true);
                break;
            case (13):
                self.disable();
                break;
            case (8):
                self.update(this.value);
                break;
            default:
                self.update(this.value)
            }
        };
        var d = AOL.Search.AutoComplete.Config[this.CONF.locale.toLowerCase()];
        try {
            this.CONF.invType = this.EL.form.s_it.value || this.EL.form.invocationType.value
        } catch (e) {
            this.CONF.invType = d[this.CONF.searchType.toLowerCase()][1]["default_sit"] || "temp_" + this.CONF.searchType
        }
		if( this.CONF.searchType.toLowerCase().match(/^cse_/) ) {
			AOL.Search.AutoComplete.inst["i"+this.globalId]=AOL.Search.AutoComplete.inst[this.globalId];
			this.CONF.serviceUrl = (d[this.CONF.searchType.toLowerCase()][1]["serviceUrl"] || this.CONF.serviceUrl || d.SERVICE_URL) + "&callback=AOL.Search.AutoComplete.inst.i"+this.globalId+".cb&q=";
			//this.CONF.serviceUrl = (d[this.CONF.searchType.toLowerCase()][1]["serviceUrl"] || this.CONF.serviceUrl || d.SERVICE_URL) + "&callback=foo&q=";
		} else {
			this.CONF.serviceUrl = (d[this.CONF.searchType.toLowerCase()][1]["serviceUrl"] || this.CONF.serviceUrl || d.SERVICE_URL) + "?echo=off&output=json&it=" + this.CONF.invType + "&count=" + this.CONF.numSuggestions + "&dict=" + d[this.CONF.searchType.toLowerCase()][0] + "&cb=AOL.Search.AutoComplete.inst[" + this.globalId + "].cb&q=";
		}
        AOL.Search.Helpers.addEvent(this.EL.inputBox, "blur", function () {
            setTimeout(function () {
                self.reset()
            }, 300)
        });
        AOL.Search.Helpers.addEvent(this.EL.inputBox, "click", function () {
            self.reset()
        });
        AOL.Search.Helpers.addEvent(window, "resize", function () {
            self.reset()
        })
    },
    init: function (inputBox, conf) {
        this.CONF = conf;
        if (!this.CONF.serviceUrl) {
            this.CONF.serviceUrl = false
        }
        this.CONF.locale = this.CONF.locale || "en_gb";
        conf.adjust = conf.adjust || {};
        this.CONF.adjust = {
            width: conf.adjust.width || false,
            x: conf.adjust.x || 0,
            y: conf.adjust.y || 0
        };
        this.CONF.numSuggestions = this.CONF.numSuggestions || 6;
        this.EL = {
            inputBox: (typeof (inputBox) == "string") ? document.getElementById(inputBox) : inputBox,
            acList: document.createElement("ul")
        };
        this.EL.acList.className = "aolSearchAutoComp";
        if (this.CONF.className) {
            this.EL.acList.className += " " + this.CONF.className
        }
        if (this.CONF.id) {
            this.EL.acList.id = this.CONF.id
        }
        this.EL.form = this.EL.inputBox;
        do {
            this.EL.form = this.EL.form.parentNode
        } while (this.EL.form.nodeName.toLowerCase() != "form");
        this.EL.acList.style.width = (this.CONF.adjust.width || this.EL.inputBox.offsetWidth) + "px";
        if (this.CONF.css) {
            this.EL.acList.setAttribute("style", this.CONF.css)
        }
        this.EL.acList.style.position = "absolute";
        this.EL.acList.innerHTML = "";
        this.EL.inputBox.setAttribute("autocomplete", "off");
        document.body.appendChild(this.EL.acList);
        this.enable();
        this.reset()
    }
};
try {
    AOL.Search.AutoComplete.Config = {
        en_gb: {
            SERVICE_URL: "http://autocomplete.search.aol.com/autocomplete/get",
            web: ["en_uk_search",{}],
			webus: ["en_us_search",{}],
            parentdish: ["en_uk_parentdish_h",{serviceUrl: "http://autocompletech.search.aol.com/autocomplete/get"}]
        },
        fr_fr: {
            SERVICE_URL: "http://autocomplete.search.aol.com/autocomplete/get",
            web: ["fr_eu_search",{}]
        },
        de_de: {
            SERVICE_URL: "http://autocomplete.search.aol.com/autocomplete/get",
            web: ["de_eu_search",{}]
        }
    }
} catch (e) {};
// CSE additions to config using CSE IDs only
(function(){
	var CSEs={
		en_gb : {
			network: "017413276943390660056:pkcvhq5flxm",
			music: "017413276943390660056:1s6pdy1aeps",
			news: "017413276943390660056:y3ghnpsdmhu",
			lifestyle: "017413276943390660056:gpz_k0ut-vq",
			sport: "017413276943390660056:jh2he4wqmf8",
			travel: "017413276943390660056:qpciy4cod1s",
			celebrity: "017413276943390660056:xv5bet9w_l0",
			cars: "017413276943390660056:vxyvhyweb6i",
			money: "017413276943390660056:xtznfgrnnje",
			entertainment: "017413276943390660056:odba_ctidjs",
			parentdish: "017413276943390660056:yhprpxs9sig",
			huffingtonpost: "017413276943390660056:eln8nv3gbwk",
			mydaily: "017413276943390660056:aw75ikmrh_q",
			asylum: "017413276943390660056:vnpue0cq4ow"
		},
		fr_fr : {},
		de_de : {}
	};
	for(var locale in CSEs) {
		locale=locale.toLowerCase();
		for(var property in CSEs[locale])
			AOL.Search.AutoComplete.Config[locale]["cse_"+property.toLowerCase()]=[locale+"_cse_"+property+"_h",{serviceUrl:"http://clients1.google.com/complete/search?ds=cse&hl=en&client=partner&source=gcsc&partnerid="+escape(CSEs[locale][property])}];
	}
})();
