//inner sign position control
var positionSign = function () {
    if ($('.sign-container').length > 0) {
        
        
        var menuBottom = $('.inner-left-column').position().top + $('.inner-left-column').outerHeight();
        var footerTop = $('.footer-container').position().top;
		
        
        if (isFixed) {
			$('.sign-container').css({ position: 'fixed', bottom: 0, top: 'auto' });
			
			var signTop = $('.sign-container').position().top;
            var signBottom = signTop + 161;
			
			if (menuBottom > signTop || footerTop < signBottom) {
                $('.sign-container').css({ position: 'absolute', top: Math.min(Math.max(signTop, menuBottom), footerTop - 161) });
            }
            
        } else {
            $('.sign-container').css({ position: 'absolute', top: footerTop - 161 });
        }
	
    }
};




$(document).ready(function () {

    //detects if position:fixed is supported and if it is, returns true.
    window.isFixed = (function () {
        var container = document.body;
        if (document.createElement && container && container.appendChild && container.removeChild) {
            var el = document.createElement("div");
            if (!el.getBoundingClientRect) {
                return null;
            }
            el.innerHTML = "x";
            el.style.cssText = "position:fixed;top:100px;";
            container.appendChild(el);
            var originalHeight = container.style.height, originalScrollTop = container.scrollTop;
            container.style.height = "3000px";
            container.scrollTop = 500;
            var elementTop = el.getBoundingClientRect().top;
            container.style.height = originalHeight;
            var isSupported = elementTop === 100;
            container.removeChild(el);
            container.scrollTop = originalScrollTop;
            return isSupported;
        }
        return null;
    } ());

    $(window).bind('scroll', function () {
        positionSign();
    });


    //position the sign horizontally 
    var signLeft = ($(window).width() - 972) / 2;
    $('.sign-container').css({ left: signLeft });
    $(window).resize(function () {
        var signLeft = ($(window).width() - 972) / 2;
        if (signLeft > 20) {
            $('.sign-container').css({ left: signLeft });
        }
        positionSign();

    });

    // homepage main carousel
    $(".slide-titles :not('.title-1')").hide();
    $(".background-container :not('.background-1')").hide();
    $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        easing: 'easeOutCirc',
        auto: 7000,
        speed: 500,
        visible: 1,
        btnGo:
            [".btn-container .1",
            ".btn-container .2",
            ".btn-container .3",
            ".btn-container .4",
            ".btn-container .5"],
        afterEnd: function (slide) {
            var i = /(background-[0-9]+)/.exec(slide.attr("class"))[0];
            $(".background-container :visible").delay(500).fadeOut(1000);
            $(".background-container ." + i).fadeIn(800);
            var title = /(title-[0-9]+)/.exec(slide.attr("class"))[0];
            $(".slide-titles :visible").fadeOut();
            $(".slide-titles ." + title).fadeIn(800);
        }
    });
    //homepage news carousel
    $('.panel-carousel').css({ opacity: '0' });
    $(".panel-carousel").jCarouselLite({
        btnNext: ".panel-next",
        btnPrev: ".panel-prev",
        visible: 1,
        easing: 'easeOutCirc',
        speed: 500
    });
    //inner image carousel
    $('.right-agent-info:not(".agent-1")').hide();
    $(".inner-slider").jCarouselLite({
        btnNext: ".agent-next",
        btnPrev: ".agent-prev",
        visible: 1,
        easing: 'easeOutExpo',
        speed: 400,
        circular: true,
        afterEnd: function (slide) {
            var i = /(agent-[0-9]+)/.exec(slide.attr('class'))[0];
            $('.right-agent-info:visible').fadeOut('fast');
            $('.right-agent-info.' + i).fadeIn('fast');
        }
    });

    //DETECT FLASH. IF THERE IS NONE, SET UP HTML5 VIDEOS TO LOAD ON CLICK.
    if (swfobject.hasFlashPlayerVersion("1")) {
        //Flash works so ignore the HTML5 video handling below.
    }
    else {
        $('.home-watch-video').click(function (e) {
            e.preventDefault();
            var id = e.target.id;
            $('.' + id + ':not(:first)').addClass('duplicate-modal');
            $('.' + id).modal({
                close: 'true',
                overlayClose: 'true',
                zIndex: 999999,
                onShow: function () {
                    var htmlSource1 = $('.' + id + ' #video source:nth-child(1)').data('source');
                    var htmlSource2 = $('.' + id + ' #video source:nth-child(2)').data('source');
                    $('.' + id + ' #video source:nth-child(1)').attr('src', htmlSource1);
                    $('.' + id + ' #video source:nth-child(2)').attr('src', htmlSource2);
                    var player = $('.' + id + ' video').get(0);
                    window.p = player;
                    player.load();
                    player.play();
                } //end onShow
            }); // end modal
            var player = $('.' + id + ' video').get(0);
            window.p = player;
            player.load();
            player.play();
        }); // end click
    }



    //homepage slider
    $('.products-btn').hide();
    $('.panel-carousel').hide();
    $('.news-btn').click(function () {
        $('.news-btn, .news-thumb-container').delay(800).fadeOut(500);
        $('.panel-carousel').delay(1000).fadeIn(500);
        $('.panel-text-container').fadeOut(500);
        $('.news-panel').stop(true, true).delay(1000).animate({ left: '215' }, { easing: 'easeOutCirc', duration: 1000 });
        $('.products-btn').fadeIn(500);
        $('.panel-carousel').css({ opacity: '1' }).delay(1200).fadeIn(500);
        $('.panel-nav').delay(500).animate({ left: '0' }, { easing: 'easeOutCirc', duration: 500 }).fadeIn(500);
    });
    $('.products-btn').click(function () {
        $('.products-btn, .panel-carousel').fadeOut(500);
        $('.news-panel').stop(true, true).animate({ left: '400' }, { easing: 'easeOutCirc', duration: 1000 });
        $('.news-btn, .news-thumb-container').fadeIn(500);
        $('.panel-text-container').delay(1500).fadeIn(500);
        $('.panel-nav').delay(1100).animate({ left: '175' }, { easing: 'easeOutCirc', duration: 500 });
    });



	
    // mega nav
    var config = {
        over: function () {
            if (isFixed) {
                $(this).addClass('nav-item-active').children(':not(".nav-tab")').stop(true, true).delay(150).fadeIn(200, 'easeInOutQuart');
            }
            if (!isFixed) {
                $(this).addClass('nav-item-active').children(':not(".nav-tab")').stop(true, true).delay(300).fadeIn(200, 'easeInOutQuart');
            }
			$('.nav-overlay').show();
			$('.nav-bg').stop(true, true).slideDown(500, 'easeInOutQuart');

			
        },
        out: function () {
			if (isFixed) {
                $(this).removeClass('nav-item-active').children(':not(".nav-tab")').stop(true, true).fadeOut(0, 'easeInOutQuart');
            }
            if (!isFixed) {
                $(this).removeClass('nav-item-active').children(':not(".nav-tab")').stop(true, true).fadeOut(0, 'easeInOutQuart');
            }
        },
        timeout: 90
    };
    $('.main-nav .nav-item').hoverIntent(config);

    var overlayConfig = {
        over: function () {
            $('.nav-bg').stop(true, true).slideDown(500, 'easeInOutQuart');
            $('.nav-overlay').fadeIn(200);
        },
        out: function () {
            $('.nav-bg').stop(true, true).slideUp(300, 'easeInOutQuart');
            $('.nav-overlay').hide();
        },
        timeout: 90
    }
    $('.main-nav').hoverIntent(overlayConfig);
	
	//Disable Agent
	$('.main-nav-agent').mouseover(function(){
		$('.nav-overlay, .nav-bg').hide();
	});
	//Hide if mouse stucl
	$('.nav-overlay').mouseover(function(){
		$('.nav-overlay').hide();
		$('.nav-bg').stop(true, true).slideUp(500, 'easeInOutQuart');
	});
	
	

    // insurance buttons
    $('.panel-text:not("#icon-ins1")').hide();


    // insurance buttons
    if ($('.panel-nav').length > 0) {
        var lgImg = $('.icon-ins1').attr('data-image-large');
        $('.icon-ins1').children().attr('src', lgImg);
        $('.panel-text:not("#icon-ins1")').hide();
        $('.panel-nav a').mouseover(function (e) {
            e.preventDefault();
            $('.panel-text').hide();
            var ins = $(this).attr('class');
            var lgImg = $(this).attr('data-image-large');

            $('.panel-nav ul li a').each(function () {
                var smImg = $(this).attr('data-image-small');
                $(this).children().attr('src', smImg);
            });
            $(this).children().attr('src', lgImg);
            $('.panel-text:visible').stop(true, true).fadeOut('fast');
            $('.panel-text#' + ins).stop(true, true).fadeIn('fast');
        });
    }

    // text resize
    $('body').removeClass('small medium large');
    $('body').addClass('small');
    if ($.cookie('TEXT_SIZE')) {
        $('body').addClass($.cookie('TEXT_SIZE'));
        if ($.cookie('TEXT_SIZE') == 'small') {
            $('li.small').addClass('current');
        }
        if ($.cookie('TEXT_SIZE') == 'medium') {
            $('li.medium').addClass('current');
        }
        if ($.cookie('TEXT_SIZE') == 'large') {
            $('li.large').addClass('current');
        }
    }
    $('.text-resizer a').click(function (e) {
        e.preventDefault();
        var textSize = $(this).parent().attr('class');
        $('body').removeClass('small medium large').addClass(textSize);
        $('.text-resizer li').removeClass('current');
        $(this).parents('li').addClass('current');
        $.cookie('TEXT_SIZE', textSize, { path: '/', expires: 10000 });
    });

    //advanced search functionality
    $('.advanced-link').click(function (e) {
        e.preventDefault();
        $('.advanced-search').stop(true, true).slideToggle(700, 'easeOutCirc');
    });



    // First set of table tabs
    var tableTabs = function () {

        $('.table-tabs').each(function () {
            $(this).children('div:first').show();
            $(this).find('ul li:first').addClass('current');
        });

        $('.table-tabs ul.tabs-list li').click(function (e) {
            $(this).parents('.table-tabs').children('div').hide();
            $(this).parents('.table-tabs').find('.current').removeClass('current');
            $(this).addClass('current');

            var clicked = $(this).find('a:first').attr('href');
            $('.table-tabs ' + clicked).fadeIn('fast');
            e.preventDefault();
        });

    } ();



    //table background
    $('.table-tabs tbody tr:odd').css({ background: '#efefef' });

    //search results hover
    $('.agent-result, .discount-result, .search-result').hover(
        function () {
            $(this).css({ background: '#f0f0f0' });
        },
        function () {
            $(this).css({ background: '#ffffff' });
        });

    // Search pagination
    $('ul.pagination li').hide();
    $('ul.pagination li:first').show();
    //right button
    $('.btn-right').click(function (e) {
        e.preventDefault();
        $('ul.pagination li:visible').hide().next().show();
        if ($('ul.pagination li:visible').index() == -1) {
            $('ul.pagination li:visible').hide();
            $('ul.pagination li:first').show();
        }
        var pageTotal = $('ul.pagination li').length;
        var pageCurrent = $('ul.pagination li:visible').index() + 1;
        $('span.pages').html('PAGE <span class="current">' + pageCurrent + '</span> OF <span class="total">' + pageTotal + '</span>');
    });
    //left button
    $('.btn-left').click(function (e) {
        e.preventDefault();
        $('ul.pagination li:visible').hide().prev().show();
        if ($('ul.pagination li:visible').index() == -1) {
            $('ul.pagination li:visible').hide();
            $('ul.pagination li:last').show();
        }
        var pageTotal = $('ul.pagination li').length;
        var pageCurrent = $('ul.pagination li:visible').index() + 1;
        $('span.pages').html('PAGE <span class="current">' + pageCurrent + '</span> OF <span class="total">' + pageTotal + '</span>');
    });

    // Display paging information
    var pageTotal = $('ul.pagination li').length;
    var pageCurrent = $('ul.pagination li:visible').index() + 1;
    $('span.pages').html('PAGE <span class="current">' + pageCurrent + '</span> OF <span class="total">' + pageTotal + '</span>');


    // Scroll to top of results when using bottom pagination
    jQuery('#pagination2 .btn-left, #pagination2 .btn-right').click(function () {

        // When bottom pagination is clicked, scroll to the top
        var catTopPosition = jQuery('a#top').offset().top;

        // Scroll down to 'catTopPosition'
        jQuery('html, body').animate({ scrollTop: catTopPosition }, 'slow');
        // Stop the link from acting like a normal anchor link
        return false;
    });

    // Hide bottom pagination if no search results are returned
    if ($('ul.pagination li').length == 0) {
        $('#pagination2').hide();
    };

    // REPLACE FORM VAL()

    $("input.sign-search, input.search-results-txt, input.agent-search-box")
      .focus(function () {
          if (this.value === this.defaultValue) {
              this.value = '';
          }
      })
      .blur(function () {
          if (this.value === '') {
              this.value = this.defaultValue;
          }
      });

    // RESET BUTTON
    $('.clear-btn').click(function () { $('#paymentdate').val(""); $('#policynumber').val(""); $('#zipcode').val(""); });



    //MODAL FUNCTIONALITY

    $('.watch-bubble-vid').click(function (e) {
        e.preventDefault();
        $('#bubbleVid').modal({
            close: 'true',
            overlayClose: 'true',
            zIndex: 999999
        });
    });
    $('.watch-puppet-vid').click(function (e) {
        e.preventDefault();
        $('#puppetVid').modal({
            close: 'true',
            overlayClose: 'true',
            zIndex: 999999
        });
    });
    $('.watch-fan-vid').click(function (e) {
        e.preventDefault();
        $('#fanVid').modal({
            close: 'true',
            overlayClose: 'true',
            zIndex: 999999
        });
    });


    $(".sign-search").bind('keypress', function (e) {
        if (e.which == 13) {
            window.location = "/general/agent-locator-search-results?searchQuery=" + $(".sign-search").val();
            e.preventDefault();
        }
    });
    $(".sign-go-btn").click(function (e) {

        window.location = "/general/agent-locator-search-results?searchQuery=" + $(".sign-search").val();
        e.preventDefault();
    });
    $(".agent-search-box").bind('keypress', function (e) {
        if (e.which == 13) {
            window.location = "/general/agent-locator-search-results?searchQuery=" + $(".agent-search-box").val();
            e.preventDefault();
        }
    });
    $(".agent-search-btn").click(function (e) {

        window.location = "/general/agent-locator-search-results?searchQuery=" + $(".agent-search-box").val();
        e.preventDefault();

    });
    $(".body-search-zip-txt").bind('keypress', function (e) {
        if (e.which == 13) {
            BodySearchFunction(1);
            e.preventDefault();
        }
    });



	//Agent result extra address field removal if empty
	$('.agent-result-column ul li').filter(function() {return $(this).text() == '';}).remove();
	
	
	$('a.more-results, a.page-button').click(function(){
		$('.agent-result-column ul li').delay(3000).filter(function() {return $(this).text() == '';}).remove();
	});


    //////////////////////////////////
    //                              //
    //     Body search functions    //
    //                              //
    //////////////////////////////////

    $('.body-search-zip-btn').click(function () {

        BodySearchFunction(1);
        //$('.body-search-results-container');
    });


    $('#body-search-county').change(function (e) {

        if (this.selectedIndex === 0) {

        }
        else {
            BodySearchFunction(0);
        }
        e.preventDefault();
        //$('.body-search-results-container');
    });

    $('.body-search-zip-txt').click(function () {
        if ($('.body-search-zip-txt').val().toLowerCase() == "enter a zip code") {
            $('.body-search-zip-txt').val('');
        }
    });



    //Baseball card carousel
    $(".baseball-carousel").jCarouselLite({
        btnNext: ".baseball-next",
        btnPrev: ".baseball-prev",
        visible: 3,
        easing: 'easeOutCirc',
        speed: 500
    });
    swapCards = function () {
        $('.card-front').click(function (e) {
            e.preventDefault();
            e.stopPropagation()
            $(this).stop(true, true).prev().fadeIn(800).next().fadeOut(800);
        });
        $('.card-back').click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).stop(true, true).next().fadeIn(800).prev().fadeOut(800);
        });

    }

    swapCards();


    //////////////////////////////////
    //                              //
    // Discount state radio buttons //
    //                              //
    //////////////////////////////////
    $('.discount-radio-selector input:radio').click(function (e) {
        $('.discount-tble').hide();

        var id = $('.discount-radio-selector input:radio[name=State]:checked').val();
        $('.grp-' + id).show();

    });



    //Switch Tables based on state
    $('input[value=MA]').attr('checked', 'checked');
    $('.table-tabs').eq(1).hide();
    $('input[name="State"]').click(function () {
        var selectedState = $(this).val();
        if (selectedState === "MA") {
            $('.table-tabs').eq(0).show();
            $('.table-tabs').eq(1).hide();
        }
        else {
            $('.table-tabs').eq(1).show();
            $('.table-tabs').eq(0).hide();
        }
    })


    //Allow only one account type on automated payment form

    $('input#checking').click(function () {
        $('input#checking').siblings('a').addClass('jqTransformChecked');
        $('input#saving').attr('checked', 'unchecked');
        $('input#saving').siblings('a').removeClass('jqTransformChecked');
    });
    $('input#saving').click(function () {
        $('input#saving').siblings('a').addClass('jqTransformChecked');
        $('input#checking').attr('checked', 'unchecked');
        $('input#checking').siblings('a').removeClass('jqTransformChecked');
    });



    $(".filter-container input:radio[name*='DiscountTableRadio']").live('click', function () {

        var selected = $(".filter-container input:radio[@name='DiscountTableRadio']:checked").val();
        if (selected == 'All') {
            $('.DiscountItem').show();
        }
        else {
            $('.DiscountItem').hide();
            $('.' + selected).show();

        }
    });
    setTimeout(positionSign, 200);
});          // end document ready agent-search-btn







