﻿
var currentElement = null;
var currentItems = null;
var counter = 0;
var totalADSections = 0;

var searchEngineElement = null;

var postExecuteFunction = "";

var currentQuestion = "";

function applyAds(element) {

    imageExists("test.gif");

    currentElement = element;

    var question = getMetaQuestion();

    var applySearchEngine = true;

    if (question.length == 0) {

        var recentAnswerDIV = document.getElementById("recentQuestions");

        if (recentAnswerDIV != null) {

            var recentAnswerLinks = recentAnswerDIV.getElementsByTagName("a");

            if (recentAnswerLinks.length > 0) {

                var itemNbr = parseInt(Math.floor(Math.random() * recentAnswerLinks.length));

                if (itemNbr >= recentAnswerLinks.length) {

                    itemNbr = recentAnswerLinks.length - 1;

                }
                
                question = recentAnswerLinks[itemNbr].firstChild.nodeValue;
                
            }

        }

        if (question.length == 0) {

            question = "Harry Potter";

        }
        
        applySearchEngine = false;

    }

    if (applySearchEngine) {
        Nifty("div#searchEngineItems", "big top transparent");
    }

    currentItems = new Array();

    counter = 0;
    totalADSections = 1;
//    totalADSections = 2;

    currentQuestion = question;

    applyLS(question, "");
    //applyCJ(question, "");

}

function showAdPage(element) {

    currentElement = element;

    currentItems = new Array();
    counter = 0;
    totalADSections = 1;
//    totalADSections = 2;

    var question = getMetaQuestion();

    postExecuteFunction = "showAllItems();";

    currentQuestion = question;

    showMessage("Searching for items...", "popupMessage", "");

    applyLS(question, "../");
//    applyCJ(question, "../");

}

function getMetaQuestion() {

    var metas = document.getElementsByTagName("meta");

    for (var x = 0; x < metas.length; x++) {

        var name = metas[x].name;
        var content = metas[x].content;

        if (name == "Question") {

            return content;

        }

    }

    return "";

}

function buildADHTML() {

    totalADSections--;

    if (totalADSections > 0) {

        return;

    }

    if (currentItems.length == 0) {

        return;

    }

    if (postExecuteFunction.length > 0) {

        eval(postExecuteFunction);

    } else {

        applyHTML(currentElement);

    }

}

function applyHTML(element) {

    var html = "<div id=\"featureAds\" style=\"width:100%\"><span class=\"SectionTitle\">Featured Items (prices might be approximate...)</span> <br /><br />";

    html += "<div>";

    var max = currentItems.length;

    if (max > 30) {

        max = 30;

    }

    for (var x = 0; x < max; x++) {

        var item = currentItems[x];

        html += "<div class=\"ad\"><a href=\"" + item.href + "\" title=\"" + item.desc + " - " + item.price + "\" target=\"_blank\">";
        html += "<img src=\"" + item.imgURL + "\" style=\"width:80px;height:100px;border-style:none;\" onError=\"this.src='noImg.gif';\" /> <br />";

        var name = item.name;

        if (name.length > 30) {

            name = name.substr(0, 30);
            name = name.substr(0, name.lastIndexOf(" ")) + "...";

        }

        html += name + "<br />";
        html += item.price;
        html += "</a></div>";

    }

    html += "</div></div>";

    if (html.length > 0) {

        html += "<div class=\"adShowAll\"><a href=\"deals/" + buildURL(currentQuestion) + ".aspx\">See More Featured Items...</a></div>";

    }

    element.innerHTML = html;

    Nifty("div#featureAds", "big top transparent");

}

function buildURL(question) {

    var allowChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
    var retrn = "";

    for (var x = 0; x < question.length; x++) {

        var c = question.substr(x, 1);

        if (allowChars.indexOf(c.toUpperCase()) > -1) {

            retrn += c;

        }

        if (c == " ") {

            retrn += "_";

        }

    }

    return retrn;

}

