﻿//A variable to use for IE6
var isIE6;


// Attaching to page load
$(document).ready(function() {

    // initialize jQuery UI Tabs.
    $("#product-selector .questions").productSelector({
        onPopulate: function(results) {
            ProductSelector.trackReturnedResults(results.length);
        },
        onIterateProduct: function(product) {
            ProductSelector.formatPrice(product);
            product.RelCode = ProductSelector.dynamicRelCode(product.Category);
            product.RevCode = ProductSelector.dynamicRevCode(product.Category);
        },
        onPopulateComplete: function(element) {
            ProductSelector.ie6ClearFix(element);
            ProductSelector.floodlight();
        }

    });
    var tabs = $("#product-selector .question-tabs").tabs();

    // All of the presentational javascript for the product selector pages
    //should be contained within this if statement.
    if ($('#product-selector').length > 0) {

        //Some presentational javascript to make the page build a bit smoother
        var questionSection = $('.question-tabs');
        var resultsSection = $('.results');

        questionSection.show();
        resultsSection.show();

        //hide the previous button on page load
        $('.previous').hide();

        //set the initial breadcrumb on page load
        $('.crumb').html($('.question-title').html());

        //hover event for the labels of the questions
        $('.question label').mouseenter(function() {
            ProductSelector.toolTip(this);
        });

        //hide the tool tip on document click event
        $(document).click(function() {
            $('.tool-tip').hide();
        });

        //Click event for the product selector next button.
        $('.question a').click(function(event) {
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
            ProductSelector.selectedTab(tabs, 'next');
            $('.previous').attr('rev', ProductSelector.dynamicTracking(tabs));
            ProductSelector.trackLink(this);
        });

        //Click event for the product selector prev button
        $('.previous').click(function(event) {
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
            ProductSelector.selectedTab(tabs, 'prev');
            $(this).attr('rev', ProductSelector.dynamicTracking(tabs));
            ProductSelector.trackLink(this);
        });

        //Click event to show and hide previous button.
        $('.question-list a').click(function(event) {
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
            ProductSelector.selectedTab(tabs, null);
            $('.previous').attr('rev', ProductSelector.dynamicTracking(tabs));
            ProductSelector.trackLink(this);
        });

        //Click event for the product selector start over button.
        $('#answer a').click(function(event) {
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
            ProductSelector.reset(tabs);
            ProductSelector.trackLink(this);
        });

        //Click event for the product selector start over button.
        $('.product-float a').click(function() {
            ProductSelector.trackLink(this);
        });

        //Click event for the product selector start over button.
        $('span.reset').click(function(event) {
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
            ProductSelector.reset(tabs);
            ProductSelector.trackLink(this);
        });

        //Set up Breadcrumbs when choices are clicked 
        //Track when any input on the page is clicked
        $('#product-selector input').click(function() {
            ProductSelector.breadCrumbCreate(tabs, this);
            ProductSelector.trackInput(this);
        });

        //Dynamic Breadcrumbing
        ProductSelector.dynamicCrumb('.question-title', '.dynamicCrumb');


        if ($('#modalWrapper').length > 0) {
            var url = '/ProductSelector/LearnMore.aspx?ds=' + $('#inline').attr('data-store') + '&swfAddr=' + $('#inline').attr('data-address');
            $.ajax({
                url: url,
                success: function(data) {
                    $('#inlineContent').html(data);
                }
            });
        }
    }
});
//End page load function


//Start Functions for Presentational Javascript for Product Selector Pages
var ProductSelector = {};
//Create a global timer for the tool tip
ProductSelector.toolTimer;
//Create a global array for breadcrumbs
ProductSelector.breadCrumb = [];


//function that adds a clearfix to the results if browser is IE 6
ProductSelector.ie6ClearFix = function(el) {
    if (isIE6) {
        el.append('<li class="ps-clearFix"></li>');
    }
};


//function that grabs the <a> element on the page and applies tracking to it
ProductSelector.reset = function(tabsUI) {
    tabsUI.tabs("select", 0);
    ProductSelector.breadCrumb.length = 0;
    var crumb = $('.question-title').html();
    $('.crumb').html(crumb);
    $('.previous').hide();
}

//function that grabs all of the input items on the page and applies tracking to them
ProductSelector.trackInput = function(element) {
    var trackingId = '';
    var classes = $(element).attr('class').split(' ');
    
    _(classes).each(function(element, index, list) {
        if (element.indexOf('tc:') == 0) {
            var splitClass = element.split(':');
            trackingId = splitClass[1];
        }
    });
}

