/*
	
	Hagerty Global Javascript Functions
	ISITE Design

*/

// jQuery document ready
jQuery(function ($) {

    //This disables the form from being submitted when the enter key pressed (default is search button)
    //    $j("form").keypress(function(e) {
    //        return (e.which != 13);
    //       });
    $('input:not(textarea)').live('keypress', function (e) {
        if (e.which == 13) return false;
        if (e.which == 13) e.preventDefault();
    });


    $j("#hva-login").unbind('keypress');

    // JS enabled
    $('html').addClass('js');

    // Few setups for IE6
    if (HIA.ie6) {
        //add class to drop downs and buttons 
        $('button').hover(
			function () { $(this).addClass('hover'); },
			function () { $(this).removeClass('hover'); }
	    );
        // first child support
        $('ul.inline li:first-child,#tertiary h5:first-child,#full-widgets .block:first-child').addClass('first-child');

        $(".dp-popup").bgiframe();

    } // if ie6

    // last-child for footer
    $('#footer ul.left li:last-child').addClass('last-child');

    // input field clearer
    //$('.form-search input').inputSetter();

    // empower print
    $('<li class="nav-action-print"><a href="#">Print</a></li>').insertAfter('.nav-action-email').find('a').click(function () { window.print(); return false; });

    // cycle articles
    HIA.cycle($('.articles'));

    // enable circular scrollables with a click handler
    HIA.scroll($('.scroll'));

    // enable date picking
    HIA.pickDates($('input.date-picker'));

    // set up rating widgets
    HIA.starRating();


    // galleriffic (Don't init on HPG vehicle info photo gallery)
    if ($('#pnlHccrVehicleInfo_VehiclePhotoGallery').length == 0) {
        if ($.galleriffic && $('#thumbs').length) {
            HIA.galleriffy.numThumbs = $('.gallery-full').length ? 9 : 5;
            $('#thumbs').galleriffic(HIA.galleriffy);
        }
    }

    // standard overlay for external content
    $("a.external-overlay-trigger").overlay({
        onBeforeLoad: function () {
            var wrap = this.getOverlay().find(".content-wrap");
            wrap.load(this.getTrigger().attr("href"), function () {
                if (jQuery('#thumbs-gs').length) {
                    $('#gallery-overlay #thumbs-gs').galleriffic({
                        numThumbs: 8, // The number of thumbnails to show page
                        preloadAhead: 18, // Set to -1 to preload all images
                        imageContainerSel: '#slideshow-gs', // The CSS selector for the element within which the main slideshow image should be rendered
                        controlsContainerSel: '#controls-gs', // The CSS selector for the element within which the slideshow controls should be rendered
                        captionContainerSel: '#caption-gs', // The CSS selector for the element within which the captions should be rendered
                        loadingContainerSel: '#loading-gs' // The CSS selector for the element within which should be shown when an image is loading
                    });
                }
            });
        }
    });
    if (!$('#overlay').length && $('a.overlayed').length) {
        $('body').append('<div class="standard-overlay" id="overlay"><div class="content-wrap"></div></div>');
    }
    $('a.overlayed').overlay({
        onBeforeLoad: function () {
            var wrap = this.getOverlay().find(".content-wrap");
            wrap.load(this.getTrigger().attr('href'));
        }
    });

    // toggle extra form fields depending on radio selection
    $('div.form li.toggler')
		.find('fieldset.option').hide().end()
		.find('input.trigger').click(function () {
		    var obj = $(this).parents('li.toggler'),
				val = $(this).val();
		    obj.find('fieldset.option').hide();
		    obj.find('fieldset.' + val).show();
		});

    // toggle fields depending on form type
    HIA.toggleFields();

    // count characters
    $('label.characters-remaining').charactersRemaining();
});      // document ready


