// accessor for legacy swf applications like stateList
var XHTMLcontent = "";					
jQuery.fn.getContent = function() {
	return XHTMLcontent;
}

$(document).ready(function(){
	
	// set for logging to firebug console
	window.log = function(string) 
	{
		if (typeof console == 'object' && appJSGlobals.isJavascriptDebugMode == "ON") 
		{ 
			console.log(string);
		}	
	}
	
	// print handlers
	$("a.printIcon").click(function(){
		var myTitle = $(this).parent().parent().parent();
		var myList = $(this).parent().parent().parent().next();
		var myParagraph = $(this).parent().parent().parent().next().next("p");
		$(".jsList, .jsInstTitle").addClass("printOff");
		$(myTitle).removeClass("printOff");
		$(myList).removeClass("printOff");
		$("#jsInstructionsContent h3, #jsInstructionsContent ul, #jsInstructionsContent p").addClass("printOff");
		$(myParagraph).removeClass("printOff");
		window.print();
		return false;
	});	

	$("#printAll").click(function(){
		$(".printOff").removeClass("printOff");
		window.print();
		return false;
	});	
	
	// Remove height and width attributes if they are not passed in.
	// If height and width are null, ImageConverter.java stores them as '0',
	// which works fine for FireFox. But for internet explorer, the height and width
	// appear as '1' instead of '0' therefore we need to check for '1' as well.
	$('img').each(function(n){
	    if( this.src != "" )
	    {
			if( this.height == 0 || this.height == 1 )
			{
				$(this).removeAttr("height");
			}
	
			if( this.width == 0 || this.width == 1)
			{
				$(this).removeAttr("width");
			}
		}
	});
	
	$("#loginbutton").bind('click',function(event) {
		return sendOmnitureOnEserviceLogin(event, 'Manage Your Policies login button');
	});
		
	$("#claimsloginbutton").bind('click',function(event) {
		return sendOmnitureOnEserviceLogin(event, 'Manage Your Claim login button');
	});
			
	if ($("#searchItem").length <= 0) 
	{
		$("#homeLogin").attr("id", 'homeLoginMove');
	}
	else
	{
		$("#homeLogin").attr("id", 'homeLogin');
	}
	

	/* when button hit, disable all buttons to prevent double submit 
	$("button[type=sugggbmit], input[type=bugggtton]").bind('click', function(event) {
		$("button[type=sggubmit], input[type=bggutton]").disable();	

		});*/

	$("ul#zoomControl, div#mapContainer button").css("display","block");
	$("p.zoom").css("display","inline");
		
	$("#printerFriendlyLink").click(function(){
		window.print();
		return false;
	});
	
	$("form").attr("autocomplete", "off");
	
	$("a[target=_popup]").click(function(){
		window.open ($(this).attr("href"),"popup","status=0,toolbar=0,scrollbars=1,menubar=0,location=0,width=800,height=600"); 
		return false;
	});
	
	/* 
	 * For Center Modules, compares height of each module and sets parent
	 * height as equal to that of the largest plus 10. Since the individual
	 * modules have height:100%, this makes them all match the height of the 
	 * largest.
	 */
	if($("#centerModSet").is("div")){
		var centerModules = $("#centerModSet").children("div");
		var moduleHeights = [];
		for (i = 0; i < centerModules.length; i++) {
			moduleHeights.push($(centerModules[i]).height());
		}
		moduleHeights.sort(function(a,b){return a-b});  
		$("#centerModSet").height(moduleHeights[moduleHeights.length-1]+10);
	}
	
	var locationHref = location.href;
	var varIndex = locationHref.indexOf("?");
	if (varIndex != -1)
	{
		locationHref = locationHref.substring(0, varIndex);
	}
		
	$("#topNav ul li a").each(function(){
		var linkHref = this.href;
		varIndex = linkHref.indexOf("?");
		if (varIndex != -1)
		{
			linkHref = linkHref.substring(0, varIndex);
		}
		if (locationHref.indexOf(linkHref) >= 0){
			//link is a parent of this page (e.g. auto, home, claims)
			$(this).attr("id", "navLinkDisabled");
			if (linkHref == locationHref){
				//same page
				$(this).attr("href", "#");
				$(this).click(function() { 						
					return false;
				});
			}
		}							
	});
	
	$("#searchOp ul li a.homeLink").each(function(){
		var linkHref = this.href;
		varIndex = linkHref.indexOf("?");
		if (varIndex != -1)
		{
			linkHref = linkHref.substring(0, varIndex);
		}
		if (linkHref == locationHref){
				//for home page, only set the disabled link styling if 
				//we are actually on that page
				$(this).attr("id", "navLinkDisabled");
				$(this).attr("href", "#");
				$(this).click(function() { 						
					return false;
				});
		}
	});
		
		
		$("#locAgentZip").bind('keypress',function(event) {
		return submitOnEnter(event,'goButton');
	});
	
	$("#searchForString").bind('keypress',function(event) {
		return submitOnEnter(event,'goButton');
	});

	$("#searchQuery").bind('focusin',function(event) {
		if ($(this).hasClass("searchBlur"))
		{
			$(this).val('');
			$(this).removeClass("searchBlur");
			$(this).addClass("searchFocus");	
		}
	});
	
	$("#searchQuery").bind('blur',function(event) {
		if ($(this).hasClass("searchFocus"))
		{
			if ($(this).val() == '')
			{
				$(this).removeClass("searchFocus");
				$(this).addClass("searchBlur");
				$(this).val('search');
			}
		}
	});

	$("#searchQuery").bind('keypress',function(event) {
		return submitOnEnter(event,'searchButton');
	});

	$("#searchButton").bind('click',function(event) {
		if ($("#searchQuery").hasClass("searchBlur"))
		{
			$("#searchQuery").val('');
		}	
	});
	
	$("#quoteZipCode").bind('keypress',function(event) {
		return submitOnEnter(event,'getQuoteButton');
	});

	$("#locClaimsOfficeZip").bind('keypress',function(event) {
		return submitOnEnter(event,'claimOfficeZipGoButton');
	});
	
	$("a.sessionClear").click(function() {
		$.cookie("JSESSIONID", null, { path: '/', domain: '.libertymutual.com'});
		return true;
	});	
	
	$("a.browseToButton").append("<span class='browse'></span>");
	
	if($.browser.msie && (parseInt($.browser.version) == 6) || (parseInt($.browser.version) == 7)) {
		$("#contentArea a.browseTo").append("<span class='browseLink'></span>").removeClass("browseTo");
	} 
});

