﻿
var MagRadar = {

    Urls: { Public: "http://www.magazineradar.com/", Widgets: "http://widgets.magazineradar.com/" },
    Widgets: [],

    SearchType: {
        Magazine: {
            noResultsCopy: "We couldn't find your title. MagazineRadar tracks more than 2500 titles. Please select another.",
            dataServicesUrl: function(startsWith, callback) { return MagRadar.Urls.Public + "dataservices/publications?startsWith=" + startsWith + "&max=2500&callback=MagRadar.Searches['" + callback + "']"; },
            submit: function(value, _unused, _unused) {
                window.open(MagRadar.Urls.Public + "/Products/Advertising/PubOverview/?pubName=" + escape(value));
            }
        }, Brand: {
            noResultsCopy: "We couldn't find your brand. MagazineRadar tracks more than 250,000 brands. Please select another.",
            dataServicesUrl: function(startsWith, callback) { return MagRadar.Urls.Public + "dataservices/companies?startsWith=" + startsWith + "&max=2500&callback=MagRadar.Searches['" + callback + "']"; },
            submit: function(value, widgetName, suggest) {
                var width = 330;
                var height = 750;
                var url = MagRadar.Urls.Public  + "/Products/Advertising/WidgetAccountReview/" + widgetName
                                                + "?suggest=" + (suggest ? 1 : 0) 
                                                + "&companyName=" + escape(value);                                                                                                      
                var popup_options = "menubar=no,toolbar=no,location=no,status=no,scrollbars=no"
                        + ",width=" + width + ",height=" + height;
                window.open(url, "_blank", popup_options);
            }
        }
    },

    MagRadarWidget: function(options) {

        var widgetDiv = document.getElementById(options.id);

        MagRadar.Widgets.push(widgetDiv);

        function output(text) { // does nothing; taking out debugging
        }

        if (document.all) {   // very basic browser detection
            var sFloat = "styleFloat"; //ie
        } else {
            var sFloat = "cssFloat"; //firefox
        }

        var searchBoxScrollingFudgeFactor = 40;
        var keyCodes = { downArrow: 40, upArrow: 38, enterKey: 13, spaceBar: 32, backspaceKey: 8, deleteKey: 46 };




        this.CreateSearchBox = function(box_options) { 
        
            var showDropdown = box_options.suggest;
            
            // ---------------- CJL: begin "phase 1" tweaks: ----------------   //
            //          these settings are hard-coded until scrolling           //
            //              suggestion-dropdown is fully working                //
            
            box_options.suggestionLimit = 10; 
            if (box_options.type == MagRadar.SearchType.Brand) {
                showDropdown = false;
            }

            // ---------------- CJL: end "phase 1" tweaks -------------------   //


            var getSuggestions = showDropdown || box_options.autoComplete || box_options.confirm;

            for (var key in box_options.widgetStyles) {
                var evalString = "widgetDiv.style." + key + "= '" + box_options.widgetStyles[key] + "';";
                eval(evalString);
            }
            //we don't want other sites to set the backgroun image; we set it after other sites' custom params
            widgetDiv.style.background = "url(\"" + MagRadar.Urls.Widgets + "/Images/" + box_options.widgetName + "-background.gif\") no-repeat top left";



            var bodyDiv = widgetDiv.appendChild(document.createElement("DIV"));
            for (var key in box_options.bodyStyles) {
                var evalString = "bodyDiv.style." + key + "= '" + box_options.bodyStyles[key] + "';";
                eval(evalString);
            }

            var bodyTextDiv = bodyDiv.appendChild(document.createElement("DIV"));
            bodyTextDiv.innerHTML = box_options.bodyText;
            for (var key in box_options.bodyTextStyles) {
                var evalString = "bodyTextDiv.style." + key + "= '" + box_options.bodyTextStyles[key] + "';";
                eval(evalString);
            }

            var form = bodyDiv.appendChild(document.createElement("FORM"));
            form.style.position = "absolute"; //for IE6 compatibility

            var callback = "jsonp" + options.id;
            MagRadar.SearchResults[callback] = Object();

            var searchBoxId = MagRadar.SearchBoxIDPrefix + box_options.id;
            var searchBox = document.createElement("INPUT");
            searchBox.setAttribute("TYPE", "TEXT");
            searchBox.setAttribute("ID", searchBoxId)
            searchBox.setAttribute("AUTOCOMPLETE", "OFF");
            searchBox.style.width = box_options.widths.textbox;
            searchBox.style.position = "relative";

            this.focus = function(e) { searchBox.focus(); searchBox.onclick(); }


            searchBox.showHint = function() {
                searchBox.value = box_options.hint;
                searchBox.style.color = "#999";
                searchBox.style.fontStyle = "italic";
            }

            searchBox.hideHint = function() {
                searchBox.value = "";
                searchBox.style.fontStyle = "normal";
                searchBox.style.color = "#000";
            }

            searchBox.showHint();

            searchBox.onclick = function(e) {

                if (searchBox.value == box_options.hint) {
                    searchBox.hideHint();
                }
                if (window.event) {
                    // this code is for IE
                    window.event.cancelBubble = true;
                } else if (e.stopPropagation) { //IE will barf if it hits this e.stopPropagation line; so leave IE check (eg window.event) first
                    // this code is for Mozilla and Opera
                    e.stopPropagation();
                }
            };

            searchBox.onblur = function(e) {
                if (!searchBox.value) {
                    searchBox.showHint();
                }
            };

            function navigateSuggestions(evt) { // CJL: taking out for phase 1
            }

            searchBox.onkeyup = function(e) {

                //don't even make the dataServices call if we're not suggesting any values
                if (!getSuggestions) return;

                var evt = e || event;

                var autoComplete = box_options.autoComplete || false;

                // user hit backspace AND we've suggested a value WHICH MEANS that part of the text was highlighted...
                if (autoComplete && searchBox.suggestions.length > 0 && evt.keyCode == keyCodes["deleteKey"]) {
                    searchBox.value = searchBox.value.substring(0, searchBox.value.length - 1);
                }


                if (!searchBox.value) {

                    searchBox.suggestions.clear();
                    return;

                } else if (evt.keyCode < 48
                    && !(evt.keyCode == keyCodes["backspaceKey"] || evt.keyCode == keyCodes["deleteKey"])) {

                    navigateSuggestions(evt);
                    return;

                }

                if (noResultsDiv && noResultsDiv.visible) noResultsDiv.hide();

                var cacheKey = searchBox.value.toLowerCase().substring(0, 1);


                if (MagRadar.Searches[callback])
                    delete MagRadar.Searches[callback];

                //Important: IE needs "MagRadar.Searches[callback] = function(data)"
                //  to be declared before calling "document.getElementsByTagName("HEAD")[0].appendChild(dataScript)"
                MagRadar.Searches[callback] = function(data) {

                    if (!MagRadar.SearchResults[callback][cacheKey]) {
                        MagRadar.SearchResults[callback][cacheKey] = data;
                    }

                    var dataSource = box_options.dataSource || MagRadar.SearchResults[callback][cacheKey];
                    var count = searchBox.suggestions.populateStartsWith(dataSource, searchBox.value);

                    if (count > 0 && showDropdown) {
                        searchBox.suggestions.show();
                    }

                    if (autoComplete) {
                        searchBox.autofillFirstSuggestion();
                    }

                }

                if (!MagRadar.SearchResults[callback][cacheKey]) {
                    var url = box_options.type.dataServicesUrl(cacheKey, callback);
                    var dataScript = document.createElement("SCRIPT");
                    dataScript.src = url;
                    dataScript.id = callback + '_' + cacheKey;

                    document.getElementsByTagName("HEAD")[0].appendChild(dataScript);
                } else {
                    MagRadar.Searches[callback](MagRadar.SearchResults[callback][cacheKey]);
                }


            };

            var searchBoxContainerDiv = form.appendChild(document.createElement("DIV"));

            searchBoxContainerDiv.style[sFloat] = "left";
            searchBoxContainerDiv.appendChild(searchBox);
            widgetDiv.searchBox = searchBox;

            var submit = createImageSubmit();
            submit.onclick = function(e) {

                if (!box_options.confirm || searchBox.suggestions.exactSingleMatch()) {
                    box_options.type.submit(searchBox.value, box_options.widgetName, box_options.suggest);
                } else {
                    noResultsDiv.show();
                }

                return false;

            }

            var submitContainerDiv = form.appendChild(document.createElement("DIV"));
            submitContainerDiv.style[sFloat] = "left";
            submitContainerDiv.style.paddingLeft = "10px";
            submitContainerDiv.style.width = submit.width + "px";
            submitContainerDiv.appendChild(submit);

            var clearFloatLeftDiv = form.appendChild(document.createElement("DIV"));
            clearFloatLeftDiv.style.clear = "both";
            clearFloatLeftDiv.style.height = "1px";
            clearFloatLeftDiv.style.fontSize = "1px";
            clearFloatLeftDiv.style.position = "relative";

            searchBox.onkeypress = function(e) {
                if ((e || event).keyCode == 13) {
                    submit.click();
                    return false;
                }
            };


            if (box_options.confirm) {

                var noResultsDiv = clearFloatLeftDiv.appendChild(document.createElement("DIV"));



                noResultsDiv.innerHTML = box_options.type.noResultsCopy;
                noResultsDiv.visible = true;
                for (var key in box_options.warningStyles) {
                    var evalString = "noResultsDiv.style." + key + "= '" + box_options.warningStyles[key] + "';";
                    eval(evalString);
                }

                noResultsDiv.show = function() {
                    noResultsDiv.style.visibility = "visible";
                    noResultsDiv.visible = true;
                }
                noResultsDiv.hide = function() {
                    noResultsDiv.style.visibility = "hidden";
                    noResultsDiv.visible = false;
                }
                noResultsDiv.hide();
            }

            if (getSuggestions) {

                searchBox.suggestions = form.appendChild(document.createElement("DIV"));
                searchBox.suggestions.style.border = "1px solid #999";
                searchBox.suggestions.style.backgroundColor = "#fff";
                searchBox.suggestions.style.position = "absolute";
                searchBox.suggestions.style.top = "23px";
                searchBox.suggestions.style.width = box_options.widths.dropdown;
                searchBox.suggestions.style.clear = "both";
                searchBox.suggestions.style.zIndex = "100";
                searchBox.suggestions.visible = false;


                var itemList = searchBox.suggestions.appendChild(document.createElement("DIV"));

                if (!box_options.suggestionLimit) {
                    itemList.style.height = "150px";
                    itemList.style.width = box_options.widths.dropdown;
                    itemList.style.overflow = "scroll";
                }
                itemList.style.padding = "7px";
                itemList.style.paddingTop = "0px";

                searchBox.suggestions.clear = function() {
                    itemList.innerHTML = "";
                    searchBox.suggestions.length = 0;
                    searchBox.suggestions.firstValue = null;
                    searchBox.suggestions.style.visibility = "hidden";
                    searchBox.suggestions.visible = false;
                    searchBox.selectedItem = null;
                    searchBox.firstItem = null;
                    searchBox.lastItem = null;
                    output(searchBox.suggestions.length + "  " + searchBox.suggestions.visible);
                }
                searchBox.suggestions.clear();


                searchBox.suggestions.show = function() {
                    searchBox.suggestions.style.visibility = "visible";
                    searchBox.suggestions.visible = true;
                    output(searchBox.suggestions.length + "  " + searchBox.suggestions.visible);
                }


                searchBox.suggestions.exactSingleMatch = function(value) {
                    return (searchBox.suggestions.length >= 1
                        && searchBox.suggestions.firstValue
                        && searchBox.suggestions.firstValue.toLowerCase() == searchBox.value.toLowerCase());
                }

                searchBox.suggestions.append = function(value) {

                    if (searchBox.suggestions.length == 0) {
                        var header = itemList.appendChild(document.createElement("DIV"));
                        header.innerHTML = "Did you mean...";
                        header.style.fontSize = "10px";
                        header.style.fontStyle = "italic";
                        header.style.color = "#999";
                        header.style.paddingBottom = "6px";
                        //header.style.border = "1px solid black";
                        header.style.textAlign = "center";
                    }

                    var item = itemList.appendChild(document.createElement("DIV"));
                    item.innerHTML = value;
                    item.style.display = "block";
                    item.onclick = function(e) {
                        box_options.type.submit(value, box_options.widgetName, box_options.suggest);
                    }
                    item.onmouseover = function(e) {
                        if (searchBox.suggestions.selectedItem)
                            searchBox.suggestions.deselect(searchBox.suggestions.selectedItem);
                        searchBox.suggestions.selectedItem = item;
                        searchBox.suggestions.select(item);
                    }

                    item.onmouseout = function(e) {
                        searchBox.suggestions.deselect(item);
                        searchBox.suggestions.selectedItem = null;
                    }

                    if (!searchBox.suggestions.firstItem) {
                        searchBox.suggestions.firstItem = item;
                        searchBox.suggestions.lastItem = item;
                        item.prevItem = null;
                        item.nextItem = null;
                    } else {
                        item.prevItem = searchBox.suggestions.lastItem;
                        searchBox.suggestions.lastItem.nextItem = item;
                        searchBox.suggestions.lastItem = item;
                        item.nextItem = null;
                    }

                    if (searchBox.suggestions.length == 0) {
                        //var header = itemList.appendChild(document.createElement("DIV"));
                        //header.innerHTML = "Did you mean";
                        searchBox.suggestions.firstValue = value;
                        if (value.toLowerCase() == searchBox.value.toLowerCase()) {
                            /* -- CJL: this would highlight the value in the dropdown if the 1st value is an exact match of what the user entered
                            if (searchBox.suggestions.selectedItem)
                            searchBox.suggestions.deselect(searchBox.suggestions.selectedItem);
                            searchBox.suggestions.selectedItem = item;
                            searchBox.suggestions.select(item);
                            */
                        }
                    }

                    searchBox.suggestions.length++;
                }


                searchBox.autofillFirstSuggestion = function() {

                    if (searchBox.suggestions.length <= 0)
                        return;

                    searchBox.originalValue = searchBox.value;

                    var start = searchBox.value.length;
                    var end = searchBox.suggestions.firstValue.length;

                    searchBox.value = searchBox.suggestions.firstValue;
                    searchBox.selectRange(start, end);

                }

                searchBox.selectRange = function(start, end) {
                    if (searchBox.setSelectionRange) {
                        searchBox.setSelectionRange(start, end);
                    } else {
                        var range = searchBox.createTextRange();
                        range.moveStart("character", start);
                        range.moveEnd("character", end - searchBox.value.length);
                        range.select();
                    }

                }

                searchBox.suggestions.populateStartsWith = function(dataSource, startsWith) {
                    startsWith = startsWith.toLowerCase();

                    searchBox.suggestions.clear();
                    for (var i = 0; i < dataSource.length; i++) {
                        var current = dataSource[i];

                        if (current.toLowerCase().indexOf(startsWith) == 0 || current.toLowerCase().indexOf("the " + startsWith) == 0) {

                            searchBox.suggestions.append(current);
                            if (box_options.suggestionLimit && searchBox.suggestions.length >= box_options.suggestionLimit)
                                break;
                        }
                    }

                    return searchBox.suggestions.length;
                }


                searchBox.suggestions.selectPrev = function() {
                    if (searchBox.suggestions.selectedItem) {
                        searchBox.suggestions.deselect(searchBox.suggestions.selectedItem);
                        searchBox.suggestions.selectedItem = searchBox.suggestions.selectedItem.prevItem;
                        if (searchBox.suggestions.selectedItem)
                            searchBox.suggestions.select(searchBox.suggestions.selectedItem);
                    } else {
                        searchBox.suggestions.selectedItem = searchBox.suggestions.lastItem;
                        if (searchBox.suggestions.selectedItem)
                            searchBox.suggestions.select(searchBox.suggestions.selectedItem);
                    }
                }

                searchBox.suggestions.selectNext = function() {
                    if (searchBox.suggestions.selectedItem) {
                        searchBox.suggestions.deselect(searchBox.suggestions.selectedItem);
                        searchBox.suggestions.selectedItem = searchBox.suggestions.selectedItem.nextItem;
                        if (searchBox.suggestions.selectedItem)
                            searchBox.suggestions.select(searchBox.suggestions.selectedItem);
                    } else {
                        searchBox.suggestions.selectedItem = searchBox.suggestions.firstItem;
                        if (searchBox.suggestions.selectedItem)
                            searchBox.suggestions.select(searchBox.suggestions.selectedItem);
                    }
                }

                searchBox.suggestions.deselect = function(div) {
                    //div.style.backgroundColor = "#fff";
                    div.style.color = "#000";
                    div.style.textDecoration = "none";
                }


                searchBox.suggestions.select = function(div) {
                    //div.style.backgroundColor = "#00f";
                    //div.style.color = "#fff";
                    div.style.color = "orange";
                    //div.style.color = "blue";
                    div.style.textDecoration = "underline";
                    div.style.cursor = "pointer";

                    /*
                    if (!div.parentNode) {
                    output(
                    "|offsetTop: " + div.offsetTop + "," + itemList.offsetTop + "," + searchBox.suggestions.offsetTop
                    + "|scrollTop: " + div.scrollTop + "," + itemList.scrollTop + "," + searchBox.suggestions.scrollTop
                    + "|clientHeight: " + div.clientHeight + "," + itemList.clientHeight + "," + searchBox.suggestions.clientHeight
                    );
                    return;
                    } else {
                    output(
                    "|offsetTop: " + div.offsetTop + "," + div.parentNode.offsetTop + "," + itemList.offsetTop + "," + searchBox.suggestions.offsetTop
                    + "|scrollTop: " + div.scrollTop + "," + div.parentNode.scrollTop + "," + itemList.scrollTop + "," + searchBox.suggestions.scrollTop
                    + "|clientHeight: " + div.clientHeight + "," + div.parentNode.clientHeight + "," + itemList.clientHeight + "," + searchBox.suggestions.clientHeight
                    );
                    }
                    */


                    var divTop = div.offsetTop - itemList.offsetTop; // -div.parentNode.offsetTop;

                    var text = divTop + "|"
                        +
                        +itemList.scrollTop + "|"
                        + searchBox.suggestions.clientHeight;

                    if (divTop < itemList.scrollTop) {    //selected item is above the "viewing" window
                        text += '|==above';
                        itemList.scrollTop = divTop;
                    } else if ((divTop + searchBoxScrollingFudgeFactor) > (itemList.scrollTop + searchBox.suggestions.clientHeight)) { //below the "viewing" window
                        var newHeight = (divTop + searchBoxScrollingFudgeFactor) - searchBox.suggestions.clientHeight;
                        itemList.scrollTop = newHeight;
                        text += '|==below; new height: ' + newHeight;
                    } else {
                        text += "| " + divTop + " < " + itemList.scrollTop + " | " + divTop + " > " + (itemList.scrollTop + searchBox.suggestions.clientHeight) + "";
                    }

                    //output(text);

                    //return;

                }

                searchBox.suggestions.onkeypress = function(e) {
                    var evt = e || event;
                    output("searchBox.suggestions.onkeyup: " + evt);
                    if (evt.keyCode < 48) {
                        navigateSuggestions(evt);

                    }
                }

                document.onclick = function(e) {

                    for (var i = 0; i < MagRadar.Widgets.length; i++) {
                        if (MagRadar.Widgets[i].searchBox.suggestions) {
                            //output("document.onclick");
                            /*
                            output(//MagRadar.Widgets[i].id + " " +
                            MagRadar.Widgets[i].searchBox.suggestions.length + " " + MagRadar.Widgets[i].searchBox.suggestions.visible);
                            */
                            if (MagRadar.Widgets[i].searchBox.suggestions.visible) {
                                MagRadar.Widgets[i].searchBox.suggestions.clear();
                            }
                        }
                    }
                }



            }

        }

        var createImageSubmit = function() {

            var submit = document.createElement("input");
            submit.setAttribute("type", "image");
            submit.setAttribute("src", MagRadar.Urls.Widgets + "/Images/s.gif");
            submit.setAttribute("title", "submit");
            submit.width = 35;
            submit.height = 23;
            submit.style.margin = "0px 0px";
            submit.style.fontSize = "1px";
            submit.style.color = "#eee";
            submit.style.background = "url(" + MagRadar.Urls.Widgets + "/Images/btn-submit.gif) no-repeat";
            submit.style.display = "block";
            submit.style.cursor = "pointer";
            submit.style.width = submit.width + "px";
            submit.style.height = submit.height + "px";
            submit.style.backgroundPosition = "0px 0px";
            submit.style.marginRight = "0px";
            submit.style.border = "0px";

            submit.onmouseover = function(e) {
                submit.style.backgroundPosition = "0px -" + submit.height + "px";
            }

            submit.onmouseout = function(e) {
                submit.style.backgroundPosition = "0px 0px";
            }

            return submit;

        }

    },

    Searches: Object(),

    SearchResults: Object()

}