//function that grabs the index of the selected tab
ProductSelector.selectedTab = function(tabsUI, direction) {
    //Get the index of the selected tab
    var selected = tabsUI.tabs('option', 'selected');

    //Based on the value of the direction param, increase or decrease selected by 1
    if (direction && direction == 'next') {
        selected++;
    } else if (direction && direction == 'prev') {
        selected--;
    }

    //Tells the UI to select the current tab
    tabsUI.tabs("select", selected);

    //Hides any tool tip that may be open
    $('.tool-tip').hide();

    //Hides and shows the previous and next buttons
    if (selected == 0) {
        $('.previous').hide();
    } else {
        $('.previous').show();
    }

    return selected;
};

//Function that creates the tool tip
ProductSelector.toolTip = function(element) {
    if ($(element).siblings('div').length > 0) {
        var toolTip = $('.tool-tip');
        ProductSelector.toolTipContent(element, toolTip);
        ProductSelector.toolTipPosition(element, toolTip);
        ProductSelector.toolTipTimer(toolTip);
    }
};

//Function that injects the tool tip with content.
ProductSelector.toolTipContent = function(el, tool) {
    var tip = $(el).siblings('div').html();
    tool.children('.tool-content').html('');
    tool.children('.tool-content').html(tip);
};

//Function that handles the positioning of the tool tip
ProductSelector.toolTipPosition = function(el, tool) {
    var top = $(el).parent().position('.question').top + 45;
    var left = 105 + $(el).position().left + $(el).width();
    var offset = (tool.outerHeight() / 2) - 9;
    
    tool.show();
    tool.css('top', top - offset);
    tool.css('left', left);
};

//Function that handles the timer for the tool tip
ProductSelector.toolTipTimer = function(tool) {
    clearTimeout(ProductSelector.toolTimer);
    ProductSelector.toolTimer = setTimeout(function() {
        tool.fadeOut('fast');
    }, 5000);
};


//This is one route to take with tracking the breadcrumbs, it works well but we might want this to be done on the backend

//breadCrumbTitle simply grabs the id from the input and returns its value
ProductSelector.breadCrumbTitle = function(input) {
    var getCrumb = $(input).attr('id');
    //Parse out all the - from the id
    var title = getCrumb.replace(/-/g, ' ');
    return title;
};

//breadCrumbArrange orders the values from the selected inputs and places them nicely in our breadCrumb array
//this method of breadCrumbing only works if the values stay in their spot in the array
ProductSelector.breadCrumbArrange = function(tabsUI, input) {
    
    //We need to place any checkbox values into its own array
    var checkbox = [];
    
    //Keep track of the current question - this will be used as the index values for our breadCrumb array
    var currentQuestion = tabsUI.tabs('option', 'selected');
    
    //We need to know what type of input we are dealing with
    var type = input.type;

    //if a checkbox is selected we need to run through all the checkboxs in the question
    //and figure out which ones are checked
    if (type == "checkbox") {
        //get all the checkboxes in the question
        var inputParent = $(input).parent('li').parent('ul').parent();
        var getBoxes = $(inputParent).find('input');
        
        //iterate throught the checkboxes and figure out which are checked
        _(getBoxes).each(function(element, index, list) {
            var check = element.checked;
            //if checked, add value to checkbox array else leave empty
            if (check) {
                checkbox[index] = ProductSelector.breadCrumbTitle(element);
            } else {
                checkbox[index] = '';
            }
        });
        
        //get rid of all the empty values in the checkbox array
        checkbox = _.without(checkbox, '');
        
        //add the checkbox array to the breadCrumb array , its index is the value of the currentQuestion
        ProductSelector.breadCrumb[currentQuestion] = checkbox;
    } else {
        //if an input other than checkbox is selected just add the value to the breadCrumb array - its index is the value of the currentQuestion
        ProductSelector.breadCrumb[currentQuestion] = ProductSelector.breadCrumbTitle(input);
    }
};