var allElement = null;

function showAllItems() {

    allElement = currentElement;

    applyAllItems(null);

}

var stores = new Hashtable();

function applyAllItems(sortBy) {

    closeMessage();

    var html = "";

    html += "<div>";

    var max = currentItems.length;

    if (sortBy != null && sortBy.length > 0) {

        sortItems(sortBy);

    }

    var filterStore = document.getElementById("filterStore");

    var filterStoreSelect = "";

    var selectedStoreIdx = 0;

    if (filterStore != null) {

        selectedStoreIdx = filterStore.selectedIndex;
        filterStoreSelect = filterStore.options[selectedStoreIdx].value;

    }

    var view = "Thumbnails";
    var viewIndex = 0;

    var viewSelect = document.getElementById("view");

    if (viewSelect != null) {

        viewIndex = viewSelect.selectedIndex;
        view = viewSelect.options[viewIndex].value;

    }

    var keepStores = stores.keys.length == 0;

    html += "<table cellspacing=\"0px\" cellpadding=\"5px\" width=\"99%\">";

    if (view == "Details") {

        html += "<tr>";
        html += "<td class=\"itemText\" align=\"center\"><a href=\"javascript:applyAllItems('name');\" title=\"Sort By Item\">Item</a></td>";
        html += "<td class=\"itemText\" align=\"center\"><a href=\"javascript:applyAllItems('desc');\" title=\"Sort By Description\">Description</a></td>";
        html += "<td class=\"itemText\" align=\"center\"><a href=\"javascript:applyAllItems('source');\" title=\"Sort By Advertiser\">Advertiser</a></td>";
        html += "<td class=\"itemText\" align=\"right\"><a href=\"javascript:applyAllItems('priceValue');\" title=\"Sort By Original Price\">Original Price (approx...)</a></td>";
        html += "<td class=\"itemText\" align=\"right\"><a href=\"javascript:applyAllItems('savingValue');\" title=\"Sort By Savings\">Savings (approx...)</a></td>";
        html += "<td class=\"itemText\" align=\"right\"><a href=\"javascript:applyAllItems('finalPrice');\" title=\"Sort By Price\">Price (approx...)</a></td>";
        html += "</tr>";

    } else {

        html += "<tr><td>";

    }

    var rowClass = "";

    for (var x = 0; x < max; x++) {

        var item = currentItems[x];

        var source = item.source;
        var href = item.href;
        var name = item.name;
        var desc = item.desc;
        var price = item.price;
        var imgURL = item.imgURL;

        var priceValue = item.priceValue;
        var saleValue = item.saleValue;

        var savingValue = item.savingValue;
        var savingPercent = item.savingPercent;

        var finalPrice = item.finalPrice;

        if (filterStoreSelect.length > 0 && filterStoreSelect != source) {

            continue;

        }

        if (view == "Details") {

            if (rowClass.length == 0) {

                rowClass = " class=\"alternateRow\"";

            } else {

                rowClass = "";

            }

            html += "<tr" + rowClass + ">";

            html += "<td class=\"itemText\" style=\"200px;\" valign=\"top\">";
            html += "<div class=\"adAll\"><a href=\"" + item.href + "\" title=\"" + item.desc + " - " + item.price + "\" target=\"_blank\">";
            html += "<img src=\"" + item.imgURL + "\" style=\"width:80px;height:100px;border-style:none;display:block;\" onError=\"this.src='noImg.gif';\" />";

            var name = item.name;

            html += name + "<br />";
            html += item.price;
            html += "</a></div>";
            html += "</td>";

            html += "<td class=\"itemText\" valign=\"top\">";
            html += desc;
            html += "</td>";

            html += "<td class=\"itemText\" valign=\"top\">";
            html += source;
            html += "</td>";

            html += "<td class=\"itemText\" valign=\"top\" align=\"right\">";
            html += formatCurrency(priceValue);
            html += "</td>";

            html += "<td class=\"itemText\" valign=\"top\" align=\"right\">";
            html += formatCurrency(savingValue);
            html += "</td>";

            html += "<td class=\"itemText\" valign=\"top\" align=\"right\">";
            html += formatCurrency(finalPrice);
            html += "</td>";

            html += "</tr>";

        } else {

            var tempHTML = "";

            tempHTML += "<div class=\"ad\"><a href=\"" + item.href + "\" title=\"" + item.desc + " - " + item.price + "\" target=\"_blank\">";
            tempHTML += "<img src=\"" + item.imgURL + "\" style=\"width:80px;height:100px;border-style:none;\" onError=\"this.src='noImg.gif'\" /> <br />";

            var name = item.name;

            if (name.length > 30) {

                name = name.substr(0, 30);
                name = name.substr(0, name.lastIndexOf(" ")) + "...";

            }

            tempHTML += name + "<br />";
            tempHTML += item.price;
            tempHTML += "</a></div>";

            html += tempHTML;

        }

        if (keepStores) {

            stores.put(source, source);

        }

    }

    stores.sortByKey();

    var storeDropDown = "Show Advertiser: <select id=\"filterStore\" onchange=\"javascript:applyAllItems();\"><option value=\"\">All</option>";

    for (var x = 0; x < stores.keys.length; x++) {

        var s = stores.keys[x];

        storeDropDown += "<option value=\"" + s + "\">" + s + "</option>"

    }

    storeDropDown += "</select>";

    if (view != "Details") {

        html += "</td></tr>";

    }

    html += "</table>";

    html += "</div></div>";

    var views = "View: <select id=\"view\" onchange=\"javascript:applyAllItems();\"><option value=\"Thumbnails\">Thumbnails</option><option value=\"Details\">Details</option></select>";

    var starting = "<div id=\"featureAllAds\" style=\"width:97%\"><span class=\"SectionTitle\">Featured Items (prices might be approximate...)</span> <br /><br />";

    var topTable = "<table style=\"width:100%\"><tr><td align=\"left\">" + storeDropDown + "</td><td align=\"right\">" + views + "</td>";

    html = starting + topTable + html;

    allElement.innerHTML = html;

    filterStore = document.getElementById("filterStore");

    filterStore.selectedIndex = selectedStoreIdx;

    viewSelect = document.getElementById("view");

    viewSelect.selectedIndex = viewIndex;

    Nifty("div#featureAllAds", "big top transparent");

}