var zipcode;
var county;
function BodySearchFunction(whichCaller) {
    var bpageTotal = 0;
    var bcurrentPageCount = 0;
    var bpageTotal = 0;
    zipcode = "";
    county = "";

    var re = /^\d{5}([\-]\d{4})?$/;
    if (whichCaller === 1) {
        zipcode = $('.body-search-zip-txt').val();
        
    }
    else if (whichCaller === 0) {

        county = $('#body-search-county').val();
    }
    if (re.test(zipcode) || county.length > 0){


        $.ajax({
            type: "POST",
            url: "/App_Webservices/Public/WebServices.asmx/GetBodyShopsByLocation",
            data: "{ json:'" + JSON.stringify({
                "ZipCode": zipcode,
                "County": county,
                "PageIndex": 1
            })
                + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {
                var jsonObject = $.parseJSON(obj.d);
                $('.body-search-results-container').html('');
                $('.body-search-results-container').html(jsonObject.Json.Html);

                bpageTotal = parseInt(jsonObject.Json.Count);
                var html = "";
                html += "<div class=\"page-button-case\">";
                for (var i = 1; i <= jsonObject.Json.TotalPages; i++) {
                    html += " <a href=\"#top\" class=\"page-button\" rel=\"" + i + "\">" + i + "</a> ";
                }
                html += "</div>";
                $('.search-results .clear').after(html);
                $('a[rel="1"]').addClass('page-button-current');
                bindPageButton();
            }
        });
    }
    else {
        $('.body-search-results-container').html('');
        $('.body-search-results-container')
        .html('<div class="search-results-container" style="text-transform:none;">Please enter a valid ZIP code</div>');
    }
}