$.fn.enable = function() {
	return this.each(function() {
		if (typeof this.disabled != "undefined")
		            this.disabled = false;
	});
} 


$.fn.disable = function() {
	return this.each(function() {
		if (typeof this.disabled != "undefined") {		
		            this.disabled = true;
		           }
	});
} 

// List all onclick handlers of all anchor elements:
//$('a').listHandlers('onclick', console.info);

// List all handlers for all events of all elements:
//$('*').listHandlers('*', console.info);

// Write a custom output function:
//$('#whatever').listHandlers('click',function(element,data){
//    $('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
//});
// $('form[id*=getQuoteForm]').listHandlers('submit', console.info);
$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};


function sendOmnitureOnEserviceLogin(event, desc)
{
	z = s_gi(appJSGlobals.omnitureAccount);
	z.linkTrackVars = 'events';
	z.linkTrackEvents = 'event7';
	z.events = 'event7';
	z.tl('button', 'o', desc);
}

function stripLeadingTrailingSpace(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

function submitOnEnter(e,commandButtonId,commandButton)
{
	 var keycode;
	 if (window.event) 
	 	keycode = window.event.keyCode;
	 else if (e) 
	 	keycode = e.which;
	 else 
	 	return true;
	
	 if (keycode == 13)
	 {
	 	if (commandButton != null)
	 	{
	 		commandButton.click();
	 		return false;
	 	}
	 	else if (commandButtonId)
	 	{
	 	var cb = "#"+commandButtonId;
	    $(cb).click();
	    return false;
	 	}
	 }
	 else
	 {
	    return true;
	 }
}

/*
 * This transforms the dom to make it flash-readable friendly.
 *
 * An alternate would have the flash read using a service url or xml files
 */
function transformForFlash(element)
{	
	if (element.length == 0) return null;
	/*
	// internet explorer's innerHTML is craptastic so we use some hackery to fix it
	// if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1){
	// BUG: self-closing <a> tags don't work , e.g "<a name='inline' />"
	*/
	
	var reTag = /(<\/?\w+)([^>]*>)/g;
	var reAttr = /(\w+=)((['"])[\s\S]*\3|[^\s>]+)/g;
	str = element.innerHTML;
	
	function fixAttr($0, $1, $2, $3) {
	    if ($3) return $1.toLowerCase() + $2;
	    else return $1.toLowerCase() + '"' + $2 + '"'
	}       
	
	function fixTag($0, $1, $2) {
	    return $1.toLowerCase() + $2.replace(reAttr, fixAttr);
	}
	
	/* clean up tags (make html tags and attributes lowercase) */
	str = str.replace(reTag, fixTag);
	
	/* correct missing quotes on target tags (omniture bug) */
	str = fixTargetTag(str, "_blank");
	str = fixTargetTag(str, "_self");	
	str = fixTargetTag(str, "_popup");		
		
	/* make sure self-closing tags are closed */
	var reSelfClosing = new RegExp("\<(area|base|basefont|br|hr|img|input)(.*?)>", "g");
	
	str = str.replace(reSelfClosing, "<$1$2/>");
	/*
	// IE's treatment of UL's and DL's is mind boggling.
	// A big brain came up with this series of search/replaces that fixes them.  You go Dan.  
	*/
	str = str.replace(/<\/li>|<\/dt>/g, "");                            // get rid of all closing li and dt tags (for IE)
	str = str.replace(/\s*<li([^>]*)>/g, "<\/li><li$1>");       // put a closing li in front of all opening li
	str = str.replace(/<\/ul>/g, "<\/li><\/ul>");                   // put a closing li in front of closing ul
	str = str.replace(/<ul([^>]*)>\s*<\/li>/g, "<ul$1>");       // remove closing li's that appear directly after opening ul
	str = str.replace(/\s*<dd([^>]*)>/g, "<\/dt><dd$1>");   // put a closing dt in front of all opening dd's
	/* end dan hackery */
	return str;
}

/*
 * omniture for some reason is removing the quotes are target attribute values
 * so as a temporary hack we are adding them back.
 */
function fixTargetTag(str, attrValue)
{
	var oldStr = "target="+attrValue;
	var newStr = "target=\"" + attrValue + "\"";
	return replaceAll(str, oldStr, newStr);
}

function replaceAll(Source, stringToFind, stringToReplace)
{
	var temp = Source;
    var index = temp.indexOf(stringToFind);
	while (index != -1)
	{
		temp = temp.replace(stringToFind,stringToReplace);
		index = temp.indexOf(stringToFind);
	}
	return temp;
}

/*
 * strips the page name off the breadcrumb
 */
function stripPageName(uri)
{
	var p = uri;
	if (uri.substring(uri.length - 1, uri.length) == '/')
	{
		p = uri.substring(0, uri.length - 1);
	}
	var loc = p.lastIndexOf("/");
	if (loc >= 0 && loc + 1 <= p.length)
	{
		p = p.substring(loc + 1);
	}
	return p;
}

/*
 * strips the domain off the uri
 */
function stripDomainName(uri)
{
	var p = uri;
	
	var loc = p.indexOf("/MediaBin");
	if (loc >= 0 && loc + 1 <= p.length)
	{
		p = p.substring(0,loc);
	}
	return p;
}

/*
 * strips the file extension off the uri
 */
function stripFileExtensionFromURL(uri)
{
	var p = uri;
	if (uri.substring(uri.length - 1, uri.length) == '.')
	{
		p = uri.substring(0, uri.length - 1);
	}
	var loc = p.lastIndexOf(".");
	if (loc >= 0 && loc + 1 <= p.length)
	{
		p = p.substring(0,loc);
	}
	return p;
}

/*
 * strips the file off the uri
 */
function stripFileFromURL(uri)
{
	var p = uri;
	if (uri.substring(uri.length - 1, uri.length) == '/')
	{
		p = uri.substring(0, uri.length - 1);
	}
	var loc = p.lastIndexOf("/");
	if (loc >= 0 && loc + 1 <= p.length)
	{
		p = p.substring(0,loc);
	}
	return p;
}


/*
 * prepare for any flash components identified by the
 * component id/ div id prefix
 */
function prepareForFlash(divIdPrefix, instantiationMethod, qualifyingClassName)
{
	var customClass = divIdPrefix;
	
	if (qualifyingClassName != null)
	{
		var selector = 'body[class*=' + qualifyingClassName +']' + ' div[id*=' + divIdPrefix + ']';
	}
	else
	{
		var selector = 'div[id*=' + divIdPrefix + ']';	
	}	
	$(selector).each(
		function(intIndex) {
			$(this).addClass(customClass);
			flashId = $(this).attr("id");
			flashResource = $(this).find(".flashResource").text();		
			flashHeight = $(this).find(".flashHeight").text();
			flashWidth = $(this).find(".flashWidth").text();	
				
			if (swfobject.hasFlashPlayerVersion(appJSGlobals.requiredFlashPlayerVersion)) 
			{	
				var instMethod = instantiationMethod + "(flashId, flashResource, flashHeight, flashWidth);";
				eval(instMethod);
			}
			else  
			{
				$("div.upgradeYourFlash").css("display", "block");				
			}					
	});	
}


/*
 * Generic method for instantiating flash components
 */
function instantiateFlash(flashId, flashResource, flashHeight, flashWidth)
{			
       var variables = 
       {
           "lm_env": appJSGlobals.mediaCenterEnvironment
       };
       var parameters = 
       {       
			 "allowScriptAccess": "always"
			,"quality": "high"
			,"wmode": "transparent"                                     
       };
       var attributes = {};
               
       swfobject.embedSWF(flashResource, flashId, flashWidth, flashHeight, appJSGlobals.requiredFlashPlayerVersion, "", variables, parameters, attributes);
}	
 
/*
 * Generic method for instantiating flash components
 */
function instantiateFlashSenior(flashId, flashResource, flashHeight, flashWidth)
{			
		myAffRes = $(".affinityRestriction").text();
		mybase = $(".flashSrcBase").text();
		mymovie = $(".flashSrcNoExtension").text();								
		myDomain = stripDomainName(flashResource)
		mybase=stripFileFromURL(flashResource)+'/';
		mymovie=stripFileExtensionFromURL(flashResource);
		
		var variables = 
		{
			"aff_res": myAffRes,
	        "lm_env": appJSGlobals.mediaCenterEnvironment,
	        "server_path": appJSGlobals.gamesDataServices + "/",	        			
	        "locale": "en_US"			
		};		
		    
		var parameters = 
		{
			"allowScriptAccess": "always",
			"quality": "high",
			"wmode": "transparent",
			"play": "true",
			"loop": "true",	
			"align": "top",							
			"quality": "high",				
			"devicefont": "false",	
			"id": "SeniorDriversGameFlash",														
			"name": "SeniorDriversGameFlash",																	
			"allowScriptAccess": "always",		
			"allowFullScreen": "true",					
			"align": "t",		
			"scale": "noscale",							        																
			"menu": "true",													
			"type": "application/x-shockwave-flash",													
			"codebase": "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0",													
			"pluginspage": "http://www.adobe.com/go/getflashplayer",
			"base": mybase,
			"movie": mymovie								
		};     
		
		var attributes = {};

		swfobject.embedSWF(flashResource, flashId, flashWidth, flashHeight, appJSGlobals.requiredFlashPlayerVersion, "", variables, parameters, attributes);			
}	

/* 
 * Checks if cookies are enabled in the browser.
 */
function areCookiesEnabled() 
{
    var r = false;
    if(navigator.cookieEnabled)
    {
    	r = true;
    }
    return r;
}

// Display the cookies message on page load if cookies are disabled.
$(document).ready(function() {
	if(!areCookiesEnabled())
	{
		$("#mainCookiesMessage").css("display", "block");
	}
});

/* $("#something").sayhello(); */
/* this function might reference myHelloer object */
/*
 * add a new wrapper method
 *
 * $("#slideshowContainerRotating").createPromoSlideshow();
 */
jQuery.extend(jQuery.fn, {
	createPromoSlideshow: function(options) {

		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't ctreate slideshow, returning nothing" );
			return;
		}
		
		// check if a promoSlideshow for this form was already created
		/* this is actually saving the first element of the selector, in the case of validator, the form */
		var promoSlideshow = jQuery.data(this[0], 'promoSlideshow');
		if (promoSlideshow) {
			return promoSlideshow;
		}
		
		promoSlideshow = new jQuery.promoSlideshow(options, this[0]);
		jQuery.data(this[0], 'promoSlideshow', promoSlideshow);
		
		return promoSlideshow;			
	}
});

/*
 * define a new object
 */
$.promoSlideshow = function(options, container) {
	this.settings = jQuery.extend({}, jQuery.promoSlideshow.defaults, options);
	this.create(container, this);
};

/*
 * extend the object attributes
 */
jQuery.extend(jQuery.promoSlideshow, {

	defaults: {
        fx: 'fade',
        speed: 200,     
        timeout: 5000,
        height: 266,
		pager: '#promonav',
		manualTrump: true,
		fit: true,
		requeueOnImageNotLoaded: false,   
    	pagerAnchorBuilder: function(idx, slide) { 
        	return '<a href="#">&nbsp;</a>'; 
    	},	 	
    	cssBefore:{
    		height: 260
    		},
	    before: function(e) {						    
			if ($(this).html().indexOf("PromoGreen") >= 0)
			{
				$('#promonav a').each(function() {
					$(this).addClass('darkPromoButton');
				});							
			}
			else
			{
				$('#promonav a').each(function() {
					$(this).removeClass('darkPromoButton');
				});				
			}		    
	    },
	    after:  function onAfter(curr, next, opts, fwd){
	        $(this).css("height", "260px"); 
		}
	},

	setDefaults: function(settings) {
		jQuery.extend(jQuery.promoSlideshow.defaults, settings);
	},
	
	prototype: {		
		create: function(container, myThis) {
			$(container).after('<div id="promonav">').cycle(jQuery.promoSlideshow.defaults);	
		}
	}	
});			