// application logic
var HIA = {
    galleriffy: {
        numThumbs: 5, // The number of thumbnails to show page
        preloadAhead: 18, // Set to -1 to preload all images
        defaultTransitionDuration: 0, // zero to prevent doulbing of images on double click
        imageContainerSel: '#slideshow', // The CSS selector for the element within which the main slideshow image should be rendered
        controlsContainerSel: '#controls', // The CSS selector for the element within which the slideshow controls should be rendered
        captionContainerSel: '#caption', // The CSS selector for the element within which the captions should be rendered
        loadingContainerSel: '#loading', // The CSS selector for the element within which should be shown when an image is loading
        enableKeyboardNavigation: false // protect Sitecore's page edit mode 
    },
    ie6: $j.browser.msie && parseInt($j.browser.version) < 7 ? true : false,
    cycle: function (obj) {

        if (obj.length == 0) return;

        var articles = $j('.article', obj),
        //height 		= HIA.maxHeight(articles),
			thumbs = $j('.carousel a', obj),
			fade = '0.5';

        // articles.css({'height':height})
        articles.not(':first').hide().end().first().addClass('current');
        if (!HIA.ie6) { thumbs.first().css('opacity', fade); }

        thumbs.live('click', function () {

            var article = $j(this).parents('li').index();

            if (!HIA.ie6) {
                thumbs.fadeTo('fast', 1);
                $j(this).fadeTo('fast', fade);
            }

            articles.filter('.current').fadeOut(function () {
                articles.removeClass('current');
                articles.eq(article).addClass('current').fadeIn();
            });

            return false;

        });

    },

    scroll: function (obj) {

        var thumbs = $j('.items a', obj);

        if (obj.length == 0) return;

        // if there are less than 2 items, don't scroll
        if (thumbs.length < 2) return;

        var s = { root: obj.scrollable({ circular: true }).autoscroll({ interval: 8000, autopause: false }).navigator('.nav-scroll') };
        s.nav = s.root.next();
        s.nav.slideDown('slow');

        s.api = s.root.data("scrollable");

        $j('a:not(.toggle)', s.nav).click(function (e) {
            e.preventDefault();
            $j('.toggle', s.nav).removeClass('pause').text('Play');
            s.api.stop();
            s.to = setTimeout(function () { $j('.toggle', s.nav).click(); }, 60000);
        });
        $j('.nav-scroll li:first', s.nav).addClass('active');

        $j('.toggle', s.nav).click(function () {
            var obj = $j(this),
				pause = obj.is('.pause');

            obj.toggleClass('pause').text(pause ? 'Play' : 'Pause');
            s.api[pause ? 'stop' : 'play']();
            clearTimeout(s.to);
            return false;
        });

    },

    maxHeight: function ($els) {
        var h = 0;
        $els.each(function () { h = h < parseInt(jQuery(this).height()) ? parseInt(jQuery(this).height()) : h; });
        return h;
    },

    pickDates: function (obj) {
        if (obj.length > 0) {
            Date.firstDayOfWeek = 7;
            Date.format = 'mm/dd/yyyy';

            $j('input.date-picker')
				.not('.future').datePicker({ startDate: '01/01/2008' }).end()
				.filter('.future').datePicker({ startDate: (new Date()).asString() }).end()
				.filter('.date-start,.date-end').bind("dpClosed", function (e, selectedDates) {
				    var d = selectedDates[0],
						type = $j(this).is('.date-start'); // switch for ternary chain below. do opposite for start/end picker					
				    if (d) {
				        d = new Date(d);
				        // in this field's parent fieldset, find input based on type. set either date end or start property based on type. set target date as 1 day ahead for start or 1 day behind for end
				        $j(this).parents("fieldset").find(type ? "input.date-end" : "input.date-start")[type ? 'dpSetStartDate' : 'dpSetEndDate'](d.addDays(type ? 1 : -1).asString());
				    }
				});
        } // end date pick		
    },

    starRating: function () {
        $j('input.star-rating').rating({
            callback: function (v, l) {
                var input = $j(this),
					val = $j(l).attr('title');
                if (val.indexOf("star") < 1) {
                    input.siblings('input').andSelf().rating('disable');
                    input.parents('.rating').attr('title', "You rated this article " + val).find('a').removeAttr('title');

                    jQuery.ajax({
                        url: window.location.href + "?async=1&rating=" + val * 2
                    });
                }

            }
        });
        $j('input.star-display').rating();
        $j('.rating-display a').removeAttr('title');
    },

    toggleFields: function () {

        var showtext = { show: "Add location to search", hide: "Remove location from search" };
        $j('ul.more.hide').hide();
        $j('fieldset a.trigger').click(function () {
            var that = $j(this),
				advanced = that.text() == showtext.hide;

            that.closest('fieldset').find('.more').slideToggle("fast");
            that.text(advanced ? showtext.show : showtext.hide);
            setCookie("searchtype", advanced ? "basic" : "advanced", 14, "/");

            return false;
        });
    }

};

