$( document ).ready( function(){
//Listeners
    $( document ).on( 'submit' , '#site-search'      , function( e ){ headerSearchController.searchPages( e )           } );
    $( document ).on( 'submit' , '#article-search'   , function( e ){ searchPageController.searchNewsOnly( e )        } );
    $( document ).on( 'submit' , '#product-search'   , function( e ){ headerSearchController.searchProducts( e , this ) } );
    $( document ).on( 'submit' , '#support-search'   , function( e ){ searchPageController.searchProductsOnly(e) } );

    // Since we aren't showing autocomplete under 810px, don't bother with AJAX request
    //if (Modernizr.mq( 'only screen and (min-width: 925px)' ) || !Modernizr.mq( 'only all' ) )
    //{
        $( document ).on( 'keyup'  , '#header-search'    , function( ){ autoCompleteController.setUp( )               } );
        $( document ).on('keydown' , '#header-search'    , function( ){ autoCompleteController.clearTimeouts( )       } );
    //}
    $( document ).on( 'submit' , '#search-page'      , function(e){ searchPageController.search(e)  } );
    $( document ).on( 'submit' , '#main-site-search' , function(e){ autoCompleteController.submitHeader(e)        } );
    $( document ).on( 'submit' , '#review-search' , function(e) { e.stopPropagation(); reviewPageController.search(e)} );
    $( document ).on( 'click', '#more-products',function(e) {e.stopPropagation(); searchPageController.loadMoreProducts()} )
    $( document ).on( 'click', '#more-news', function(e) { e.stopPropagation(); searchPageController.loadMoreNews()}),
    $( document ).on( 'click', '#more-tvs', function(e) { e.stopPropagation(); searchPageController.loadMoreTvs()})

    $( document ).on( 'click' , autoSearchContainer.hide );
    $( document ).on( 'click' , '#main-site-search', function( e ){ e.stopPropagation(); } );
    $( document ).on( 'focus' , '#header-search', autoSearchContainer.focus );
    $( document ).on( 'focusout' , '#header-search', autoSearchContainer.focusTab );
    $('#autocompleteContainer').on('focusout', autoSearchContainer.focusTab);
    $( document ).on( 'click' , '.ga-action', headerSearchController.gaSmartSearchAction );
    searchPageController.setupPage();

    $( document ).on( 'click', '.product-search-result', function(e) {
        window.location = $(this).data('href');
    });

    $( document ).on( 'click', '.pinterestBinding', function( e ) {
        //e.preventDefault;
        var product = $(this).data('slug'),
            category = $(this).data('category'),
            price = $(this).data('price');
        if( typeof enablePinterest != 'undefined' ) {
        pintrk( 'track', 'AddToCart', { 'line_items': [
                {
                    'product_name': product,
                    'product_category': category,
                    'product_price': price,
                    'product_quantity': '1'
                }
            ]});
        }
        e.stopPropagation();
        //window.location = $(this).attr('href');
        //return false;
    })
});

var reviewPageController = {
    search: function(e) {
        e.preventDefault();
        var query = $("#search-input").val();
        query = query.replace('/','~');
        $("#search-results").addClass('loading');
        $.ajax({
                type:'POST',
                url: sanusSearchUrl + '/' + query,
                data: {q:query},
                success: function(response) {
                    var products = response.results.products;
                    products = reviewPageController.getProductHTML(products);
                    response.results.products = products;
                    $("#search-results").load(sanus_website_search.productsTabUrl,{data:response},function() {
                        if(products.length < 10) {
                            $("#more-products").css('display','none');
                        }
                        $("#search-results").removeClass('loading');
                    });
                }
        });

    },

    getProductHTML : function(products){
        var productHTML = '';
        if(products.length > 0){
            for(var i=0;i < products.length;i++){

                var product = products[i];
                product.reviewLink = reviewPageController.getReviewLink(product);
            }
            return products;
        }
        productHTML = '<li><p>No Suggestions</p></li>';
        return productHTML;
    },

    getReviewLink : function(product){
        var url = window.location.href;
        var link = url + product.slug + '/?bvdisplaycode=1943-en_us&bvappcode=rr&bvproductid=' + product.slug + '&bvpage=http%3A%2F%2Fsanus.ugc.bazaarvoice.com%2Fbvstaging%2F1943-en_us%2F' + product.slug + '%2Fsubmitreview.htm%3Fformat%3Dembedded%26campaignid%3DBV_REVIEW_DISPLAY%26sessionparams%3D__BVSESSIONPARAMS__%26return%3Dhttp%253A%252F%252Fsanus3.msheeks.dev.mocodev.com%252Fapp_dev.php%252Fen_US%252Fproducts%252Fmounts%252F' + product.slug + '%252F%26innerreturn%3Dhttp%253A%252F%252Fsanus.ugc.bazaarvoice.com%252Fbvstaging%252F1943-en_us%252F' + product.slug + '%252Freviews.djs%253Fformat%253Dembeddedhtml%26user%3D__USERID__%26authsourcetype%3D__AUTHTYPE__&bvcontenttype=REVIEW_SUBMISSION&bvauthenticateuser=false';

        return link;
    }
}

