﻿/////////////////////////////////////////////////////////
// Variables
/////////////////////////////////////////////////////////
var filters = "";
var c = new Array();
var isEmbedded = false;

/////////////////////////////////////////////////////////
// Load Data
/////////////////////////////////////////////////////////
function LoadConsumerProductSearchResults(manufacturer, model, certifications,
            colors, categories, orientations, solutionTypes, filterReload) {
    if (filterReload) {
        PullFilters(manufacturer, model);
    }
    $.ajax({
        type: "POST",
        url: '/WebServices/ConsumerProductService.asmx/GetConsumerProductSearch',
        data: "{ 'manufacturer': '" + manufacturer + "', 'model' : '" + model + "', 'certifications' : '" + certifications + "', 'colors' : '" + colors + "', 'categories' : '" + categories +
            "', 'orientations' : '" + orientations + "', 'solutionTypes' : '" + solutionTypes + "', 'sortBy' : '' }",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('#lblNoResults').text('Total Result: ' + msg.d.Items.length);
            LoadSearchResults(msg.d);
        },
        error: function (xhr, textStatus, thrownError) {
            alert("/WebServices/ConsumerProductService.asmx/GetConsumerProductSearch Service Error - Unable to pull product details. TextStatus: "
                    + textStatus + " ThrownError: " + thrownError);
        }
    });
};

function LoadSearchResults(searchResultsObj) {
    var title = 'Info Not Available';
    var description = 'Info Not Available';
    var smallImage = '<img id="NoImg" src="http://cdn.chiefmfg.com/chiefProducts/NA-P_small.jpg" alt="" title="No Image" />';
    var itemHtml = "";
    
    // Remove existing results
    $('#hiddenResult').html('');

    $.each(searchResultsObj.Items, function () {
        // Append into table
        $('#hiddenResult').append(GenerateItemListing(this, searchResultsObj, isEmbedded));
    });

    // Load Pagger
    $('#divUpdateProgress').hide();
    initPaginations();
};

/////////////////////////////////////////////////////////
// Control Events
/////////////////////////////////////////////////////////
function BindSearchEvents() {
    c = document.getElementsByTagName('input');
    for (var i = 0; i < c.length; i++) {
        if (c[i].type == 'checkbox' && c[i].name.indexOf('chkProductSeriesCompare', 0) > 0) {
            c[i].checked = false;
        }
    }

    // Toggles Search Filters Drop Panel
    $(".btn-slide").live('click', function () {
        $("#divSearchFilters").slideToggle("slow");
        $(this).toggleClass("active"); 
        return false;
    });
        
    // Check for hash values
//    if ($.address.value().length > 1) {
//        SetFilters();

//        //Submit Filters 
//        $("#imgFilterResults").trigger('click');
//    }

    // Collect selected filters on button click
    $("#imgFilterResults").click(function () {
        if (!isEmbedded) {
            $("#mfEmbeddedFilters input:checked").each(function (id) {
                filters += "||" + $(this).attr('id');
            });

            // Add filters to hash
            //$.address.value(filters);

            // Clear filters for next round
            filters = "";
        }
    });

    $('#imgFilterResults').live('click', function () {
        var certifications = '';
        var colors = '';
        var orientations = '';
        var solutionTypes = '';
        var categories = '';

        $('#mfEmbeddedFilters h2').each(function () {
            if ($(this).attr('id').indexOf('Certification') > 0) {
                $('#divCertifications input:checked').each(function () {
                    certifications += $(this).attr('id') + ',';
                });
            }
            else if ($(this).attr('id').indexOf('Color') > 0) {
                $('#divColors input:checked').each(function () {
                    colors += $(this).attr('id') + ',';
                });
            }
            else if ($(this).attr('id').indexOf('Orientation') > 0) {
                $('#divOrientations input:checked').each(function () {
                    orientations += $(this).attr('id') + ',';
                });
            }
            else if ($(this).attr('id').indexOf('SolutionType') > 0) {
                $('#divSolutionTypes input:checked').each(function () {
                    solutionTypes += $(this).attr('id') + ',';
                });
            }
            else if ($(this).attr('id').indexOf('Categories') > 0) {
                $('#divCategories input:checked').each(function () {
                    categories += $(this).attr('id') + ',';
                });
            }
        });

        var manufacturer = $('#ddManufacturers :selected').text();
        var model = $('#ddModels :selected').text();
        LoadConsumerProductSearchResults(manufacturer, model, certifications,
            colors, categories, orientations, solutionTypes, false);        

        // Close filter box
        $('.btn-slide').trigger('click');
    });
};

