(function (j$) {
    j$(document).ready(function () {
        // -- Cookie Code -- //
        var normalTextSize = 12;
        var oneSizeUpTextSize = 14;
        var twoSizesUpTextSize = 17;
        //units in which the text size is determined
        var textSizeUnits = "px";
        //in days, number of days to persist the textsize cookie
        var cookieLife = 365; //changed from 365 to 1 per client request 1/12/2010
        // name of the cookie
        var cookieName = "textsizestyle";
        var cookieNameClasses = "whichButtonPressed";

		/*
        //Agency Locator default text
        j$("#agency_finder input[type*='text']").val("Enter a Zip Code").attr("style", "color:#C2C2C2;");
        j$("#agency_finder input[type*='text']").focus(function () {
            if (j$("#agency_finder input[type*='text']").val() == "Enter a Zip Code") {
                j$("#agency_finder input[type*='text']").val("").attr("style", "color:#000;");
            }
        });
        j$("#agency_finder input[type*='text']").blur(function () {
            if (j$("#agency_finder input[type*='text']").val() == "") {
                j$("#agency_finder input[type*='text']").val("Enter a Zip Code").attr("style", "color:#C2C2C2;");
            }
        });
		*/

		
        //Searchbox default text
        j$("#header_search input[type*='text']").val("Enter a Keyword").attr("style", "color:#C2C2C2;");
        j$("#header_search input[type*='text']").focus(function () {
            if (j$("#header_search input[type*='text']").val() == "Enter a Keyword") {
                j$("#header_search input[type*='text']").val("").attr("style", "color:#000;");
            }
        });
        j$("#header_search input[type*='text']").blur(function () {
            if (j$("#header_search input[type*='text']").val() == "") {
                j$("#header_search input[type*='text']").val("Enter a Keyword").attr("style", "color:#C2C2C2;");
            }
        });
		
		
        // Global "Enter" keypress override of default <form> action to submit.
        j$("input").keypress(function (event) {
            if (event.which === 13) {
                event.preventDefault();
            }
        });
		
		
        //Keypress fix for the agency locator Module
		/*j$("#agency_finder .aoi_form input[type*='text']").keypress(function (event) {
			if (event.which == 13) {
				j$("#agency_finder .aoi_form a").click();
			}
		});*/


		/*j$("#agency_finder .aoi_form a.form_submit_quote").click(function(event) {
			var findButton = j$(this);
			var zipCodeField = j$("#agency_finder input[type*='text']");
			var isValid = true;
			var validators = null;
			
			// Manually invoke all ASP.NET Validators assigned to the textbox.
			if (ValidatorValidate)
			{
				validators = zipCodeField.nextAll(".NormalRed:parent");

				if (validators.length > 0) 
				{
					for (var i = 0; i < validators.length; i++)
					{
						if (validators[i])
						{
							ValidatorValidate(validators[i]);

							if (validators[i].isvalid === false)
							{
								isValid = false;
							}
						}
					}
				}
			}

			// If the ASP.NET Validators pass validation, the validate the zip code against the database.
			if (isValid === true)
			{
				event.preventDefault();

				validateZipCode_ServerSide(zipCodeField.val(), function(result) {
					if (result.d === true)
					{
						j$("#agency_finder .aoi_form tr.quoting_validator_row").remove();
						eval(findButton.attr("href"));
					}
					else
					{
						if (ValidatorUpdateDisplay && validators.length > 0)
						{
							validators.each(function(i) {
								j$(this)[0].isvalid = true;
								ValidatorUpdateDisplay(j$(this)[0]);
							});

							j$("#agency_finder .aoi_form tr.quoting_validator_row").remove();
							validators.first().closest("tr").after('<tr class="quoting_validator_row"><td colspan="2"><span class="NormalRed">Quoting is not available for this zip code</span></td></tr>');
						}

						return;
					}
				}, function(response) {
					return false;
				});
			}
			else
			{
				j$("#agency_finder .aoi_form tr.quoting_validator_row").remove();
				return false;
			}
		});*/


		/*var validateZipCode_ServerSide = function(zipCode, successHandler, failureHandler) {
			j$.ajax({
				type: "GET",
				url: "/Portals/0/AgencyValidationClientService.svc/ValidatePublicQuotingZipCode",
				data: 'zipCode=' + zipCode,
				contentType: "application/json; charset=utf-8",
				dataType: "json", 
				success: function(result) { 
					if (successHandler)
					{
						successHandler(result);
					}
				},
				error: function(response) {
					if (failureHandler)
					{
						failureHandler(response);
					}
				}
			});
		};*/
		
		//Fix for clicking "find" and having it search on "Enter a Keyword". Blanks out search field if that text is there.
		j$("#header #header_search a").click(function (event){
			event.preventDefault();
			if (j$("#header_search input[type*='text']").val() == "Enter a Keyword") {
				j$("#header_search input[type*='text']").val("");
			}
			window.location = j$("#header #header_search a").attr("href");
		});

        // -- Text Resizer Code -- //
        checkCookie();
        j$("#text_resize a").click(function (event) {
            j$(".text_here").removeClass("text_here");
            j$(this).addClass("text_here");
        });
        j$("#smallFont").click(function (event) {
            j$("#text_resize a").attr("style", "text-decoration:none;");
            j$("#smallFont").attr("style", "text-decoration:underline;");
            setPageFontSize(normalTextSize);
            setCookie(normalTextSize, "smallFont");
        });
        j$("#mediumFont").click(function (event) {
            j$("#text_resize a").attr("style", "text-decoration:none;");
            j$("#mediumFont").attr("style", "text-decoration:underline;");
            setPageFontSize(oneSizeUpTextSize);
            setCookie(oneSizeUpTextSize, "mediumFont");
        });
        j$("#largeFont").click(function (event) {
            j$("#text_resize a").attr("style", "text-decoration:none;");
            j$("#largeFont").attr("style", "text-decoration:underline;");
            setPageFontSize(twoSizesUpTextSize);
            setCookie(twoSizesUpTextSize, "largeFont");
        });

        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function setCookie(theSize, theButton) {
            createCookie(cookieName, theSize, cookieLife);
            createCookie(cookieNameClasses, theButton, cookieLife);
        }

        function setPageFontSize(theSize) {
            document.body.style.fontSize = theSize + textSizeUnits;

            var h2s = document.getElementsByTagName("h2");
            for (var index = 0; index < h2s.length; index++) {
                h2s[index].style.fontSize = (parseInt(theSize) + 8).toString() + textSizeUnits;
            }
            var h3s = document.getElementsByTagName("h3");
            for (var index = 0; index < h3s.length; index++) {
                h3s[index].style.fontSize = (parseInt(theSize) + 2).toString() + textSizeUnits;
            }
            var h4s = document.getElementsByTagName("h4");
            for (var index = 0; index < h4s.length; index++) {
                h4s[index].style.fontSize = (parseInt(theSize) + 1).toString() + textSizeUnits;
            }
            var h5s = document.getElementsByTagName("h5");
            for (var index = 0; index < h5s.length; index++) {
                h5s[index].style.fontSize = (parseInt(theSize) + 0).toString() + textSizeUnits;
            }
        }
        function setButtonHereClass(theButton) {
            addClass(document.getElementById(theButton), "text_here");
        }
        function checkCookie() {
            if (readCookie(cookieName) != null) {
                setPageFontSize(readCookie(cookieName));
            }
            else {
                setPageFontSize(normalTextSize);
                j$("#smallFont").attr("style", "text-decoration:underline;")
            }
            if (readCookie(cookieNameClasses) != null) {
                setButtonHereClass(readCookie(cookieNameClasses));
            }
            else {
                setButtonHereClass("smallFont");
                j$("#text_resize").attr("style", "text-decoration:none;")
                j$("#smallFont").attr("style", "text-decoration:underline;")
            }
        }
        function addClass(element, value) {
            if (element) {
                if (!element.className) {
                    element.className = value;
                }
                else {
                    newClassName = element.className;
                    newClassName += " ";
                    newClassName += value;
                    element.className = newClassName;
                }
            }
        }

        //Homepage Accordian - "header" discates the headers for the accordian, "icons" dictate the triangles
        //j$("#dnn_AgencyPane").accordion({ header: '.module h2', icons: { 'header': 'closed', 'headerSelected': 'open', autoHeight: false} });

        //Initializes the rotator, generates the nav buttons, and adds listeners to the page left/right buttons.
        j$('#img_panels > div').cycle({
            fx: 'scrollHorz',
            easing: 'easeOutExpo',
            timeout: 10000,
            next: '#img_right',
            prev: '#img_left',
            pager: '#img_nav',
            pagerAnchorBuilder: function (idx, slide) {
                return '<li></li>';
            }
        });

        //Enables clicking on the video panel to pause the rotator and clicking on the navigation to resume it.
        /*j$('#img_panels > div').click(function () {
        j$('#img_panels > div').cycle('pause');
        });*/
        //Pause function moved below for youtube api -JB
        j$('#img_nav > li').click(function () {
            j$('#img_panels > div').cycle('resume');
        });
        j$('#img_left').click(function () {
            j$('#img_panels > div').cycle('resume');
        });
        j$('#img_right').click(function () {
            j$('#img_panels > div').cycle('resume');
        });

        //Unhides image rotator nav buttons
        j$('#img_nav').show();

        //Sets page left/right buttons as visible, fades buttons up on approach.
        j$('.pager_btn').fadeTo(0.00);
        j$('.pager_btn').approach({ opacity: 1 }, 150);
		
		//Toggles the play video image for the flood insurance page on hover, and starts the video on click.
		j$('#floodVideoImage').hover(function (event) {
            j$(this).attr('src', 'http://www.auto-owners.com/Portals/0/images/Flood/ClickplayOver.jpg');
        }, function (event) {
            j$(this).attr('src', 'http://www.auto-owners.com/Portals/0/images/Flood/Clickplay.jpg');
        });
        j$('#floodVideoImage').click(function () {
            j$(this).parent().html('<iframe style="float: right; height:350px; width: 220px;" src="http://www.fema.gov/help/widgets/countdown-small.html" frameborder="0" scrolling="no" marginwidth="0"></iframe>');
            j$('#mymovie').live('click', function (event) {
                alert(j$(this).attr('id'));
            });
        });
		
		/* ROI Trax for agency locator clicks */
		var pageUrl = j$(location).attr('href');
		j$("a[href^='http://agency.auto-owners.com']").click(function (event) {
			if (pageUrl.indexOf("car-insurance") != -1 && pageUrl.indexOf("wisconsin") != -1) {
				event.preventDefault();
				_rts_set_conversion('0.00', 'Agency Locator - Wisconsin Car Insurance');
				window.setTimeout('location.href=\'' + j$(this).attr('href') + '\'', 500);
				return false;
			} else if (pageUrl.indexOf("car-insurance") != -1) {
				event.preventDefault();
				_rts_set_conversion('0.00', 'Agency Locator - General Car Insurance');
				window.setTimeout('location.href=\'' + j$(this).attr('href') + '\'', 500);
				return false;
			}
		});
    });
})(jQuery.noConflict());

function new_window(url, winwidth, winheight, winleft, wintop) {
    parameters = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,width="+winwidth+",height="+winheight+",left="+winleft+",top="+wintop;
    link = window.open(url,"Link",parameters);
}

//youtube playing items
function onytplayerStateChange(newState) {
   switch (newState) {
       case 1:
       case 3:
           // Video has begun playing/buffering
           jQuery('#img_panels > div').cycle('pause');
           break;
       case 2:
       case 0:
           // Video has been paused/ended
           jQuery('#img_panels > div').cycle('resume');
           break;
   }
}
function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("youtube_video");
	if (ytplayer.addEventListener) {
		ytplayer.addEventListener("onStateChange", "onytplayerStateChange", false);
	}
    else if (ytplayer.attachEvent) { //IE Fix
		ytplayer.attachEvent("onStateChange", "onytplayerStateChange");
	}
}

/*Fixes weird IE error*/
var setRemoveCallback = function() {
	__flash__removeCallback = function(instance, name) {
		if(instance) {
			instance[name] = null;
		}
	};
	window.setTimeout(setRemoveCallback, 10);
};
setRemoveCallback();