var searchPageController = {
    productPage: 1,
    tvsPage: 2,
    newsPage: 1,
    productCount: 0,
    tvsCount: 0,
    newsCount: 0,
    search : function(e) {
        e.preventDefault();
        var query = $("#search-input").val();
        query = query.replace('/','~');
        if(autoCompleteController.isZipCode(query)) {
            window.location = sanus_website_search.storeLocationSubmit + '?zipCode='+ query;
            return 0;
        }
        $('#search-results').addClass('loading');
        $.ajax({
            type:'POST',
            url: sanusSearchUrl + '/' + query,
            data: {q:query},
            success: function(response) {
                $("#productsCount").html(response.productsCount);
                searchPageController.productCount = response.productsCount;

                $("#tvsCount").html(response.tvsCount);
                searchPageController.tvsCount = response.tvsCount;

                $("#newsCount").html(response.newsCount);
                searchPageController.newsCount = response.newsCount;

                $("#tab-one").load(sanus_website_search.productsTabUrl,{data:response}, function() {searchPageController.setupPage();});
                $("#tab-two").load(sanus_website_search.tvsTabUrl,{data:response}, function() {searchPageController.setupPage();});
                $("#tab-three").load(sanus_website_search.newsTabUrl,{data:response}, function() {searchPageController.setupPage();});

                $('#search-results').removeClass('loading');
                return 0;
            }
        })
        },

    loadMoreProducts: function() {
    $('#search-results').addClass('loading');
        $.ajax({
            type:'POST',
            url: sanus_website_search.moreProducts,
            data: {
                query: $("#search-input").val(),
                page: searchPageController.productPage
            },
            success: function(response) {
                $("#searchResultsProductList").append(response);
                searchPageController.productPage++;
                if((searchPageController.productPage*10) > parseInt(searchPageController.productCount)) {
                    $("#more-products").css('display','none');
                }
                $('#search-results').removeClass('loading');
            }
        })
        },

    loadMoreNews: function() {
    $('#search-results').addClass('loading');
    $('#newsArticleListContainer').addClass('loading');
        $.ajax({
            type:'POST',
            url: sanus_website_search.moreNews,
            data: {
                query: $("#search-input").val(),
                page: searchPageController.newsPage
            },
            success: function(response) {
                $("#searchResultsNews").append(response);
                searchPageController.newsPage++;
                if((searchPageController.newsPage*10) > parseInt(searchPageController.newsCount)) {
                    $("#more-news").css('display','none');
                }
                $('#search-results').removeClass('loading');
                $('#newsArticleListContainer').removeClass('loading');
            }
        })
        },

    loadMoreTvs: function() {
    $('#search-results').addClass('loading');
        $.ajax({
            type:'POST',
            url: sanus_website_search.moreTvs,
            data: {
                query: $("#search-input").val(),
                page: searchPageController.tvsPage
            },
            success: function(response) {
                $("#moreTvs").append(response);
                searchPageController.tvsPage++;
                if(((searchPageController.tvsPage+1)*10) > parseInt(searchPageController.tvsCount)) {
                    $("#more-tvs").css('display','none');
                }
                $('#search-results').removeClass('loading');
            }
        })
        },

    searchProductsOnly: function(e) {

            e.preventDefault();
            var query = $("#search-input").val();
            query = query.replace('/','~');
            $('#searchResultsContainer').addClass('loading');
            $.ajax({
                type:'POST',
                url: sanusSearchUrl + '/' + query,
                data: {q:query},
                success: function(response) {
                    searchPageController.productCount = response.productsCount;
                    $("#searchResultsContainer").load(sanus_website_search.productsTabUrl,{data:response},function() {
                        if(searchPageController.productCount < 10) {
                            $("#more-products").css('display','none');
                        }
                    });
                    $('#searchResultsContainer').removeClass('loading');

                }
            })

        },

    searchNewsOnly: function(e) {
        e.preventDefault();
        var query = $("#search-input").val();
        query = query.replace('/','~');

        $('#newsArticleListContainer').addClass('loading');

        $.ajax({
            type: 'POST',
            url: sanusSearchUrl + '/' + query,
            data: {q:query},
            success: function(response) {
                searchPageController.neewsCount = response.newsCount;
                var div = $("div").find("[data-id=searchResultsContainer]");
                div.load(sanus_website_search.newsTabUrl,{data:response},function() {
                    if(searchPageController.newsCount < 10) {
                        $("#more-news").css('display','none');
                    }
                });
                $('#newsArticleListContainer').removeClass('loading');
            }
        })
    },

    setupPage: function() {
        searchPageController.productCount = $('#productsCount').html();
        searchPageController.tvsCount = $("#tvsCount").html();
        searchPageController.newsCount = $("#newsCount").html();
        if(parseInt(searchPageController.productCount) < 10) {
            $("#more-products").css('display','none');
        } else {
            $("#more-products").css('display','block');
        }
        if(parseInt(searchPageController.tvsCount) < 20) {
            $("#more-tvs").css('display','none');
        } else {
            $("#more-tvs").css('display','block');
        }
        if(parseInt(searchPageController.newsCount) < 10) {
            $("#more-news").css('display','none');
        } else {
            $("#more-news").css('display','block');
        }
    }
    }