function initPaginations() {
    initPagination('hiddenResult', 'pagination', 'galleryItems', $('#pageSize').val());
}

//////////////////////////////////////////////
// Search Filters
//////////////////////////////////////////////

// Load Search Filters
function PullFilters(manufacturer, model) {
    $.ajax({
        type: "POST",
        url: '/WebServices/ConsumerProductService.asmx/GetConsumerProductSearchFilters',
        data: "{ 'manufacturer': '" + manufacturer + "', 'model' : '" + model + "' }",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            ClearFilters();
            if (msg.d.Certifications != null) {
                $('#h2CertificationsHeader').show();
                $('#lblNoFilterOptions').hide();
                $.each(msg.d.Certifications, function () {
                    $('#divCertifications').append('<input id="' + this.CertificationName + '" type="checkbox" name="Certifications" />' + this.CertificationName + '</input>');
                });
            }

            if (msg.d.Colors != null) {
                $('#h2ColorsHeader').show();
                $('#lblNoFilterOptions').hide();
                $.each(msg.d.Colors, function () {
                    $('#divColors').append('<input id="' + this.ColorName + '" type="checkbox" name="Colors" />' + this.ColorName + '</input>');
                });
            }

            if (msg.d.Orientations != null) {
                $('#h2OrientationsHeader').show();
                $('#lblNoFilterOptions').hide();
                $.each(msg.d.Orientations, function () {
                    $('#divOrientations').append('<input id="' + this.Orientation + '" type="checkbox" name="Orientations" />' + this.Orientation + '</input>');
                });
            }

            if (msg.d.SolutionTypes != null) {
                $('#h2SolutionTypesHeader').show();
                $('#lblNoFilterOptions').hide();
                $.each(msg.d.SolutionTypes, function () {
                    $('#divSolutionTypes').append('<input id="' + this.SolutionType + '" type="checkbox" name="SolutionTypes" />' + this.SolutionType + '</input>');
                });
            }

            if (msg.d.Categories != null) {
                $('#h2CategoriesHeader').show();
                $('#lblNoFilterOptions').hide();
                $.each(msg.d.Categories, function () {
                    $('#divCategories').append('<input id="' + this.HierarchyTitle + '" type="checkbox" name="Categories" >' + this.HierarchyTitle + '</input>');
                });
            }

            $('#mfEmbeddedFilters').height()

            // Set filters from url
            SetFilters();
        },
        error: function (xhr, textStatus, thrownError) {
            alert("/WebServices/ItemService.asmx/GetSeriesDetails Service Error - Unable to pull product details. TextStatus: "
            + textStatus + " ThrownError: " + thrownError);
        }
    });
};

function ClearFilters() {
    $('#divCertifications').html('');
    $('#divColors').html('');
    $('#divOrientations').html('');
    $('#divSolutionTypes').html('');
    $('#divCategories').html('');
};

// Re-check filters from hash
function SetFilters() {
//    if ($.address.value().length > 1) {
//        var filters = $.address.value().split("||");

//        $('#mfEmbeddedFilters input:checkbox').each(function (id) {
//            if ($.inArray($(this).attr('id'), filters) > -1) {
//                this.checked = true;
//            }
//        });                
//    }
};  
