// Global variables to keep track of which type of product browser
// we will be using (markets, categories or brands) and the value for
// each to use in the search
SEARCHTYPE = "";
SEARCHKEY = "";
SEARCHKEYVAL = "";


function setupProductBrowser() {
    // check out if the browser doesn't
    if (!document.getElementById) return false;
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById("browser")) return false;

    // determine if we are searching by categories, markets or brands
    // using predefined URLs
    setSearchType();
    
    // assign onclick event handlers to each of the columns so that
    // they can grab the next bit of information, where appropriate

    // if we're on the categories browser, then the categories column
    // wouldn't exist
    if (document.getElementById("browse-cats")) {
        assignCategoryLinks();
    }

    // but these columns will always be on the page
    assignSubCategoryLinks();
    assignProductLinks();
}


function assignCategoryLinks() {
    var catCol = document.getElementById("browse-cats");
    var catLnks = catCol.getElementsByTagName("a");

    // loop through all links, adding event handlers on each
    for (var i=0; i<catLnks.length; i++) {
        catLnks[i].onclick = function() {
            getSubCategories(this.href);
            return false;
        }
    }
}


function assignSubCategoryLinks() {
    var subcatCol = document.getElementById("browse-subcats");
    var subcatLnks = subcatCol.getElementsByTagName("a");

    // loop through all links, adding event handlers on each
    for (var i=0; i<subcatLnks.length; i++) {
        subcatLnks[i].onclick = function() {
            getProducts(this.href);
            return false;
        }
    }
}


function assignProductLinks() {
    var prodCol = document.getElementById("browse-products");
    var prodLnks = prodCol.getElementsByTagName("a");

    // loop through all links, adding event handlers on each
    for (var i=0; i<prodLnks.length; i++) {
        prodLnks[i].onclick = function() {
            getProductInfo(this.href);
            return false;
        }
    }
}


function setSearchType() {
    // get the URL of the page we are on
    var url = location.href;

    // split the URL by forward slashes
    urlPieces = url.split('/');

    // the search type will always be the fifth item:
    // i.e., http://www.kpg-industrial.com/products/brands/
    switch (urlPieces[4]) {
        case "brands":
            SEARCHTYPE = 0;
            SEARCHKEY = "brandCleanName";
            break;
        case "markets":
            SEARCHTYPE = 1;
            SEARCHKEY = "marketCleanName";
            break;
        case "categories":
            SEARCHTYPE = 2;
            SEARCHKEY = "categoryCleanName";
            break;
        default:
            break;
    }

    // the search key (the brand clean name, the category clean name or
    // the market clean name) will always be the sixth item
    SEARCHKEYVAL = urlPieces[5];
}


function getSubCategories(url) {
    // make url passed available globally so that the displaySubCategories
    // function can use it to reassign URLs
    CATLNK = url;

    // split up the URL to get the clean name for the category, as this 
    // will be passed to the AJAX call to get the list of associated
    // sub-categories (clean name is always second-last item due to ending
    // slash)
    var urlPieces = url.split('/');
    var catCleanName = urlPieces[urlPieces.length-2];

    // do the AJAX calls using the DWR libraries
    // first set up values to pass as attributes to the call
    var map = {};
    map.productAttribute = SEARCHTYPE;
    map.categoryCleanName = catCleanName;
    map[SEARCHKEY] = SEARCHKEYVAL;

    // now do the call itself, returning the data to the
    // displaySubCategories() function to populate the sub-categories
    // column in the browser
    JProductByAttribute.getDwrSubCategoryListMap(map, displaySubCategories);

    // while we wait, let's set the category we clicked on as the
    // currently selected item
    highlightCurrent("browse-cats", CATLNK);
}