/*
 * AJAX FUNCTION CONTROLLER
 */

var headerSearchController ={
    storeLocationAjax     : null,
    productLocationAjax   : null,
    tvModelsAjax          : null,
    pageSuggestionsAjax   : null,
    searchProductsAjax    : null,
    searchPagesAjax       : null,
    searchPageProductAjax : null,
    searchArticlesAjax    : null,

    isNullorEmpty : function( data ){
        if( typeof( data ) === 'undefined' )
        {
            return true;
        }
        if( data === null )
        {
            return true;
        }
        return false;
    },

    ajax : function( url , data,  success ){

        return $.ajax( {
                    url      : url,
                    type     : 'POST',
                    data     : data,
                    dataType : 'json',
                    success  : function( data ){ success( data ); },
                    error    : function( jqXHR , textStatus , errorThrown )
                    {
                        console.log( errorThrown );
                    }
                } );
    },

    //Searches for the top 5 StoreLocations
    getStoreLocations : function()
    {
        if( headerSearchController.ajaxVar != null )
        {
            this.storeLocationAjax.abort();
        }
        autoSearchContainer.searchStart();
        this.storeLocationAjax = this.ajax( sanus_website_search.storeLocator,
                                            storeLocationModel.getParameters(),
                                            storeLocationModel.success );
    },

    //Searches for the Products based on Autocomplete
    getProductLocations : function()
    {
        $( '#searchproducts' ).addClass( 'progress' );

        if( this.productLocationAjax != null )
        {
            this.productLocationAjax.abort();
        }
        autoSearchContainer.searchStart();
        this.productLocationAjax = this.ajax( sanus_website_search.defaultPath,
                                              { q    : autoCompleteController.query},
                                              autoCompleteController.success );
    },

    //Searches for TVs based on Autocomplete
    getTvModels : function()
    {
        $( '#searchTvs' ).addClass( 'progress' );

        if( this.tvModelsAjax != null )
        {
            this.tvModelsAjax.abort();
        }
        autoSearchContainer.searchStart();
        this.tvModelsAjax =             $.ajax( {
                    url      : sanus_website_search.tvModelAutocomplete,
                    type     : 'GET',
                    data     : {q: autoCompleteController.query},
                    dataType : 'json',
                    success  : function( data ){
                        data.isTvs = true;
                        autoCompleteController.success( data ); },
                    error    : function( jqXHR , textStatus , errorThrown )
                    {
                        console.log( errorThrown );
                    }
                } );
    },

    //Search for getting page suggestions for the header search
    getPageSuggestions : function()
    {
        $( '#searchrecommendations' ).addClass( 'progress' );

        if(this.pageSuggestionsAjax != null)
        {
            this.pageSuggestionsAjax.abort();
        }
        autoSearchContainer.searchStart();
        this.pageSuggestionsAjax = this.ajax( sanusSearchPageUrl,
                                              { q     : autoCompleteController.query,
                                                limit : 4,
                                                lang  : $('html').attr('lang'),label:'site' },
                                              autoCompleteController.success );
    },

    //Searches the Products for an AJAX load into a div container
    searchProducts : function( e , element )
    {
        e.preventDefault();
        if( this.searchProductsAjax != null )
        {
            this.searchProductsAjax.abort();
        }
        if( $( element ).attr( 'id' ) === 'support-search' )
        {
            searchProductModel.animateSupport();
        }
        this.searchProductsAjax = this.ajax( sanusSearchUrl,
                                             searchProductModel.getParameters(),
                                             searchProductModel.success );
    },

    //Searches all of the pages that are not a product or an article
    searchPages : function( e )
    {
        if( this.searchPagesAjax != null )
        {
            this.searchPagesAjax.abort();
        }
        e.preventDefault();
        this.searchPagesAjax = this.ajax( sanusSearchUrl,
                                          searchPageModel.getParameters( $( '#site-search input[name="q"]' ).val() ),
                                          searchPageModel.success );
    },

    //Searches top 3 pages and all Products that are not a product or an article
    searchPage : function( e )
    {
	    var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
                    if(autoCompleteController.isZipCode( $('#search-page input[name="q"]').val() ) !== false )
            {
                                	
					if (typeof ga == 'function') {
					// call ga object here
                    ga('send','event',{
                        'eventCategory' : 'Site Search',
                        'eventAction'   : 'Search Page Submitted',
                        'eventLabel'    : 'Store Location'
                    });}
                                window.location = sanus_website_search.storeLocationSubmit + '?zipCode='+ $( '#search-page input[name="q"]' ).val();
            }
                        	if (typeof ga == 'function') {
			// call ga object here
            ga('send','event',{
                'eventCategory' : 'Site Search',
                'eventAction'   : 'Search Page Submitted',
                'eventLabel'    : 'Product/Page'
            });}
                if( this.searchPageProductAjax != null )
        {
            this.searchPageProductAjax.abort();
        }
        e.preventDefault();
        this.searchProductAjax = headerSearchController.ajax( sanusSearchUrl,
                                                              searchPageModel.getPageParameters( $( '#search-page input[name="q"]' ).val() ),
                                                              searchPageModel.searchPageSuccess);
    },

    //Searches the articles for an Ajax load into a div container
    searchArticles : function(e){
        if( this.searchArticlesAjax != null )
        {
            this.searchArticlesAjax.abort();
        }
        e.preventDefault();

        if( searchArticleModel.getParameters().searchText != "" || searchArticleModel.getParameters().searchText === " " ){
            $( '#searchResultsContainer' ).html( '<h1>Searching&hellip;</h1>' );
            this.searchArticlesAjax = headerSearchController.ajax( sanusArticleSearchUrl,
                                                                   searchArticleModel.getParameters(),
                                                                   searchArticleModel.success );
        }
    },

    gaSmartSearchAction : function(){
                	var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
			if (typeof ga == 'function') {
			// call ga object here
            ga('send','event',{
                'eventCategory' : 'Site Search',
                'eventAction'   : 'Smart Search Item Clicked',
                'eventLabel'    : 'Product/Page'
            });}
            }
}

