﻿// global variables for searchbox, dropdown and popout controls

//Message for NO Results.
var SorryMessage = 'Sorry, nothing found.';
/*---------------------------------------------*/

var gssSearchbox;
var gssPopoutDiv;
var gssDistilleryPopoutDiv;
// on page load grab elements by id
function DefineOnLoad() {
    //debugger;
    gssPopoutDiv = document.getElementById('gssPopoutDiv');
    gssDistilleryPopoutDiv = document.getElementById('gssDistilleryPopoutDiv');
    gssSearchbox = document.getElementById('ucSearch_ucSearch_searchHeadInput');
    if (gssSearchbox == null) 
    {
        gssSearchbox = document.getElementById('ctl00_ucSearch_ucSearch_searchHeadInput');
    }
}
// hides popout div when user clicks elsewhere on the page
document.onclick = check;
function check(e) {
    var target = (e && e.target) || (event && event.srcElement);
    var parent = checkParent(target);
    if (parent) { gssPopoutDiv.style.display = 'none'; }
    if (target == gssSearchbox) { gssPopoutDiv.style.display = 'block'; }
}
// allows you to click child nodes to the popout div without it hiding
function checkParent(t) {
    while (t.parentNode) {
        if (t == document.getElementById('gssPopoutDiv')) { return false }
        t = t.parentNode
    }
    return true;
}
// triggered on keyup of searchbox
function searchboxChange() {
    // capture searchbox value
    debugger;
    var txt = removeSpecialCharacters(gssSearchbox.value);
    gssPopoutDiv.style.visibility = "hidden";
    gssPopoutDiv.innerHTML = "";
    // if search term is not a single character, trigger google search (protects against insane overflow from searching "a")
    if (txt.length > 1) {
        // performs Google search and processes returned xml file
        //debugger;

        //PageMethods.ReadXML(txt, OnRequestComplete, OnRequestError);
        $.ajax({
            type: "POST",
            url: GetDomainName(window.location.href) + "Webservice/GoogleXML.asmx/ReadXML",
            
            data: "{'searchQuery':'" + txt + "'}",
            success: function(data) {
                OnRequestComplete(data, "", "ReadXML");
            }
            ,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(e, textStatus, errorThrown) {
                OnRequestError();
            }
        });



        // search message to user
        gssPopoutDiv.innerHTML = "<div id='googleResults'><h3>Searching...</h3></div>";
        // display popout
        gssPopoutDiv.style.visibility = "visible";
    }
}
// called when ajax response is recieved
function OnRequestComplete(result, userContext, methodName) {
    // div to contain all results
    //debugger;
    var googleDiv = document.getElementById('googleResults');
    // keep track of current category (distilleries, regions, bottles, etc)
    var category = "";
    // count number of results per category
    var categoryCount;
    // count the number of distilleries
    var distilleryCounter = 0;
    // string to capture a single result
    var resultString;
    // contains excess results to be stored in a hidden div
    var hideString = "";
    // container generated for hidden results
    var hiddenDiv;
    // result[0] contains the value that initiated the search. 

    // stops the display of unwanted results when user is typing quickly
    if (result.d[0] == gssSearchbox.value) {
        // adds distillery popout to results div
        googleDiv.innerHTML = "<div id='gssDistilleryDiv'></div>";
        // for each result returned
        for (var i = 0; i < result.d[1][result.d[1].length - 1]; i++) {
            // if the results category is not equal to the last category
            if (result.d[5][i] != category) {
                // attach hide button if the last category had more than five results
                if (categoryCount > 5) { googleDiv.innerHTML += "<div id='gssMoreResults" + category + "' style='display: none;'>" + hideString + "<a href='#' onClick='gssHide(\"" + category + "\",\"other\");' ><div class='gssHover' id='" + category + "HideButton'>Show fewer " + category.toLowerCase() + " &nbsp; <img src='/images/arrUp.gif'></div></a></div>"; }
                // as this is a new category, clear hideString
                hideString = "";
                // displays divider if this is not the first category
                if (category != "") { googleDiv.innerHTML += "<hr>"; }
                // set result's category as the current one
                category = result.d[5][i];
                // add category header
                googleDiv.innerHTML += "<h3>" + result.d[5][i] + "</h3>";
                // reset category counter
                categoryCount = 0;
            }

            // if category is distillery
            if (category == "Distilleries") {
                // increment distillery count
                distilleryCounter = distilleryCounter + 1;
                // if distillery has more than one bottle, append s
                var bottles = "s";
                if (result.d[1][distilleryCounter - 1] == 1) { bottles = ""; }
                // attach distillery listing with bottle count and ability to hover to display bottles
               // debugger;
                //dickie distillery starts here
                googleDiv.innerHTML += "<div class='gssHover' onMouseOver='gssShow(\"" + distilleryCounter + "\",\"distillery\");' onMouseOut='gssHide(\"" + distilleryCounter + "\",\"distillery\");'><a href='" + result.d[2][i] + "'><div class='csImage' style='padding:5px;'>" + result.d[7][i] + "</div><div class='gssTitleHover' style='width:280px;'><div class='gssTitle'><h4>" + result.d[3][i] + " (" + result.d[1][distilleryCounter - 1] + " bottle" + bottles + ")</h4></div><div class='gssDescription'>" + result.d[4][i] + "</div></div></a></div><div class=\"cb\"></div>";
                // grab distillery popout div
                var gssDistilleryDiv = document.getElementById('gssDistilleryDiv');
                // creates container inside the distillery popout for this distilleries listings
                gssDistilleryDiv.innerHTML += "<div id='gssMoreResults" + distilleryCounter + "' style='display: none; padding-top: 10px;' onMouseOver='gssShow(\"" + distilleryCounter + "\",\"distillery\");' onMouseOut='gssHide(\"" + distilleryCounter + "\",\"distillery\");'></div></div>";
                // grab the distillery results container just created
                hiddenDiv = document.getElementById("gssMoreResults" + distilleryCounter);
                // sets flag
                var distilleryBottles = 1;
                // distillery has bottles
                var distilleryHasBottles = 1;
                // sets distillery as current distillery
                var currentDistillery = result.d[3][i];
                // loop while still the same distillery
                while (distilleryBottles == 1) {
                    // check if still the same distillery
                    if (result.d[5][i + 1] == currentDistillery) {
                        distilleryHasBottles = 2;
                        // increase count to move to next listing
                        i = i + 1;
                        //debugger;
                        // capture bottle listing
                        hiddenDiv.innerHTML += "<div class='gssHover'><a href='" + result.d[2][i] + "'><div class='csImage'>" + result.d[7][i] + "</div><div class='gssTitleHover'><div class='gssTitle'>" + result.d[3][i] + "</div><div class='gssDescription'>" + result.d[4][i] + "</div></div><div class='gssPrice'>" + result.d[6][i] + "</div></a></div><div class=\"cb\"></div>";
                    }
                    // if not the same distillery; flag and close container
                    else {
                        if (distilleryHasBottles == 1) {
                            hiddenDiv.innerHTML += "<h3>This distillery has no bottles</h3>";
                        }
                        distilleryBottles = 2;
                        hiddenDiv.innerHTML += "</div>";
                    }
                }
            }
            // if not distillery
            else {
                // increment number of results in this category
                categoryCount = categoryCount + 1;
                // when count reaches six append show more button
                if (categoryCount == 6) { googleDiv.innerHTML += "<br><a href='#' onClick='gssShow(\"" + category + "\",\"other\");' ><div id='" + category + "ShowButton'>Show more " + category.toLowerCase() + "&nbsp; <img src='/images/arrDown.gif'></div></a>"; }
                // capture result
                //dickie //show std bottles
                //debugger;
                resultString = "<div class='gssHover'><a href='" + result.d[2][i] + "'><div class='csImage'>" + result.d[7][i] + "</div><div class='gssTitleHover'><div class='gssTitle'>" + result.d[3][i] + "</div><div class='gssDescription'>" + result.d[4][i].replace("</...","...") + "</div></div><div class='gssPrice'>" + result.d[6][i] + "</div></a></div><div class=\"cb\"></div>";
                
                
                
                // if over five results, add to hide string
                if (categoryCount > 5) { hideString += resultString; }
                // otherwise append to results div
                else { googleDiv.innerHTML += resultString; }
            }
        }
        // add hide button and hidden results to the last category in the loop before closing
        if (categoryCount > 5) { googleDiv.innerHTML += "<div id='gssMoreResults" + category + "' style='display: none;'>" + hideString + "<a href='#' onClick='gssHide(\"" + category + "\",\"other\");' ><div class='gssHover' id='" + category + "HideButton'>Show fewer " + category.toLowerCase() + " &nbsp; <img src='/images/arrUp.gif'></div></a></div><div class=\"cb\"></div>"; }
        // if no results, cry about it
        if (result.d[1] == 0) { googleDiv.innerHTML += "<h3>" + SorryMessage +"</h3>"; }
    }
}
// called if ajax response fails (fail silently)
function OnRequestError(error, userContext, methodName) { }
// hides show more button and displays distillery popout
function gssShow(category, type) {
    // displays div containing hidden results
    var div = document.getElementById('gssMoreResults' + category);
    div.style.display = 'block';
    // if distillery popout
    if (type == 'distillery') {
        // make popout visible
        var gssDistilleryDiv = document.getElementById('gssDistilleryDiv');
        gssDistilleryDiv.style.visibility = "visible";
        // position popout
        if (category == 1) {
            var distilleryDivPosition = 22;
        }
        else {
            var distilleryDivPosition = (category * 50) - 10;
        }
        gssDistilleryDiv.style.marginTop = distilleryDivPosition + "px";
    }
    // else if show more button
    else {
        // hide show more button
        var button = document.getElementById(category + 'ShowButton');
        button.style.display = 'none';
    }
}
// displays show more button and hides distillery popout
function gssHide(category, type) {
    // hide div containing more results
    var div = document.getElementById('gssMoreResults' + category);
    div.style.display = 'none';
    // if distillery popout
    if (type == 'distillery') {
        // hide distillery popout
        var gssDistilleryDiv = document.getElementById('gssDistilleryDiv');
        gssDistilleryDiv.style.visibility = "hidden";
    }
    else {
        // display show more button
        var button = document.getElementById(category + 'ShowButton');
        button.style.display = 'block';
    }
}

function removeSpecialCharacters(rv) {
    // replacing with space allows the camelcase to work a little better in most cases.
    rv = rv.replace("\\", "");
    rv = rv.replace("(", "");
    rv = rv.replace(")", "");
    rv = rv.replace("/", "");
    rv = rv.replace("-", " ");
    rv = rv.replace(",", " ");
    rv = rv.replace(">", "");
    rv = rv.replace("<", "");
    rv = rv.replace("-", " ");
    rv = rv.replace("&", " ");
    rv = rv.replace(":", "");
    rv = rv.replace("\"", "");
    rv = rv.replace("%", " ");
    rv = rv.replace("*", "");
    return rv;

}