function getProducts(url) {
    // make url passed available globally so that the displayProducts
    // function can use it to reassign URLs
    SUBCATLNK = url;

    // split up the URL to get the clean name for the category and subcategory,
    // as this will be passed to the AJAX call to get the list of associated
    // products
    var urlPieces = url.split('/');
    var catCleanName = urlPieces[urlPieces.length-3];
    var subcatCleanName = urlPieces[urlPieces.length-2];

    // do the AJAX calls using the DWR libraries
    // first set up values to pass as attributes to the call
    var map = {};
    map.productAttribute = SEARCHTYPE;
    map.categoryCleanName = catCleanName;
    map.subCategoryCleanName = subcatCleanName;
    map[SEARCHKEY] = SEARCHKEYVAL;

    // now do the call itself, returning the data to the
    // displayProducts() function to populate the products
    // column in the browser
    JProductByAttribute.getDwrProductByCategoryListMap(map, displayProducts);

    // while we wait, let's set the sub-category we clicked on as the
    // currently selected item
    highlightCurrent("browse-subcats", SUBCATLNK);
}


function getProductInfo(url) {
    // note - no need to set the URL here globally, as the format of the
    // product detail page doesn't require the category, sub-category, etc.

    // split up the URL to get the clean name for the category, subcategory,
    // and product, as this will be passed to the AJAX call to get the product
    // information
    var urlPieces = url.split('/');
    var catCleanName = urlPieces[urlPieces.length-4];
    var subcatCleanName = urlPieces[urlPieces.length-3];
    var productCleanName = urlPieces[urlPieces.length-2];

    // do the AJAX calls using the DWR libraries
    // first set up values to pass as attributes to the call
    var map = {};
    map.productAttribute = SEARCHTYPE;
    map.categoryCleanName = catCleanName;
    map.subCategoryCleanName = subcatCleanName;
    map.productCleanName = productCleanName;
    map[SEARCHKEY] = SEARCHKEYVAL;

    // now do the call itself, returning the data to the
    // displayProducts() function to populate the products
    // column in the browser
    JProductByAttribute.getDwrProductMap(map, displayProductInfo);

    // while we wait, let's set the product we clicked on as the
    // currently selected item
    highlightCurrent("browse-products", url);
}


function displaySubCategories(response) {
    // parse through the data and make it into an array to loop through
    var results = createArry(response, 'subcats');

    // grab the appropriate div to insert this list into
    var subcatCol = document.getElementById("browse-subcats");
    var subcatDiv = subcatCol.getElementsByTagName("div")[0];

    // clear out whatever is in there
    subcatDiv.innerHTML = "";

    // start a string that we'll insert in to the column at the end
    var str = "";

    // start inserting!
    if (results['subcats'].length == 0) {
        str = "<p class=\"error\">No subcategories found</p>";
    } else {

        // start the unordered list
        str = "<ul>";

        // loop through all subcategories, assigning them links and actions
        // to load the next set of data
        for (var i=0; i<results['subcats'].length; i++) {
            str += "<li><a href=\"" + CATLNK +
                    results['subcats'][i].categoryCleanName + "/\">" +
                    results['subcats'][i].categoryName + "</a></li>";
        }

        // finish up the list
        str += "</ul>";
    }

    // now add the string of markup to the subcategories column
    subcatDiv.innerHTML = str;

    // with everything in place, reassign the links to the subcategories
    // column
    assignSubCategoryLinks();

    // add the appropriate message to the products column to prompt the
    // user to choose a subcategory
    var prodCol = document.getElementById("browse-products");
    var prodDiv = prodCol.getElementsByTagName("div")[0];
    prodDiv.innerHTML = "<p class=\"wait\">Please choose a Sub-Category</p>";

    // and while we're at it, completely eliminate anything in the product
    // info column as well
    var prodInfoCol = document.getElementById("browse-info");
    var prodInfoDiv = prodInfoCol.getElementsByTagName("div")[0];
    prodInfoDiv.innerHTML = "";
}