/*
 * AUTOCOMPLETE CONTROLLER
 */

var autoCompleteController = {
    zipMatch           : false,
    zipMatchCountry    : null,
    query              : '',
    autoCompleteSource : null,
    getStoreLocations  : null,
    getProducts        : null,
    getPages           : null,

    //determines if the header search is a zip code or a product/page search
    setUp : function()
    {
		var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
        if( $( '#header-search' ).val() !== this.query )
        {
            this.query = $( '#header-search' ).val();
            if( this.query.length < 3 )
            {
                autoSearchContainer.hide();
                return 0;
            }
                            if( this.isZipCode( this.query ) )
                {
                                        
					if (typeof ga == 'function') {
					// call ga object here
                        ga('send','event',{
                            'eventCategory' : 'Site Search',
                            'eventAction'   : 'Smart Search Triggered',
                            'eventLabel'    : 'Store Location'
                        });}
                                        this.zipMatch          = true;
                    this.zipMatchCountry   = this.isZipCode( this.query );
                    this.getStoreLocations = setTimeout( storeLocationModel.addressSearch( this.query ), 300 );
                    return 0;
                }
                                    	if (typeof ga == 'function') {
					// call ga object here
               ga('send','event',{
                   'eventCategory' : 'Site Search',
                   'eventAction'   : 'Smart Search Triggered',
                   'eventLabel'    : 'Product/Page'
               });}
                if( typeof enablePinterest != 'undefined' ) {
                    pintrk('track', 'Search', { 'search_query': this.query } );
                }
                        this.getProducts = setTimeout( function(){ autoSearchContainer.show(); headerSearchController.getProductLocations(); }, 300 );
            this.getTvModels = setTimeout( function(){ autoSearchContainer.show(); headerSearchController.getTvModels(); }, 300);
            this.getPages    = setTimeout( function(){ autoSearchContainer.show(); headerSearchController.getPageSuggestions();  }, 300 );
            return 0;
        }
    },

    //Clears the getProducts and getPages Timeouts
    clearTimeouts: function()
    {

        if( this.getStoreLocations )
        {
            clearTimeout( this.getStoreLocations );
        }
        if( this.getProducts )
        {
            clearTimeout( this.getProducts );
        }
        if( this.getTvModels )
        {
            clearTimeout( this.getTvModels );
        }
        if( this.getPages )
        {
            clearTimeout( this.getPages );
        }
    },

    //Submits the page to the Storelocator bundle when a zipcode is entered or the Main Search Page if not.
    submitHeader : function( e )
    {
        e.preventDefault();

        this.query = $( '#header-search' ).val();

                    if( this.isZipCode( this.query ) !== false )
            {
                                	var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
					if (typeof ga == 'function') {
					// call ga object here
                    ga('send','event',{
                        'eventCategory' : 'Site Search',
                        'eventAction'   : 'Smart Search Submitted',
                        'eventLabel'    : 'Store Location'
                    });}
                                window.location = sanus_website_search.storeLocationSubmit + '?zipCode='+ this.query;
                return 0;
            }
                        	var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
			if (typeof ga == 'function') {
			// call ga object here
            ga('send','event',{
                'eventCategory' : 'Site Search',
                'eventAction'   : 'Smart Search Submitted',
                'eventLabel'    : 'Product/Page'
            });}
                window.location = sanus_website_search.mainSearch + '?q='+this.query;
        return 0;
    },

    //takes a value and determines if it is a zipcode for 3 countries
    isZipCode : function( q )
    {
        caRegex = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
        usRegex = /^\d{5}(-\d{4})?$/;
        gbRegex = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/;

        if(caRegex.test(q) === true){
            // this.zipMatch = true;
            // this.zipMatchCountry = 'CA';
            return 'CA';
        }
        if(usRegex.test(q) === true){
            // this.zipMatch = true;
            // this.zipMatchCountry = 'US';
            return 'US';
        }
        if(gbRegex.test(q) === true){
            // this.zipMatch = true;
            // this.zipMatchCountry = 'GB';
            return 'GB';
        }
        this.zipMatch = false;
        this.zipMatchCountry = null;
        return false;
    },

    //gets the ProductHTML and returns it for display in the autocomplete container
    getProductHTML : function(products){
        var productHTML = '';
        if(products.length > 0){
            for(var i=0;i < products.length;i++){
                var product = products[i];
                //if(product.retailers.length > 0) continue; MMS - removed on 03/31/16 as a reversal of a previous SANUS request

                productAutoCompleteModel.image         =    product.img;
                productAutoCompleteModel.name          =    product.name;
                productAutoCompleteModel.subHead       =    product.subhead;
                productAutoCompleteModel.slug          =    product.slug;
                productAutoCompleteModel.url           =    product.url;
                productAutoCompleteModel.category_slug =    product.category_slug;
                productAutoCompleteModel.price         =    product.price;
                productAutoCompleteModel.cartPath      =    product.cartPath;
                productAutoCompleteModel.publishSetting =   product.publishSetting;

                if ( typeof product.retailerName !== undefined ) {
                    productAutoCompleteModel.retailerName = product.retailerName;
                }

                productHTML += productAutoCompleteModel.returnAutoCompleteSnippet();
            }
            return productHTML;
        }
        productHTML = '<li><p>No Suggestions</p></li>';
        return productHTML;
    },

    getTvHTML : function(models) {
        var tvHTML = '';
        if(models.length > 0){
            modelsCount = models.length;
            if(modelsCount > 6) modelsCount = 6;
            for(var i=0;i < modelsCount;i++){
                var model = models[i];

                TvModelAutoCompleteModel.name           = model.name;
                TvModelAutoCompleteModel.modelUrl       = model.url;

                tvHTML += TvModelAutoCompleteModel.returnAutoCompleteSnippet();
            }
            return tvHTML;
        }
        tvHTML = "<li><p>No TV Models</p></li>";
        return tvHTML;
    },

    getPageHTML : function(pages){
        var pageHTML = '';
        if(pages.length > 0){
            var pageCount = pages.length;
            if(pageCount > 4){
                var pageCount = 4;
            }
            for(var i=0;i < pageCount;i++){
                    var page = pages[i];

                    pageAutoCompleteModel.featuredImageUrl = (typeof(page.featuredImage) === 'undefined' ? page.featuredImage : page.featuredImage.replace('resize_w=40','resize_w=343').replace('resize_h=40','resize_h=150') );
                    /*
                    if (page.featuredImage !== undefined) {
                        pageAutoCompleteModel.featuredImageUrl = page.featuredimage.replace('resize_w=40','resize_w=343').replace('resize_h=40','resize_h=150');
                    }*/
                    pageAutoCompleteModel.title = page.title;
                    pageAutoCompleteModel.summary = page.summary;
                    pageAutoCompleteModel.url = page.url;

                    pageHTML += pageAutoCompleteModel.returnAutoCompleteSnippet();
            }
            return pageHTML;
        }
        pageHTML = '<li><p>No Suggestions</p></li>';
        return pageHTML;
    },

    //the function called on sucessful AJAX call for products and pages
    success : function(products){

        if(autoCompleteController.zipMatch === false){
            if ($('#store-locations').length) {
                $('#autocompleteContainer').removeClass('store-locations');
                $('#autocomplete').html('<div id="searchproducts" class="left third"></div><div id="searchTvs" class="left third"></div><div id="searchrecommendations" class="right third"></div>');
            }
            if(typeof(products.searchResults) === "undefined"){
                if(!!products.isTvs) {
                    $( '#searchTvs').removeClass('progress');
                    $( '#autocomplete #searchTvs').html('<h2>Find Products for these TVs</h2>');
                    $( '#autocomplete #searchTvs').append('<ul>'+autoCompleteController.getTvHTML(products)+'</ul>');
                }
                else {
                    $( '#searchproducts' ).removeClass( 'progress' );
                    $('#autocomplete #searchproducts').html('<h2>Popular Products</h2>');
                    $('#autocomplete #searchproducts').append('<ul>'+autoCompleteController.getProductHTML(products)+'</ul>');
                }

                return 0;
            }
            $( '#searchrecommendations' ).removeClass( 'progress' );
            $('#autocomplete #searchrecommendations').html('<h2>Recommendations</h2>');
            $('#autocomplete #searchrecommendations').append('<ul>'+autoCompleteController.getPageHTML(products.searchResults.other)+'</ul>');
            autoSearchContainer.searchEnd();
            return 0;
        }
    }
}

