﻿//colors to use for the flyout background
var colorList = new Array("#FEF200", "#C8E2BF", "#AEE0FA", "#B1B1D5", "#F7BB9D", "#DD6245", "#DDBA45", "#DD45AF", "#FCC330")

//Number of columns to display the filters in the flyout
var numColumns = 4;

//The flyout has completed and is shown
function flyOutCompleted(filterId) {

    //Set the loading animation
    jQuery("#" + filterId + "-FlyOutContentDetail").html("<span id='LoadingAnimation'><img id='ajaxAnimation' src='/DesktopModules/Pelco.Products/Images/ajax-loader.gif' alt='' /> Loading Items</span>");

    //Set service parameters
    var parametersAsJSONObject = { "ParentFilterID": filterId };

    //Set the success callback function
    var successCallback = function(data) {
        loadProductFilters(filterId, data.d);
    };
    
    //Call the service
    ServiceCall(jQuery("input[id$='hf_WebsiteDomainPath']").val() + "GetSearchFilterItems", parametersAsJSONObject, successCallback);

}

//The hiding of the flyout has completed
function hideCompleted(filterId) {
    jQuery("#" + filterId + "-FlyOutContentDetail").html("");
}

//Open the overlay
function openOverlay(ProductID) {

    //Set service parameters
    var parametersAsJSONObject = { "ProductID": ProductID };

    //Set the success callback function
    var successCallback = function(data) {
    
        loadProductDetail(data.d);

    };

    //Call the service
    ServiceCall(jQuery("input[id$='hf_WebsiteDomainPath']").val() + "GetProductDetail", parametersAsJSONObject, successCallback);

}

//Populate the Filters
function loadProductFilters(filterId, data) {

    var filtersLevel2 = data;
    //StringBuffer is custom function
    var filtersHTML = new StringBuffer();
    var filtersPath = ""
    var colorIndex = 0;
    
    //Clear the FlyOutContentDetail html
    jQuery("#" + filterId + "-FlyOutContentDetail").html("");
    
    //Loop through the 2nd Level Filters
    for (var i = 0; i <= (filtersLevel2.length - 1); i++) {
        
        //Get Color for the background
        var backgroundColor = "#F1EECA;" // colorList[colorIndex];

         filtersHTML.append("<div style='background-color:" + backgroundColor + "; margin-bottom: 4px;'>" +
                            "<h3 class='filtersLevel2'><a class='Filter' filterID='" + filtersLevel2[i].FilterID + "' filterName='" + filtersLevel2[i].FilterName + "' filterParent='" + filterId + "'>" + filtersLevel2[i].FilterName + "</a></h3>");

        //Increment the colorIndex if we 
        if (colorIndex < (colorList.length - 1)) {
            colorIndex++;
        }

        //Get this levels Filter Children
        var filtersLevel3 = filtersLevel2[i].FilterChildren;

        //Loop through the 3rd Level Filters
        if (filtersLevel3 != undefined) {
        
            //Determine how many levels per column
            var filtersLevel3PerColumn = Math.ceil(filtersLevel3.length / numColumns);
            
            //Counter used to keep track of how many <td>s we have created
            var numColumnsCreated = 0;

            filtersHTML.append("<table cellpadding='0' cellspacing='0' style='width: 100%;'><tr>");

            for (var j = 0; j <= (filtersLevel3.length - 1); j++) {

                //Start a <td>
                if ((j % filtersLevel3PerColumn) == 0) {

                    var style = "padding: 7px; text-align: left; vertical-align: top; width: " + (100 / numColumns) + "%;"
                    
                    //Change style depending on if this is the last column
                    if (numColumnsCreated < (numColumns - 1)) {
                        style = "border-right: dashed 1px Green; " + style;
                    }

                    filtersHTML.append("<td style='" + style + "'>");
                    
                    //Increment number columns counter
                    numColumnsCreated += 1;
                }

                filtersHTML.append("<h4 class='filtersLevel3'><a class='Filter' filterID='" + filtersLevel3[j].FilterID + "' filterName='" + filtersLevel3[j].FilterName + "' filterParent='" + filtersLevel2[i].FilterID + "'>" + filtersLevel3[j].FilterName + "</a></h4>");

                //Get this levels Filter Children
                var filtersLevel4 = filtersLevel3[j].FilterChildren;

                //Loop through the 3rd Level Filters
                if (filtersLevel4 != undefined) {

                    filtersHTML.append("<ul class='columnizedFilters'>");

                    for (var k in filtersLevel4) {

                        filtersHTML.append("<li>" +
                                                "<h5 class='filtersLevel4'><a class='Filter' filterID='" + filtersLevel4[k].FilterID + "' filterName='" + filtersLevel4[k].FilterName + "' filterParent='" + filtersLevel3[j].FilterID + "'>" + filtersLevel4[k].FilterName + "</a></h5>" +
                                           "</li>");
                    }

                    filtersHTML.append("</ul>");
                }

                //End the <td>
                if (((j % filtersLevel3PerColumn) == (filtersLevel3PerColumn - 1)) || ( j == (filtersLevel3.length - 1)) ) {
                    filtersHTML.append("</td>");
                }
            }

            //Add empty <td>s until we have the correct number of columns
            while (numColumnsCreated < numColumns) {
            
                var style = "vertical-align: top; width: " + (100 / numColumns) + "%;"

                //Change style depending on if this is the last column
                if (numColumnsCreated < (numColumns - 1)) {
                    style = "border-right: dashed 1px #004796; " + style;
                }

                filtersHTML.append("<td style='" + style + "'>");
                
                numColumnsCreated += 1;
            }
            
            filtersHTML.append("</tr></table>");

        }

        filtersHTML.append("</div>");
    }

    //Check if we found any filters for the flyout
    if (filtersHTML == "") {
    
        filtersHTML = "<h2 style='margin-bottom: 10px; margin-top: 7px;'>There were no Child Categories found.</h2>";

        //Set the FlyOutContentDetail to the filters
        jQuery("#" + filterId + "-FlyOutContentDetail").html(filtersHTML);
        
    } else {

        //Animation effect for the display of the flyout
        jQuery(".FlyOutContentDetail").css('display', 'none');
        
        //Set the FlyOutContentDetail to the filters
        jQuery("#" + filterId + "-FlyOutContentDetail").html(filtersHTML.toString());

        //Animation effect for the display of the flyout
        jQuery(".FlyOutContentDetail").fadeIn('slow');
        
        //Setup the Click
        setUpFilterClick();

    }

}