// jQuery plugins
jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this);
		var $label = jQuery("label[for='"+$input.attr("id")+"']");
		var labeltext = lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();	
		$input.val(labeltext);		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; }	})
			  .blur(function() { if (!this.value.length) { this.value = labeltext; } });		
	});
};

jQuery.fn.charactersRemaining = function() {	
    // prevent elem has no properties error
    if (this.length === 0) { return(this); }	
	function cr($obj) {
		var counter = {			
			$target	 	: jQuery("#"+$obj.attr('for')),
			$span		: $obj.find("span:first"),
			maxvalue 	: $obj.children('span:first').text(),
			remaining	: null,
			
			init : function() {
				counter.remaining = counter.maxvalue - counter.$target.val().length;
				counter.$span.text(counter.remaining);
				counter.$target.bind("keyup keydown",counter.tally);			
			},
			
			tally : function() {								
				if (counter.$target.val().length > counter.maxvalue) { 
					counter.$target.val(counter.$target.val().substring(0, counter.maxvalue));
				}
				counter.$span.text(counter.maxvalue - counter.$target.val().length);				
			}			
		};
		// init the counter
		counter.init($obj);
	};	
	// return jquery - create new cr instance
	return this.each(function() {
		new cr(jQuery(this));		
	});		
};

// etc
// Cookies get/set/delete
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null;	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; }
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "/" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "/") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
// end cookies