/*
 * STORE LOCATION MODEL
 */

var storeLocationModel = {
    latitude     : null,
    longitude    : null,
    country      : null,
    storeName    : null,
    storeAddress : null,
    storeCity    : null,
    storeState   : null,
    storeZipCode : null,

    clear : function(){
        storeLocationModel.storeName     = null;
        storeLocationModel.storeAddress  = null;
        storeLocationModel.storeCity     = null;
        storeLocationModel.storeState    = null;
        storeLocationModel.storeZipCode  = null;
        storeLocationModel.storeDistance = null;
    },

    addressSearch : function(zipCode){

        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({'address':zipCode},function(results,status){
            if(status === 'OK'){
                if(!results[0].address_components[1]){
                    consle.log(false);
                }
                storeLocationModel.setParameters(results);
                headerSearchController.getStoreLocations();
            }
        });
    },

    setParameters : function(results){
        this.latitude  = results[0].geometry.location.lat();
        this.longitude = results[0].geometry.location.lng();
    },

    getParameters : function(){
        return {
            lat     : storeLocationModel.latitude,
            lon     : storeLocationModel.longitude,
            country : autoCompleteController.zipMatchCountry,
            limit   : 10
        };
    },

    renderStoreLocationHTML : function(){
        var storeHTML = '';
        storeHTML += '<li>';
        storeHTML += '<h3>'+ this.storeName +' <span class="store-distance">| ';
        storeHTML += Math.round(this.storeDistance*10)/10 + ' mi</span></h3>';
        storeHTML += '<p>'+ this.storeAddress +'<br />';
        storeHTML += this.storeCity +', '+ this.storeState + ' ' + this.storeZipCode + '</p>';
        storeHTML += '<a class="directions-link" target="_blank" href="';
        storeHTML += (isMobile.iOS()) ? 'https://maps.apple.com/maps?f=d&hl=' : 'https://maps.google.com/maps?f=d&hl=';
        storeHTML += $('html').attr('lang') + '&saddr=' + autoCompleteController.query + '&daddr=' + this.storeZipCode + "+" + this.storeAddress +'" >Get Directions</a>';
        storeHTML += '</li>';
        return storeHTML;
    },

    success : function(stores){
        $('#autocompleteContainer').addClass('store-locations');
        $('#autocomplete').html('<h2>Store Locations</h2>');
        if(stores === false){
            $('#autocomplete').append('<p id="store-locations">No stores within 10 miles of '+autoCompleteController.query+'.</p>');
        }else{
            var storesList = '';

            for(var i=0;i < stores.length;i++){
                var storeLocation = stores[i];
                storeLocationModel.storeName     = storeLocation.name;
                storeLocationModel.storeAddress  = storeLocation.address1;
                storeLocationModel.storeCity     = storeLocation.city;
                storeLocationModel.storeState    = storeLocation.state_province;
                storeLocationModel.storeZipCode  = storeLocation.postal_code;
                storeLocationModel.storeDistance = storeLocation.distance;

                storesList += storeLocationModel.renderStoreLocationHTML();
                storeLocationModel.clear();
            }
            $('#autocomplete').append('<ul id="store-locations">'+storesList+'</ul>');
        }
        autoSearchContainer.show();
        autoSearchContainer.searchEnd();
    }
}