//Populate the Product Detail
function loadProductDetail(data) {

    var productDetail = data;

    jQuery("#ProductDetailName").html(productDetail.Name);
    jQuery("#ProductDetailPartNumber").html(productDetail.PartNumber);
    jQuery("#ProductDetailPartNumberAlternate").html(productDetail.PartNumberAlternate);
    jQuery("#ProductDetailProductSpecs").html(productDetail.Specifications);
    jQuery("#ProductDetailDescription").html(productDetail.Description);

    //Clear the Images
    jQuery("#ProductDetailImages").html("");
    
    //Get the Primary Image
    var primaryImage = JSLINQ(productDetail.Images).Where(function(item) { return item.IsPrimary == true; }).Select(function(item) { return item; });

    if (primaryImage.items.length > 0) {
        var primaryImageHTML = "<a href='" + primaryImage.items[0].ImagePath + "' class='imageLinks' title='" + primaryImage.items[0].Description + " <span style=\"margin-left: 20px;\">(Click to Close or Drag)</span>'>" +
                                 "<img src='" + primaryImage.items[0].ImagePath + "' alt='" + primaryImage.items[0].Description + "' style='height: 250px;' />" +
                               "</a>";
    } else {
        var primaryImageHTML = "<img src='/Portals/0/images/PelcoProductNoImage/ImageNotAvailable.png' alt='No Image' style='height: 250px;' />";
    }

    jQuery("#ProductDetailPrimaryImage").html(primaryImageHTML);

    //Get the Other Images
    var otherImages = JSLINQ(productDetail.Images).Where(function(item) { return item.IsPrimary != true; }).Select(function(item) { return item; });

    //StringBuffer is custom function
    var imagesHTML = new StringBuffer();

    //Loop through the other images
    for (var i in otherImages.items) {

        imagesHTML.append("<span class='ProductDetailImage'>" +
                                "<a href='" + otherImages.items[i].ImagePath + "' class='imageLinks' title='" + otherImages.items[i].Description + " <span style=\"margin-left: 20px;\">(Click to Close or Drag)</span>'>" +
                                    "<img src='" + otherImages.items[i].ImagePathThumbnail + "' alt='" + otherImages.items[i].Description + "' style='height: 50px;' />" +
                                "</a>" +
                          "</span>");

    }

    //Set the image html
    jQuery("#ProductDetailImages").html(imagesHTML.toString());

    //Clear the Files
    jQuery("#ProductDetailFiles").html("");

    //StringBuffer is custom function
    var filesHTML = new StringBuffer();

    //Loop through the files
    for (var j in productDetail.Files) {
        filesHTML.append("<a class='ProductDetailFile' href='" + productDetail.Files[j].FilePath + "' target='_blank' alt='" + productDetail.Files[j].Description + "'>" + productDetail.Files[j].Description + "</a><img src='/DesktopModules/Pelco.Products/Images/pdf_icon.png' style='border: none; margin-left: 10px;' /><br/>");
    }

    //Set the file html
    jQuery("#ProductDetailFiles").html(filesHTML.toString());

    //Check if user is logged in
    if (jQuery("input[id$='hf_UserID']").val() > 0) {

        //Check if Product is a favorite
        checkProductIsFavorite(productDetail.ID, jQuery("input[id$='hf_UserID']").val());
    }

    //Save the Product ID
    jQuery("#ProductDetailButtons").data("ProductID", productDetail.ID);

    //Clear out the Quantity
    //jQuery("#Quantity").val("0");

    //Clear out the Item Added
    jQuery("#ItemAdded").html("");

    //Hook up the Zoom Image stuff
    jQuery("a.imageLinks").zoomimage({
        border: 20,
        centered: true,
        hideSource: true, 
        opacity: .6
    });
    
}