var lastSort = "";

function sortItems(sortBy) {

    for (var x = 0; x < currentItems.length; x++) {

        for (var y = 0; y < currentItems.length - 1; y++) {

            var thisValue = "";
            var nextValue = "";

            switch (sortBy) {

                case 'name':
                    thisValue = currentItems[y].name;
                    nextValue = currentItems[y + 1].name;
                    break;

                case 'desc':
                    thisValue = currentItems[y].desc;
                    nextValue = currentItems[y + 1].desc;
                    break;

                case 'source':
                    thisValue = currentItems[y].source;
                    nextValue = currentItems[y + 1].source;
                    break;

                case 'priceValue':
                    thisValue = currentItems[y].priceValue;
                    nextValue = currentItems[y + 1].priceValue;
                    break;

                case 'savingValue':
                    thisValue = currentItems[y].savingValue;
                    nextValue = currentItems[y + 1].savingValue;
                    break;

                case 'finalPrice':
                    thisValue = currentItems[y].finalPrice;
                    nextValue = currentItems[y + 1].finalPrice;
                    break;

            }            
            

            if (lastSort != sortBy) {

                if (thisValue > nextValue) {

                    var temp = currentItems[y];
                    currentItems[y] = currentItems[y + 1];
                    currentItems[y + 1] = temp;

                }

            } else {

                if (thisValue < nextValue) {

                    var temp = currentItems[y];
                    currentItems[y] = currentItems[y + 1];
                    currentItems[y + 1] = temp;

                }
                
            }

        }

    }

    if (lastSort != sortBy) {

        lastSort = sortBy;

    } else {

        lastSort = "";

    }

}