/*
 * PRODUCT AUTOCOMPLETE MODEL
 */

var productAutoCompleteModel = {
    image: null,
    name : null,
    slug : null,
    category_slug : null,
    subHead : null,
    rating  : null,
    url : null,
    retailerName: null,
    publishSetting: null,

    setImageFileName : function(imageFileName){
        if(typeof(imageFileName) === "undefined"){
            throw 'Invalid parameter for setImageFileName';
        }
        this.imageFileName = imageFileName;
    },

    setName : function(name){
        if(typeof(name) === "undefined"){
            throw 'Invalid parameter for setName';
        }
        this.name = name;
    },

    setSlug : function(slug){
        if(typeof(slug) === "undefined"){
            throw 'Invalid parameter for setSlug';
        }
        this.slug = slug;
    },

    setProductUrl : function(url){
        if(typeof(url) !== "undfined"){
            this.productUrl = url;
        }
    },

    setSubHead : function(subHead){
        if(typeof(subHead) === "undefined"){
            throw 'Invalid parameter for subHead';
        }
        this.subHead = subHead;
    },

    setPublishSetting: function( publishSetting ) {
        if ( typeof( publishSetting ) === "undefined" ) {
            throw "Invalid parameter for publishSetting";
        }
        this.publishSetting = publishSetting;
    },

    returnAutoCompleteSnippet : function(){
        var cartButtonClass = '';
        if( this.cartPath == undefined ) {
            cartButtonClass = ' disabled';
        }

        var HTML = '';

        HTML += '<li class="clearfix '+this.category_slug+' product-search-result" data-href="'+this.url+'" role="link" tabindex="0">';
        //HTML += '    <a class="ga-action" href="'+this.url+'">';
        HTML += '    <div class="image">';
        HTML += '        <img alt="Small thumbnail product shot of '+this.name+'" src="'+this.image+'" />';
        HTML += '    </div>';
        HTML += '    <div class="product-meta">';
        HTML += '       <h3>';
        HTML +=         this.name

        if ( this.publishSetting === 'Draft' ) {
            HTML += ' (' + this.publishSetting.toUpperCase() + ') ';
        }

        HTML +=         '</h3>';
        HTML += '       <p>'+this.subHead+'</p>';
        HTML += '    </div>';HTML += '</li>';

        return HTML;
    }
}