//Hover over a product
function productHover() {
    jQuery(".ProductResultsItem").hover(
        function() {
            jQuery(this).addClass("ProductResultsItemHover");
        },
        function() {
            jQuery(this).removeClass("ProductResultsItemHover");
        }
    );
}

//Set up the AutoComplete jQuery
function setUpAutoComplete() {

    //Get hidden field variables
    var proxySearchElement = jQuery("input[id$='hf_WebsiteDomainPath']").val() + "GetAutoComplete";

    //Get the textbox to do the autocomplete on
    var textboxSearchElement = jQuery("input[id$='tbx_SearchField']");
    
    //Set up the jQuery Autocomplete
    jQuery(textboxSearchElement).autocomplete(
        proxySearchElement,
        {
            autoFill: true,
            delay: 15,
            lineSeparator: "~",
            loadingClass: "Loading",
            loadingElement: "LoadingAnimation",
            loadingNotClass: "LoadingNot",
            minChars: 1,
            matchSubset: 1,
            maxItemsToShow: 15
        }
    );

    if (jQuery.trim(textboxSearchElement.val()) != originalValue) {
        textboxSearchElement.addClass("autoCompleteTextFocus");
    }
    
    //Autocomplete textbox got focus
    textboxSearchElement.focus(function() {

        if (jQuery.trim(textboxSearchElement.val()) == originalValue) {
            textboxSearchElement.val('');
            textboxSearchElement.addClass("autoCompleteTextFocus");
        }

    });

    //Autocomplete textbox lost focus
    textboxSearchElement.blur(function() {

        if (jQuery.trim(textboxSearchElement.val()) == '') {
            textboxSearchElement.val(originalValue);
            textboxSearchElement.removeClass("autoCompleteTextFocus");
        }
    });
}

//Set up the FlyOut jQuery
function setUpFlyOut() {

    //Add the mouse event event to show the flyout
    jQuery("div[id$='-FlyOutContainer']").mouseenter(function() {

        //Get the Filter ID from the custom property
        var filterID = jQuery(this).children(".Filter").attr("filterID");

        //Get the Filter Path from the custom property
        var filterPath = jQuery(this).children(".Filter").attr("filterPath");

        //Add the mouse over class
        jQuery("#" + filterID + "-FlyOutTrigger").addClass("FlyOutTriggerHover");

        //Display Flyout
        FlyOut(filterID, 1, "flyOutCompleted(" + filterID + ")");

    });

    //Add the mouse event event to hide the flyout
    jQuery("div[id$='-FlyOutContainer']").mouseleave(function() {

        //Get the Filter ID from the custom property
        var filterID = jQuery(this).children(".Filter").attr("filterID");
        
        //Remove the mouse over class
        jQuery("#" + filterID + "-FlyOutTrigger").removeClass("FlyOutTriggerHover");
        
        //Hide Flyout
        FlyOut(filterID, -1, "hideCompleted(" + filterID + ")");

    });
}

//Set up the Filter Click
function setUpFilterClick() {

    //Remove all previous Click handlers to prevent multiple handlers on one object
    jQuery(".Filter").unbind("click");

    //Add the click event for the Filter Path
    jQuery(".Filter").click(function() {

        //Get the Filter ID from the custom property
        var filterID = jQuery(this).attr("filterID");

        //Get the Filter Name from the custom property
        var filterName = jQuery(this).attr("filterName");

        //Filter link HTML
        var filterLinks = "<a class='Filter' filterID='" + filterID + "' filterName='" + filterName + "'>" + filterName + "</a>  &gt;&gt; ";

        var parentFilter = jQuery("*[filterID='" + jQuery(this).attr("filterParent") + "']");

        //Get all the parents of this filter
        while (parentFilter.length > 0) {

            filterLinks = "<a class='Filter' filterID='" + jQuery(parentFilter).attr("filterID") + "' filterName='" + jQuery(parentFilter).attr("filterName") + "' filterParent='" + jQuery(parentFilter).attr("filterParent") + "'>" + jQuery(parentFilter).attr("filterName") + "</a> &gt;&gt; " + filterLinks;

            var tempFilter = parentFilter;

            parentFilter = "";

            parentFilter = jQuery("*[filterID='" + jQuery(tempFilter).attr("filterParent") + "']");

        }

        filterLinks = filterLinks.substring(0, ((filterLinks.length - 1) - 10));

        //Populate the Products
        postBackGetProducts(filterID, filterLinks);

    });
}