function displayProducts(response) {
    // parse through the data and make it into an array to loop through
    var results = createArry(response, 'products');

    // grab the appropriate div to insert this list into
    var productsCol = document.getElementById("browse-products");
    var productsDiv = productsCol.getElementsByTagName("div")[0];

    // clear out whatever is in there
    productsDiv.innerHTML = "";
    
    // start a string that we'll insert in to the column at the end
    var str = "";

    // start inserting!
    if (results['products'].length == 0) {
        str = "<p class=\"error\">No products found</p>";
    } else {
        // start the unordered list
        str = "<ul>";

        // loop through all products, assigning them links and actions
        // to load the next set of data
        for (var i=0; i<results['products'].length; i++) {
            str += "<li><a href=\"" + SUBCATLNK +
                    results['products'][i].productCleanName + "/\">" +
                    results['products'][i].productName + "</a></li>";
        }

        // finish up the list
        str += "</ul>";
    }

    // now add the string of markup to the products column
    productsDiv.innerHTML = str;

    // with everything in place, reassign the links in the products
    // column
    assignProductLinks();

    // now, if the result is only one product, let's save some time by
    // just marking the product as current and loading the product info
    // into the info column, avoiding another call to the database
    if (results['products'].length == 1) {
        var prodURL = SUBCATLNK +
                      results['products'][0].productCleanName + "/";
        displaySingleProductInfo(response, prodURL);
    } else {
        // add the appropriate message to the product info column to prompt the
        // user to choose a product
        var infoCol = document.getElementById("browse-info");
        var infoDiv = infoCol.getElementsByTagName("div")[0];
        infoDiv.innerHTML = "<p class=\"wait\">Please choose a Product</p>";
    }
}


function displayProductInfo(response) {
    // parse through the data and make it into an array to loop through
    var results = createArry(response, 'info');

    // grab the appropriate div to insert this list into
    var infoCol = document.getElementById("browse-info");
    var infoDiv = infoCol.getElementsByTagName("div")[0];

    // clear out whatever is in there
    infoDiv.innerHTML = "";

    // start a string that we'll insert in to the column at the end
    var str = "";

    // start inserting!
    if (results['info'].length == 0) {
        str = "<p class=\"error\">No product info found</p>";
    } else {
        // start the unordered list
        str = "<ul>";

        // loop through all product info, assigning them links
        for (var i=0; i<results['info'].length; i++) {
            str += "<h3><a href=\"/products/" +
                    results['info'][i].productCleanName + "/\">" +
                    results['info'][i].productName + "</a></h3>";
            str += "<div class=\"imgpreview\"><a href=\"/products/" +
                    results['info'][i].productCleanName + "/\">";
            str += "<img src=\"/images/products/img-sm/" +
                    results['info'][i].productImage + ".gif\" alt=\"" +
                    results['info'][i].productName + "\" />";
            str += "</a></div>";
            str += "<p>" + results['info'][i].productDescription + "</p>";
            str += "<p class=\"more\"><a href=\"/products/" +
                    results['info'][i].productCleanName + "/\">" +
                   "More info</a></p>";
        }

        // finish up the list
        str += "</ul>";
    }

    // now add the string of markup to the product info column
    infoDiv.innerHTML = str;
}


function displaySingleProductInfo(response, lnk) {
    // highlight the product chosen
    highlightCurrent("browse-products", lnk);

    // now display the product information
    displayProductInfo(response);
}


function highlightCurrent(colId, curLnk) {
    // get a reference to the column
    var col = document.getElementById(colId);

    // loop through all links within the column, looking for the one
    // with the passed link.  If it has it, assign a class to it's
    // parent to make it current
    var lnks = col.getElementsByTagName("a");

    for (var i=0; i<lnks.length; i++) {
        if (lnks[i].href == curLnk) {
            lnks[i].parentNode.className = "current";
        } else if (lnks[i].parentNode.className == "current") {
            // we may have already done a search, so we want to remove
            // what has already been assigned as current
            lnks[i].parentNode.className = "";
        }
    }
}


function createArry(resp, name) {
    var ar = {};
    ar[name] = Array();
    var n = 0;

    // do we even have data?
    if (resp.length) {

        // loop through all items, assigning them as items in the array
        for (var prop in resp) {
		//because of prototype.js, it extends object and gives an object all sorts of functions
		//, we need to ignore those when we loop
		//values from dwr are numbered 0,1,2,3,...
	     if(isNaN(prop)==false){
		//alert(prop + " " + resp[prop]);
              ar[name][n] = resp[prop];
		n++;
	     }
            
        }

    } else if (resp && (resp != '')) {
        ar[name][0] = resp;
    }

    return ar;
}


// run the setup function when the body of the page loads
addLoadEvent(setupProductBrowser);