function applyCJ(question, basePath) {

    new CallBack(basePath + "redirect.ashx?type=CJ&q=" + encodeURIComponent(question), "buildJEItems", "", true);

}

function applyLS(question, basePath) {

    new CallBack(basePath + "redirect.ashx?type=LS&q=" + encodeURIComponent(question), "buildLSItems", "", true);

}

function buildJEItems(response) {

    var cjelements = response.getElementsByTagName("product");

    for (var xcj = 0; xcj < cjelements.length; xcj++) {

        var item = new AdRecord();

        //item.source = "CJ - " + getElementValue(cjelements[xcj], "advertiser-name", "");
        item.source = getElementValue(cjelements[xcj], "advertiser-name", "");
        item.name = handleChars(getElementValue(cjelements[xcj], "name", ""));
        item.desc = handleChars(getElementValue(cjelements[xcj], "description", ""));
        item.priceValue = getElementValue(cjelements[xcj], "price", "");
        item.price = formatCurrency(item.priceValue);
        item.priceValue = parseFloat(item.priceValue);
        //item.imgURL = getElementValue(cjelements[xcj], "image-url", "noImg.gif");
        item.imgURL = getElementValue(cjelements[xcj], "image-url", "");
        item.href = getElementValue(cjelements[xcj], "buy-url", "");

        var salePrice = getElementValue(cjelements[xcj], "sale-price", "0.00");

        item.saleValue = parseFloat(salePrice);

        item.savingValue = 0.00;
        item.savingPercent = 0;

        item.finalPrice = item.priceValue;

        if (parseFloat(salePrice) > 0) {

            item.price = formatCurrency(salePrice);

            item.finalPrice = parseFloat(salePrice);

            item.savingValue = roundNumber(item.priceValue - item.saleValue, 2);

            var savings = parseInt(Math.floor((item.savingValue / item.priceValue) * 100));

            if (savings > 0) {

                item.price += " - Save " + savings + "%";
                item.savingPercent = savings;

            }

        }

        item.desc = item.name + " (" + item.price + ") - " + item.desc;

        if (imageExists(item.imgURL)) {

            currentItems[counter++] = item;

        }

    }

    buildADHTML();

}

function buildLSItems(response) {

    var cjelements = response.getElementsByTagName("item");

    for (var xcj = 0; xcj < cjelements.length; xcj++) {

        var item = new AdRecord();

        //item.source = "LS - " + getElementValue(cjelements[xcj], "merchantname", "");
        item.source = getElementValue(cjelements[xcj], "merchantname", "");
        item.name = handleChars(getElementValue(cjelements[xcj], "productname", ""));
        item.desc = handleChars(getElementValue(cjelements[xcj].getElementsByTagName("description")[0], "long", item.name));
        item.priceValue = getElementValue(cjelements[xcj], "price", "");
        item.price = formatCurrency(item.priceValue);
        item.priceValue = parseFloat(item.priceValue);
        //item.imgURL = getElementValue(cjelements[xcj], "image-url", "noImg.gif");
        item.imgURL = getElementValue(cjelements[xcj], "imageurl", "");
        item.href = getElementValue(cjelements[xcj], "linkurl", "");

        var salePrice = "0.00";

        item.saleValue = parseFloat(salePrice);

        item.savingValue = 0.00;
        item.savingPercent = 0;

        item.finalPrice = item.priceValue;

        if (parseFloat(salePrice) > 0) {

            item.price = formatCurrency(salePrice);

            item.finalPrice = parseFloat(salePrice);

            item.savingValue = roundNumber(item.priceValue - item.saleValue, 2);

            var savings = parseInt(Math.floor((item.savingValue / item.priceValue) * 100));

            if (savings > 0) {

                item.price += " - Save " + savings + "%";
                item.savingPercent = savings;

            }

        }

        item.desc = item.name + " (" + item.price + ") - " + item.desc;

        if (imageExists(item.imgURL)) {

            currentItems[counter++] = item;

        }

    }

    buildADHTML();

}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function AdRecord() {

    var source = "";
    var href = "";
    var name = "";
    var desc = "";
    var price = 0.0;
    var imgURL = "";

    var priceValue = 0.0;
    var saleValue = 0.0;

    var savingValue = 0.0;
    var savingPercent = 0.0;

    var finalPrice = 0.0;

}