//breadCrumbCreate writes the values of our breadCrumb array to a string and injects the string into the page
ProductSelector.breadCrumbCreate = function(tabsUI, input) {
    
    //We don't want to listen to any of the sort inputs
    if ($(input).attr('name') != 'sort') {
        
        //Create crumb, this is our string, and populate it right of the bat with the name of the page
        var crumb = $('.question-title').html();
        
        //Call ProductSelector.breadCrumbArrange so that we can use the array to populate our string
        ProductSelector.breadCrumbArrange(tabsUI, input);
        
        //A good old for loop to deal with IE's rejection of undefined array values - probably a better way to do this
        for (var k = 0; k < ProductSelector.breadCrumb.length; k++) {
            if (ProductSelector.breadCrumb[k] == undefined) {
                //The value of 'none' will be placeholder untill it gets parsed out
                ProductSelector.breadCrumb[k] = 'none';
            }
        }
        
        //This is where crumb is built - iterate through ProductSelector.breadCrumb and grab the values
        _(ProductSelector.breadCrumb).each(function(element, index, list) {
            //if the element is empty we don't want to include a /
            if (element.length == 0) {
                crumb += element;
            } else {
                crumb += ' / ' + element;
            }
        });
        
        //Some string parsing to get crumb lookin good
        //this one gets rid of any commas left over from our checkbox array
        crumb = crumb.replace(/\,/g, ' / ');
        //this one gets rid of our place holder 'none' value if it exists
        crumb = crumb.replace(/\/ none /g, '');
        
        //inject crumb to the page
        $('.crumb').html(crumb);
    }
};


//Checks to see if the results returned are 0.  If yes, then the emptyResults div is displayed
ProductSelector.trackReturnedResults = function(length) {
    $('.results-displayed span').html(length);
    if (length == 0) {
        $('.emptyResults').show();
    } else {
        $('.emptyResults').hide();
    }
};

//This function parses and formats the price of the products
ProductSelector.formatPrice = function(product) {
    //Grabs product.Price and parses it to 2 decimal places, removes .00 if found, and returns a number
    var price = parseFloat(product.Price).toFixed(2).replace('.00', '');
    
    //Function that adds commas to the price if needed
    function addCommas(priceStr) {
        priceStr += '';
        priceSplit = priceStr.split('.');
        price1 = priceSplit[0];
        price2 = priceSplit.length > 1 ? '.' + priceSplit[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(price1)) {
            price1 = price1.replace(rgx, '$1' + ',' + '$2');
        }
        return price1 + price2;
    }
    
    //assign product.Price to the returned value price with commas added
    product.Price = addCommas(price);
    return product.Price;
};

//This function grabs appends a rev attribute for tracking purposes
ProductSelector.dynamicTracking = function(tabsUI) {
    //The index of the selected tab
    var selected = tabsUI.tabs('option', 'selected');

        //Grab the link previous to the selected tab
        var question = $('.ui-state-active').children('a');
        //Tracking string is created
        var tracking = $(question).attr('rev') + '_Previous';
        return tracking;
};


//Function that creates a dynamic breadcrumb for the page header
ProductSelector.dynamicCrumb = function(sourceEl, targetEl) {
    var pageTitle = $(sourceEl).html();
    $(targetEl).html(pageTitle);
};



ProductSelector.dynamicRelCode = function(category) {
    var relCode = 'default';
    switch (category) {
        case 9:
            //Washer
            relCode = 'mhdco308';
            break;
        case 8:
            //Refrigerator
            relCode = 'mhdco193';
            break;
        case 7:
            //Range
            relCode = 'mhdco782';
            break;
        case 6:
            //Microwave
            relCode = 'mhdco759';
            break;
        case 5:
            //Hood
            relCode = 'mhdco256';
            break;
        case 3:
            //Dryer
            relCode = 'mhdco561';
            break;
        case 2:
            //Dishwasher
            relCode = 'mhdco475';
            break;
        case 1:
            //BuiltIn
            relCode = 'mhdco110';
            break;
    }
    return relCode;
};

ProductSelector.dynamicRevCode = function(category) {
    var revCode = 'default';
    switch (category) {
        case 9:
            //Washer
            revCode = 'Washer';
            break;
        case 8:
            //Refrigerator
            revCode = 'Refrigerators';
            break;
        case 7:
            //Range
            revCode = 'Ranges';
            break;
        case 6:
            //Microwave
            revCode = 'Microwave';
            break;
        case 5:
            //Hood
            revCode = 'Hoods';
            break;
        case 3:
            //Dryer
            revCode = 'Dryer';
            break;
        case 2:
            //Dishwasher
            revCode = 'Dishwasher';
            break;
        case 1:
            //BuiltIn
            revCode = 'Ovens';
            break;
    }
    return revCode;
};

// DoubleClick Floodlight tracking
ProductSelector.floodlight = function() {
    $("a.floodlight").click(function(e) {
        e.preventDefault();
        var href = $(this).attr("href");
        var cat = $(this).attr("rel");
        var t = $(this).attr("target");
        var url = "http://fls.doubleclick.net/activityi;src=2625291;type=mayhdlp;cat=" + cat + ";ord=" + ((Math.random() + "") * 10000000000000);
        $("#flFrame").attr("src", url).one("load", function() {
            if (t == "_blank") {
                window.open(href);
            } else {
                self.location = href;
            }
        });
    });
};