// IE6 fixes
// make sure IE has the abbr and acronym tag
if(document.all){
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch (e) { }

// jquery no conflict. use $ or jQuery outside of ready function
var $j = jQuery.noConflict();

// Start Filter Sort

 var Collection = function () {
     this.count = 0,
            this.collection = {},
            this.add = function (key, item) {
                if (this.collection[key] != undefined)
                    return undefined;
                this.collection[key] = item;
                return ++this.count;
            },
            this.remove = function (key) {
                if (this.collection[key] == undefined)
                    return undefined;
                var oldTarget = this.collection[key];
                delete this.collection[key];
                --this.count;
                return oldTarget;
            },
            this.item = function (key) {
                return this.collection[key];
            }
 };

 var Pairings = new Collection();

 var FilterSort = {
     sortCriterium: "",
     filterCriterium: "",
     baseHref: function () { return FilterSort.getBase() },
     getBase: function () {
         var base = location.href;
         if (location.href.indexOf("?") > -1) {
             base = location.href.substring(0, location.href.indexOf("?"));
         }
         return base;
     },
     applyFilter: function (val) {
         FilterSort.filterCriterium = val;
         FilterSort.redirect();
     },
     applySort: function (val) {
         FilterSort.sortCriterium = val;
         FilterSort.redirect();
     },
     getQueryStringParam: function (varName) {
         var queryStr = unescape(window.location.search) + '&';
         var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');

         var val = queryStr.replace(regex, "$1");

         return val == queryStr ? "" : val;
     },
     redirect: function () {
         var newQs = "?";

         var pairs = Pairings.collection;
         if (Pairings.count > 0) {
             for (var pair in pairs) {
                 if (newQs.length != 1)
                     newQs += "&";
                 newQs += pair;
                 newQs += "=" + escape(pairs[pair]);
             }
         }
         if (FilterSort.sortCriterium.length > 0) {
             if (newQs.length > 1) {
                 newQs += "&";
             }
             newQs += "sortby=" + FilterSort.sortCriterium;
         }
         if (FilterSort.filterCriterium.length > 0) {
             if (newQs.length > 1) {
                 newQs += "&";
             }
             newQs += "filterby=" + escape(FilterSort.filterCriterium);
         }

         window.location = FilterSort.baseHref() + newQs;
     },
     putOtherQSParamsInCollection: function () {
         if (location.search.length > 0) {
             var qs = location.search.replace("?", "");
             var pairs = unescape(qs).split("&");

             for (var i = 0; i < pairs.length; ++i) {
                 var pair = pairs[i];
                 var keyval = pair.split("=");
                 if (keyval[0] != "filterby" && keyval[0] != "sortby")
                     Pairings.add(keyval[0], keyval[1]);
             }
         }
     },
     trackFilter: function () {
         var newVal = $j(".track-filter").val();
         trackAnalytics("FilteredList", newVal.replace(/ /g, ''), "ReviewsPage")

     },
     trackSort: function () {
         trackAnalytics("SortedList", $j(".track-sort").val(), "ReviewsPage")
     }
 };


 // jquery no conflict. use $ or jQuery outside of ready function
 var $j = jQuery.noConflict();

 jQuery(function ($) {

     FilterSort.sortCriterium = FilterSort.getQueryStringParam("sortby");
     FilterSort.filterCriterium = FilterSort.getQueryStringParam("filterby");

     FilterSort.putOtherQSParamsInCollection();

     $j('.filter-list').change(function () {
         FilterSort.trackFilter();
         FilterSort.applyFilter($(this).val());
     });

     $j('.sort-list').change(function () {
         FilterSort.trackSort();
         FilterSort.applySort($(this).val());
     });
 });

 //End Filter Sort

 //Begin Display Overlay
 var Overlay = {
     overlayGuid: "",
     retrieveContent: function (path) {
         if (!Overlay.getGuidFromPath(path))
             return false;

         var xmlHttpReq = createXMLHttpRequest();
         xmlHttpReq.open("GET", "/Handlers/ContentRetrieval.ashx?guid=" + Overlay.overlayGuid, false);

         xmlHttpReq.onreadystatechange = function () {
             if (xmlHttpReq.readyState == 4) {
                 if (xmlHttpReq.status == 200) {
                     var content = xmlHttpReq.responseText;

                     if (content.length > 0) {
                         $j('#content-overlay').html(content);
                         $j("#content-overlay").dialog('open');
                         return true;
                     }
                     else {
                         return false;
                     }
                 }
                 if (xmlHttpReq.status == 500) {
                     return false;
                 }
             }
         }

         xmlHttpReq.send(null);
     },
     getGuidFromPath: function (path) {
         if (path.indexOf("link.aspx") > -1) {
             Overlay.overlayGuid = path.substring(path.indexOf("id=") + 3, path.indexOf("&"));
             return true;
         }
         // link is not internal link; just follow link
         return false;
     }
 }

 function createXMLHttpRequest() {
    try { return new XMLHttpRequest(); } catch (e) { }
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } 
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
    return null;
}

jQuery(function ($) {

    $j('.general-overlay').click(function () {
        var linkIsGood = Overlay.retrieveContent(this.attributes["href"].value);
        if (this.attributes["title"].value.length > 1)
            $("#content-overlay").dialog({ title: this.attributes["title"].value });
        if ((linkIsGood) || (linkIsGood == undefined))
            return false;
        else {
            this.attributes["target"].value = "_blank";
            return;
        }


    });

    var dialogOpts = {
        autoOpen: false,
        modal: true,
        title: "INFO",
        height: 600,
        bgiframe: true,
        position: 'top',
        width: 525,
        zIndex: 2,
        show: 'blind',
        hide: 'blind',
        dialogClass: 'overlay-class'
    };

    // initialize dialog box
    $("#content-overlay").dialog(dialogOpts);

});
 //End Overlay