/*
 *  TV MODEL AUTOCOMPLETE MODEL
 */

var TvModelAutoCompleteModel = {
    image : null,
    name : null,
    modelName : null,
    modelUrl: null,

    setImage : function(image) {
        if(typeof(image) === "undefined") {
            throw "Invalid parameter for setImage";
        }
        this.image = image;
    },

    setName : function(name) {
        if(typeof(name) === "undefined") {
            throw "Invalid parameter for setName";
        }
        this.name = name;
    },

    setModelName : function(modelName) {
        if(typeof(modelName) === "undefined") {
            throw "Invalid parameter for setModelName";
        }
        this.modelName = modelName;
    },

    setModelUrl : function(modelUrl) {
        if(typeof(name) === "undefined") {
            throw "Invalid parameter for setModelUrl";
        }
        this.modelUrl = modelUrl;
    },

    returnAutoCompleteSnippet : function() {
        var breakPos = this.name.indexOf('" ');
        var name = this.name.substring(0,breakPos+1);
        var model = this.name.substring(breakPos+1);
        var HTML = '';

        HTML += '<li class="clearfix">';
        HTML += '   <a class="ga-action" href="'+this.modelUrl+'">';
        //HTML += ' <span class="illustration">';
        //HTML += ' </span>';
        HTML += '   <div class="model-meta">';
        HTML += '       <h3>'+model+'</h3>';
        HTML += '       <p>'+name+'</p>';
        HTML += '   </div>';
        HTML += '   </a>';
        HTML += '</li>';

        return HTML;
    }
}

/*
 * PAGE AUTOCOMPLETE MODEL
 */

var pageAutoCompleteModel = {
    title : null,
    featuredImageUrl : null,
    summary : null,
    url : null,
        image: null, // added by Brian


    returnAutoCompleteSnippet : function(){

        var HTML = '';
                var imageLink = '';

        HTML += '<li class="clearfix">';
        HTML +=         '<a class="ga-action" href="'+this.url+'">' ;
        HTML +=             '<div class="image">';

                HTML +=                 headerSearchController.isNullorEmpty(this.featuredImageUrl) ? '<img src="\/img\/search_placeholder.jpg"' : '<img src="'+this.featuredImageUrl+'" onError="$(this).hide();"';


                if (pageAutoCompleteModel.checkImageSize()) {
            HTML +=             'class="non-thumb"';
        }
        HTML +=                 ' />';
        HTML +=             '</div>';
        HTML +=             '<div>';
        HTML +=                 '<h3>'+this.title+'</h3>';
        HTML +=                 headerSearchController.isNullorEmpty(this.summary) ? '' : '<p>'+this.summary+'</p>';
        HTML +=             '</div>';
        HTML +=         '</a>' ;
        HTML +=     '</li>';

        return HTML;
    },

    checkImageSize: function(){
        if (!headerSearchController.isNullorEmpty(this.featuredImageUrl)) {
            var image = new Image();
            image.src = this.featuredImageUrl;
            if (image.width > 60) {
                return true;
            }
            else {
                return false;
            }
        }
    }

}