//Add a product to the users favorites
function addProductToFavorites() {

    //Get variables stored in the jQuery data
    var productID = jQuery("#AddToFavorites").data("ProductID");
    var userID = jQuery("#AddToFavorites").data("UserID");

    //Set service parameters
    var parametersAsJSONObject = { "ProductID": productID, "UserID": userID };

    //Set the success callback function
    var successCallback = function(data) {
        //Show the appropriate controls
        jQuery("#AddToFavorites").css("display", "none");
        jQuery("#RemoveFromFavorites").css("display", "block");
    };

    //Call the service
    ServiceCall(jQuery("input[id$='hf_WebsiteDomainPath']").val() + "AddProductToFavorites", parametersAsJSONObject, successCallback);

}

//Remove a product from the users favorites
function removeProductFromFavorites() {

    //Get variables stored in the jQuery data
    var productID = jQuery("#RemoveFromFavorites").data("ProductID");
    var userID = jQuery("#RemoveFromFavorites").data("UserID");

    //Set service parameters
    var parametersAsJSONObject = { "ProductID": productID, "UserID": userID };

    //Set the success callback function
    var successCallback = function(data) {
        //Show the appropriate controls
        jQuery("#RemoveFromFavorites").css("display", "none");
        jQuery("#AddToFavorites").css("display", "block");
    };

    //Call the service
    ServiceCall(jQuery("input[id$='hf_WebsiteDomainPath']").val() + "RemoveProductFromFavorites", parametersAsJSONObject, successCallback);

}

//Check if a product is a user's favorite
function checkProductIsFavorite(ProductID, UserID) {

    //Set service parameters
    var parametersAsJSONObject = { "ProductID": ProductID, "UserID": UserID };

    //Set the success callback function
    var successCallback = function(data) {
        loadIsProductFavorite(ProductID, data.d);
    };

    //Call the service
    ServiceCall(jQuery("input[id$='hf_WebsiteDomainPath']").val() + "IsProductFavorite", parametersAsJSONObject, successCallback);

}

//Populate the Is Product Favorite
function loadIsProductFavorite(ProductID, data) {

    var productIsFavorite = data;

    //Product is a favorite
    if (productIsFavorite  == true) {

        //Show the appropriate controls
        jQuery("#AddToFavorites").css("display", "none");
        jQuery("#RemoveFromFavorites").css("display", "block");

    }
    else {

        //Show the appropriate controls
        jQuery("#RemoveFromFavorites").css("display", "none");
        jQuery("#AddToFavorites").css("display", "block");

    }
    
        //Save variables in the jQuery data
        jQuery("#RemoveFromFavorites").data("ProductID", ProductID);
        jQuery("#RemoveFromFavorites").data("UserID", jQuery("input[id$='hf_UserID']").val());
        
        //Save variables in the jQuery data
        jQuery("#AddToFavorites").data("ProductID", ProductID);
        jQuery("#AddToFavorites").data("UserID", jQuery("input[id$='hf_UserID']").val());

}

//Add Product to the Shopping Cart
function addProductToCart() {

    //show the Add to Cart animation
    jQuery("#AddingToCartAnimation").css("display", "inline");

    //Get variables stored in the jQuery data
    var productID = jQuery("#ProductDetailButtons").data("ProductID");

    //Get the Quantity added
    var Quantity = 1; //jQuery("#Quantity").val();

    //Check if Quantity entered is a number
    if ((!isNaN(Quantity)) && (Quantity > 0)) {

        var jsonShoppingCartProducts = new Array();

        //Set service parameters
        var parametersAsJSONObject = { "ShoppingCartProduct":
                                        { "Product": { "ID": productID }/*,
                                            "Quantity": Quantity,
                                            "SKUNo": SKUNo*/
                                        }
                                     };

        //Set the success callback function
        var successCallback = function(data) {

            //hide the Add to Cart animation
            jQuery("#AddingToCartAnimation").css("display", "none");

            //Show that items were added to the cart
            //jQuery("#ItemAdded").html("You have added " + Quantity + " to your cart.");
            jQuery("#ItemAdded").html("Added item to request.");
            
        };

        //Call the service
        ServiceCall(jQuery("input[id$='hf_WebsiteDomainPath']").val() + "AddProductToShoppingCart", parametersAsJSONObject, successCallback);


    } else {

        //hide the Add to Cart animation
        jQuery("#AddingToCartAnimation").css("display", "none");

        //alert("Please enter a valid quantity.");
    }

}