$(document).ready(function(){

	// GLOBAL LINK TITLE TOOLIP WINDOW CODE	
	$('a[title],img[title]').tooltip({ 
		track: false,
		delay: 0, 
		fixPNG: true,
		showURL: false, 
		opacity: 1, 
		showBody: " - ",
		top:10, 
		left:10
	});
	
	// 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, #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)
				{
					$(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('keypress',function(event) {
				return submitOnEnter(event,'searchButton');
				});

             $("form[id*=officesGetQuoteForm]").each(function(n) {
				var buttonGuy = $(this).find("button");
				$(this).find("input[type=text]").bind('keypress',function(event) {
					return submitOnEnter(event,null,buttonGuy[0]);
				});
			});	

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

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

	
});

$.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;
		           }
	});
} 

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;
}

/*
 * prepare for any flash components identified by the
 * component id/ div id prefix
 */
function prepareForFlash(divIdPrefix)
{
	var customClass = divIdPrefix;
	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)) 
			{													
				instantiateFlash(flashId, flashResource, flashHeight, flashWidth);
			}
			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);
}		