function bindPageButton() {
    $('.page-button').click(function (e) {
        var queryString2 = getQuerystring("searchQuery");
        var newPage = this.rel;
        $.ajax({
            type: "POST",
            url: "/App_Webservices/Public/WebServices.asmx/GetBodyShopsByLocation",
            data: "{ json:'" + JSON.stringify({
                "ZipCode": zipcode,
                "County": county,
                "PageIndex": this.rel
            })
                    + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {
                var json1 = $.parseJSON(obj.d);
                $('.body-search-results-container').html('');
                $('.body-search-results-container').html(json1.Json.Html);

                bpageTotal = parseInt(json1.Json.Count);
                var html = "";
                html += "<div class=\"page-button-case\">";
                for (var i = 1; i <= json1.Json.TotalPages; i++) {
                    html += " <a href=\"#top\" class=\"page-button\" rel=\"" + i + "\">" + i + "</a> ";
                }
                html += "</div>";

                $('.search-results .clear').after(html);
                $('.page-button-current').removeClass('page-button-current');
                $('a[rel="' + newPage + '"]').addClass('page-button-current');
                bindPageButton();
            }
        });

    });
}


function isValidZipCode(value) {
    var re = /^\d{5}([\-]\d{4})?$/;
    return (re.test(value));
}




    function getQuerystring(key) {
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs == null)
            return "";
        else
            return qs[1];
    };
	
	
	
	

			