/*
 * SEARCH ARTICLE MODEL
 */

var searchArticleModel = {
        name            : null,
        date            : null,
        excerpt         : null,
        url             : null,
        featuredImage   : null,
        translationLink : null,

        clear : function(){
                searchArticleModel.name = null;
                searchArticleModel.date = null;
                searchArticleModel.excerpt = null;
                searchArticleModel.url = null;
                searchArticleModel.featuredImage = null;
                searchArticleModel.translationLink = null;
        },

        displayHTML : function(){
                var HTML = '<article class="news-article">';
                                        if(searchArticleModel.featuredImage !== null || typeof(searchArticleModel.featuredImage) === 'undefined'){
                                                HTML += '<img class="award-image no-border left" src="/assets/news/images/thumb/'+searchArticleModel.featuredImage+'">';
                                        }
                                        HTML += '<h3>'+searchArticleModel.name+'</h3>';
                                        HTML += '<p class="article-date">'+searchArticleModel.date+'</p>';
                                        HTML += '<div class="article-excerpt">'+searchArticleModel.excerpt+'</div>';
                                        HTML += '<a class="button" href="'+searchArticleModel.url+'">Read More</a> ';
                                                                                HTML += '</article>';
                searchArticleModel.featuredImage = null;
                return HTML;
        },

        success : function(data){

                var articles = data.articles;

                if( typeof( $('div [data-id="searchResultsContainer"]').find('div.searching-message-container').html() ) === "undefined" ){
                        $('div [data-id="searchResultsContainer"]').html('<div class="searching-message-container"><h1>Searching...</h1></div>');
                }
                else
                {
                        $('div.searching-message-container').html('<h1>Searching...</h1>');
                }

                if(articles.length > 0){
                        var articleList = '<h1>Search Results for '+searchArticleModel.searchText+'</h1>';
                        length = articles.length >5 ? 5 : articles.length
                        for(var i = 0; i<articles.length;i++){



                                if(typeof(articles[i]) !== "undefined"){
                                        searchArticleModel.name = articles[i].name;
                                        searchArticleModel.date = articles[i].date;
                                        searchArticleModel.excerpt = articles[i].excerpt;
                                        searchArticleModel.url = articles[i].url;
                                        searchArticleModel.translationLink = articles[i].translationLink;
                                        if(typeof(articles[i].image) !== "undefined"){
                                                searchArticleModel.featuredImage = articles[i].image;
                                        }

                                        articleList += searchArticleModel.displayHTML();
                                        searchArticleModel.clear();
                                }
                        }

                        $('div [data-id="searchResultsContainer"]').html('<div class="news-articles article-list" id="searchResultsList">'+articleList+'</div>');
                }else{
                        $('div.searching-message-container').append('<div class="news-articles article-list" id="searchResultsList"><h2>No\u0020Search\u0020Results...</h2></div>');
                }
        },

        getParameters : function(){
                searchArticleModel.searchText = $('#search-input').val();
                return {
                        searchText : $('#search-input').val(),
                };
        }
}


/*
 * HEADER SEARCH SHOW/HIDE
 */

var autoSearchContainer = {

    show: function(){
        var $search = $('#autocompleteContainer');

        if (Modernizr.csstransitions) {
            if (!$search.hasClass('show')) {
                $search.addClass('show');
            }
        }
        else {
            if (!$search.is(':visible')) {
                $search.stop(true,true).fadeIn(250);
            }
        }
    },

    hide: function(){
        var $search = $('#autocompleteContainer');

        if (Modernizr.csstransitions) {
            $search.removeClass('show');
        }
        else {
            $search.stop(true,true).fadeOut(250);
        }
    },

    focus: function(){
        var val = $('#header-search').val();
        if (val.length >= 3) { autoSearchContainer.show();}
    },

    focusTab: function() {
        const container = $(this);

		setTimeout(function () {
			if (document.querySelectorAll("#autocompleteContainer :focus").length === 0) {
                autoSearchContainer.hide();
            } else {
                // Do Nothing
            }
		}, 500);
    },

    searchStart: function() {
        $('#header-search').addClass('searching');
    },

    searchEnd: function() {
        $('#header-search').removeClass('searching');
    }
}