function getElementValue(element, item, defaultValue) {

    var items = element.getElementsByTagName(item);

    if (items == null || items.length == 0) {

        return defaultValue;

    }

    if (items[0].firstChild == null) {

        return defaultValue;

    }

    return items[0].firstChild.nodeValue;

}

function formatCurrency(num) {

    num = "" + num;

    if (num.length == 0) {
    
        return num;
        
    }

    if (num.indexOf(".") == -1) {

        num = num + ".00";
        
    }

    var parts = num.split(".");

    while (parts[1].length < 2) {
        parts[1] += "0";
    }

    var formatted = "";
    var c = 0;

    for (var x = parts[0].length - 1; x >= 0; x--) {

        if (c == 3) {

            formatted = "," + formatted;
            c = 1;

        } else {

            c++;

        }

        formatted = parts[0].substr(x, 1) + formatted;

    }

    return "$" + formatted + "." + parts[1];

}

function showContact() {

    var html = "<table width=\"450px\">";

    html += "<tr><td colspan=\"2\">Provide us with the following and we will get back with you as soon as possible.<br /><hr /></td></tr>"
    html += "<tr><td width=\"100px\">Name:</td><td><input type=\"text\" id=\"ContactName\" style=\"width:500px;\"/></td></tr>";
    html += "<tr><td width=\"100px\">Email:</td><td><input type=\"text\" id=\"ContactEmail\" style=\"width:500px;\"/></td></tr>";
    html += "<tr><td width=\"100px\">Subject:</td><td><input type=\"text\" id=\"ContactSubject\" style=\"width:500px;\"/></td></tr>";
    html += "<tr><td width=\"100px\" valign=\"top\">Message:</td><td><textarea id=\"ContactMessage\" style=\"width:500px;height:200px;\"></textarea></td></tr>";

    html += "</table>";

    showMessage(html, "popupMessage", "<a href=\"javascript:submitContact();\">Submit</a>");

}

function submitContact() {

    var messages = "";

    if (!isFieldEntered("ContactName")) {
        messages += "Contact name is needed.<br />";
    }

    if (!isFieldEntered("ContactEmail")) {
        messages += "Contact email address is needed.<br />";
    }

    if (!isFieldEntered("ContactSubject")) {
        messages += "Subject must be entered.<br />";
    }

    if (!isFieldEntered("ContactMessage")) {
        messages += "Message must be entered.<br />";
    }

    if (messages.length > 0) {
        setPopupErrorMessage(messages);
        return;
    }

    var content = "Action=SubmitContactInfo" + getMessagePopupFieldContent();

    new CallBack(baseAJAXDir + "ajax.ashx", "handleContactResponse", content, true);

}

function handleContactResponse(response) {

    showMessage("Thanks for your response.", "popupMessage", "");

}

function addBookMark() {

    var title = document.title;
    var url = document.URL;

    if (window.sidebar) {

        window.sidebar.addPanel(title, url, "");

    } else if (window.external) {

        window.external.AddFavorite(url, title);

    }

}

function handleChars(str) {

    return str.replace(/\"/g, "&quot;");

}

function isFieldEntered(fieldId) {

    var textBox = document.getElementById(fieldId);

    if (textBox.value.length == 0) {

        return false;

    } else {

        return true;

    }

}

function imageExists(url) {

    return true;

}





