var timeOuts = [];
var dipHome = 0;
var myHeight = 0;
var totalHeight = 0;
var activeSecondary = '';

String.prototype.parseURL = function () {
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function (url) {
        return url.link(url);
    });
};

String.prototype.parseDate = function () {
    var v = this.split(' '); var dte = new Date(Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3] + " UTC"));
    return (dte.getMonth() + 1) + '/' + dte.getDate() + '/' + dte.getFullYear();
}

var showAccordionByID = function(thisAccordionID) {
	jQuery('#accordionTab'+thisAccordionID).addClass('active');
	jQuery('#accordionContent'+thisAccordionID).slideDown(200);
}

var hideAccordionByID = function(thisAccordionID) {
	jQuery('#accordionTab'+thisAccordionID).removeClass('active');
	jQuery('#accordionContent'+thisAccordionID).slideUp(200);
}

var accordionsOpen = function() {
	result = 0;
	jQuery("#inlineAccordion > div.inlineAccordionTab").each(function (i) {
		temp = jQuery(this).css("background-image");
		if (temp.indexOf('up') != -1) {
			result++;
		}
	});
	return result;
}


var tw = function (data) {
	//jQuery(".sideBarTwitterFeed").append('<img src="http://c3212742.r42.cf0.rackcdn.com/twitterTop.png" /><div id="tweets" />');
	jQuery(".sideBarTwitterFeed").append('<img src="http://www.marathonnorge.no/en/images/obfT.jpg" /><div id="tweets" />');
	jQuery.each(data, function (i, item) {
		jQuery("<div/>").html('<div class="tweet"><p>' + String(item.text).parseURL() + '</br>' + String(item.created_at).parseDate() + ' | <a href="http://twitter.com/intent/tweet?in_reply_to='+item.id_str+'">reply</a> | <a href="http://twitter.com/intent/retweet?tweet_id='+item.id_str+'">retweet</a> | <a href="http://twitter.com/intent/favorite?tweet_id='+item.id_str+'">favorite</p></div>').appendTo("#tweets");
	});
}

var emailPage = function() {
	temploc='http://www.marathonoil.com/About_Us/Contacts/Email_Page/?myURL=';
	temploc = temploc + window.location.href.replace(/\&/, '%26').replace(/\?/, '%3F');
	window.location.href = temploc;
}

var printPage = function() {
	window.print();
}

/* YouTube Data Call Back */
var yt = function (data) {
	var myLength = data.feed.entry.length;
	jQuery(".embedYouTubeVideo").each( function () {
		var $this = jQuery(this);
		var keyword = $this.attr('rel');
		for (i=0;i<myLength;i++) {
			var item = data.feed.entry[i];
			var myKeywords = item.media$group.media$keywords.$t;
			if(myKeywords.indexOf(keyword) > -1) {
				MYID = keyword+'Vid'+String(i);
				if ($this.hasClass('multi')) {
					$this.append('<div class="youtubeVideoMulti"><div id="'+MYID+'"></div><div class="youTubeVideoDescription"><h2>'+item.title.$t+'</h2><p>'+item.media$group.media$description.$t+'</p><div class="clear"></div></div>');
					swfobject.embedSWF(item.content.src+'&rel=0', MYID, "120", "90", "9.0.0","expressInstall.swf", {}, {wmode:"transparent"}, {});
				} else {
					if ($this.hasClass('homeVideo')) {
						$this.append('<div class="youtubeVideoHome" id="'+MYID+'"></div>');
						i=myLength;
						swfobject.embedSWF(item.content.src+'&rel=0', MYID, "302", "224", "9.0.0","expressInstall.swf", {}, {wmode:"transparent"}, {});
					} else {
						$this.append('<div class="youtubeVideo" id="'+MYID+'"></div><div class="youTubeVideoDescription"><h2>'+item.title.$t+'</h2><p>'+item.media$group.media$description.$t+'</p><div class="clear"></div>');
						i=myLength;
						swfobject.embedSWF(item.content.src+'&rel=0', MYID, "360", "270", "9.0.0","expressInstall.swf", {}, {wmode:"transparent"}, {});
					}
				}
				
			}
			
		}
	});
	/*var $vidPage = jQuery("#videoPage");
	if ($vidPage.length > 0) {
		for(i=0;i<myLength;i++) {
			var item = data.feed.entry[i];
			var myKeywords = item.media$group.media$keywords.$t;
			
		}
	}*/
}
	
jQuery(function () { 
	jQuery.noConflict();
	setTimeout("jQuery('#inline').css('min-height', jQuery('#leftNav').height()+40)", 100);
	jQuery("#stockTicker").load( '/content/includes/AJAXtwister.asp?type=2011homequote');
	
	initializePage = function (id, primaryid) {
		
		
		/* Inline Accordion Code */
        if (jQuery("#inlineAccordion").length > 0) {
            jQuery("#inlineAccordion > div.inlineAccordionContent").each(function (i) {
                // Find the ideal height to display the tallest single accordion
                if (jQuery(this).height() > myHeight) myHeight = jQuery(this).height();
                // Calculate the ideal height to display all accordions
                totalHeight += jQuery(this).height() + 44;
            });

            myHeight += 208;

            jQuery("#inlineAccordion > div.inlineAccordionTab").each(function (i) {
                // Add in the height of each tab
                myHeight += jQuery(this).height();
                totalHeight += jQuery(this).height();
            });

            jQuery(".inlineAccordionTab").bind("click", function (e) {
                $this = jQuery(this);
                if ($this.hasClass('active') == false) {
                    setTimeout('showAccordionByID(' + $this.attr('id').substring(12) + ')', 250)
                }
                if (accordionsOpen() > 1) {
                    hideAccordionByID($this.attr('id').substring(12));
                } else {
                    jQuery(".inlineAccordionContent").slideUp(200);
                    jQuery(".inlineAccordionTab").removeClass('active');
                }
                updateCollapser();
            });

            jQuery("#accSpacer").height(totalHeight);

            jQuery("#expand").bind("click", function (e) {
                if (jQuery("#inlineAccordion > div.inlineAccordionTab").length / 2 >= accordionsOpen()) {
                    jQuery("#inlineAccordion > div.inlineAccordionContent").each(function (i) { jQuery(this).slideDown(200); });
                    jQuery("#inlineAccordion > div.inlineAccordionTab").each(function (i) { jQuery(this).addClass('active') });
                } else {
                    jQuery("#inlineAccordion > div.inlineAccordionContent").each(function (i) { jQuery(this).slideUp(200); });
                    jQuery("#inlineAccordion > div.inlineAccordionTab").each(function (i) { jQuery(this).removeClass('active') });
                }
                updateCollapser();
            });
        }	
	
		/* World Map Code */
		if (jQuery("#countryList").length>0) {
			/* Drop Down */
			jQuery("#countryList").bind('change', function () { 
				if(jQuery(this).find("option:selected").val() != '') {
					window.location.href = jQuery(this).find("option:selected").val();
				}
			});
		}
		if (id==1908) {
			/* Map Hotspots */
			jQuery(".wmHotSpot").each(function () {
				var $this = jQuery(this);
				$this.find('img').css('height', $this.height()).css('width', $this.width());
			}).click( function () {
				jQuery('.wmHotSpot').show();
				var $this = jQuery(this).hide();
				jQuery('.popup').hide();
				jQuery('#pu'+$this.attr('id')).fadeIn(250);
			});
			
			/* Popup Close Buttons */
			jQuery(".popupCloser").click( function () {
				var $this = jQuery(this);
				jQuery("#"+$this.find('img').attr('rel')).fadeIn(125);
				$this.parents('.popup').hide();
			});
		}
		
		/* Home Page Specific Code */
		if (id==2577) {
			jQuery("#tabContentPR").load('http://www.marathonnorge.no/en/content/includes/AJAXtwister.asp?type=norway2011EnNewsReleasesHome', function() {
				$this = jQuery("#tabContentPR");
				$ul = $this.find('ul');
				var toBig = true;
				do {
				   $ul.find('li:last').remove();
				   if($ul.height() < 190) toBig = false;
				} while (toBig);
			});
			
		}
		
		/* Home Page Specific Code for Norwegian */
		if (id==2675) {
			jQuery("#tabContentPR").load('http://www.marathonnorge.no/en/content/includes/AJAXtwister.asp?type=2011NewsReleasesHomeNE', function() {
				$this = jQuery("#tabContentPR");
				$ul = $this.find('ul');
				var toBig = true;
				do {
				   $ul.find('li:last').remove();
				   if($ul.height() < 190) toBig = false;
				} while (toBig);
			});
			
		}
		
		
		
		/* News Page Specific Code */
		if (id==1910) {
			jQuery("#tabContent3828").load('http://www.marathonnorge.no/en/content/includes/AJAXtwister.asp?type=2011NewsReleasesHome', function() {
				$this = jQuery("#tabContent3828");
				$ul = $this.find('ul');
				var toBig = true;
				do {
				   $ul.find('li:last').remove();
				   if($ul.height() < 345) toBig = false;
				} while (toBig);
			});
		}
		
		/* Press Releases Specific Code */
		if (id==2039) {
			jQuery(function() { jQuery('#pressReleases').load('http://www.marathonnorge.no/en/content/includes/AJAXtwister.asp?type=2011NewsReleases');});
		}
		
		/* Investor Center Home Code */
		if (id==1909 || 1==1) {
			jQuery("#newsEventsSidebar").load('http://www.marathonnorge.no/en/content/includes/AJAXtwister.asp?type=2011IRSidebarNews', function() {
				$this = jQuery("#newsEventsSidebar");
				$ul = $this.find('ul');
				var toBig = true;
				do {
				   $ul.find('li:last').remove();
				   if($ul.height() < 300) toBig = false;
				} while (toBig);
			});
		}
		
		/* Spotlight Series Specific Code */
		if (id == 2045) {
                jQuery("#featureArea").load( 'http://www.marathonnorge.no/en//content/includes/AJAXtwister.asp?type=spotlightImageRotator' );
        }
		
		/* Shade Button Code */
		/* Shade Button Configurator */
		jQuery(".shadebutton").each( function () {
			var $this = jQuery(this), myTarget = $this.parent().attr('href'), myLabel = $this.parent().attr('title'), myDescription = $this.attr('alt'), myWidth = $this.width(), myHeight = $this.height();
			$this.parent().wrap('<div class="shadebuttonwrapper" />').before('<div class="shadebuttonlabel">'+myLabel+'</div>', '<div class="shadeclipper"><div class="shadebuttontab sprite"><div class="shadebuttondesc">'+myDescription+'</div></div></div>', '<a href="'+myTarget+'" class="shadebuttontrigger" title=""><img src="http://marathon.brandextract.com/2011staged/images/spacer.gif" alt="" /></a>');
			$this.parent().siblings('.shadeclipper, .shadebuttontrigger').css('width', String(myWidth+'px')).css('height', String(myHeight+'px')).find('.shadebuttontab').css('width', String(myWidth+'px'));
			$this.parent().siblings('.shadebuttontrigger').find('img').css('width', String(myWidth+'px')).css('height', String(myHeight+'px'));
		});
		
		/* Shadebutton Watcher */
		jQuery('.shadebuttontrigger').hover( function () {
			var $this = jQuery(this);
			$this.siblings('.shadeclipper').find('.shadebuttontab').animate({marginTop: 0}, 125, "swing");
		}, function () {
			var $this = jQuery(this);
			$this.siblings('.shadeclipper').find('.shadebuttontab').animate({marginTop: -99}, 500, "swing");
		});
		
		/* WavyImage Code */
		jQuery(".wavyImage").each( function () {
			var $this = jQuery(this), myDescription = $this.attr('alt'), myWidth = $this.width(), myHeight = $this.height();
			$this.wrap('<div class="wavyImageWrapper" />').before('<div class="wavyImageWaves sprite" />');
			$this.siblings('.wavyImageWaves').css('width', String(myWidth+'px')).css('height', String(myHeight+'px'));
		});
		
		/* Search Box Watcher */
		jQuery("#q").focus(
			function () { 
				if(this.value == 'Search this site...') this.value = '';
			}
		).blur(
			function () { 
				if(this.value == '') this.value = 'Search this site...';
			}
		);
		
		/* Overlapping Tab Code */
		/* Code needs to be tweaked if we are going to have multiple tab groups on a page */
		jQuery(".oTab.target").click( function () {
			var $this = jQuery(this);
			var $that = jQuery("#"+$this.attr('rel'));
			$this.closest(".oTabGroup").find(".oTabContent").removeClass("active");
			$this.closest(".oTabGroup").find(".oTab").removeClass("active").removeClass("nextActive");
			$this.addClass("active").prev().addClass("nextActive").next().next().addClass("active");
			$that.addClass("active");
		});
		
		jQuery(".lovTable tr:odd").addClass("blue");
	
	}
	
	activateRollovers = function () {
		// This nonsense is here because some browsers try and run this bit before elements have their offset top and left defined
		if (
			jQuery("#primaryNav>div>ul>li:eq(0)").offset().left != jQuery("#primaryNav>div>ul>li:eq(1)").offset().left
		) {
			$activePrimary = jQuery("#primaryNav li.active");
			$activePrimary.length > 0 ? dipHome = $activePrimary.offset().left : dipHome = 0;
			jQuery("#ulNav1908").pacNav({ "type": "primary", "dd": "#globalDD" });
			jQuery("#ulNav1909").pacNav({ "type": "primary", "dd": "#investorDD" });
			jQuery("#ulNav1910").pacNav({ "type": "primary", "dd": "#newsDD" });
			jQuery("#ulNav1911").pacNav({ "type": "primary", "dd": "#socialDD" });
			jQuery("#ulNav1912").pacNav({ "type": "primary", "dd": "#careersDD" });
			jQuery("#ulNav1913").pacNav({ "type": "primary", "dd": "#aboutDD" });
			jQuery(".dropDownContainer").pacNav( { type: 'dropdown' } );
		} else {
			setTimeout("activateRollovers()", 100);
		}
	};
	
	secondaryOff = function () {
		jQuery("#primaryDip").stop().animate({ "width": dipHome }, 200, "swing");
		jQuery(".dropDownContainer").stop().fadeOut("Fast");
		//jQuery("#"+activeSecondary).fadeOut("fast");
		
	}
	
	secondaryOn = function (left, dd) {
		jQuery("#primaryDip").stop().animate({ "width": left }, 200, "swing"); 
		activeSecondary = dd;
		jQuery(dd).fadeIn("fast");
	}
	
	stopTimeOut = function () {
		for(key in timeOuts ){
    		clearTimeout(timeOuts[key]);
  		}
	}
	
	jQuery.fn.pacNav = function (params) { 
		this.each(function () {		
			var $this = jQuery(this);
			var dipLeft = $this.offset().left+140;
			var ddLeft = $this.offset().left-40;
			var ddWidth = jQuery(params.dd).width();
			var maxLeft = jQuery('.pageWidth:eq(0)').width() + jQuery('.pageWidth:eq(0)').offset().left - ddWidth;
			
			if (ddLeft > maxLeft) ddLeft = maxLeft;
			
			if(jQuery($this).hasClass("active")) {
				jQuery("#primaryDip").stop().css( { "width": dipLeft }).show();
				dipHome = dipLeft;
			}
//			alert(jQuery("#primaryIndicator").offset().top);
			jQuery(params.dd).css( {'top': jQuery("#primaryIndicator").offset().top+1, 'left': ddLeft });
			
			/*if (ddTriggerArray.indexOf(jQuery(this).attr("id")) != -1) {
				jQuery(this).children().css( {'cursor': 'default' });
			}*/
			
			
			jQuery(this).bind("mouseover", function () { 
				var $this = jQuery(this);
				switch(params.type) {
					/*case 'primary':
						jQuery(this).attr("src",params.on); 
  						break;*/
					case 'dropdown':
						stopTimeOut();
						break;
					default:
  						stopTimeOut();
						left = $this.offset().left+140;
						timeOuts["mouseIn"] = setTimeout("secondaryOn("+left+", '"+params.dd+"')", 125);
						if (activeSecondary != params.dd) {
							jQuery(activeSecondary).fadeOut("fast");
						}
						
					
				}
			 });
			jQuery(this).bind("mouseout", function () { 
				switch(params.type) {
					/*case 'primary':
						jQuery(this).attr("src",params.off); 
						break;*/
					default:
						stopTimeOut();
						timeOuts["mouseOut"] = setTimeout("secondaryOff()",100);
				}
			});
		});
	};
	
	activateRollovers();
	
	var fitList = function(id, height) {
	$this = jQuery(id);
	$ul = $this.find('ul');
	$ul.height() < height ? toBig = false : toBig = true;
	if (toBig) {
		do {
			$ul.find('li:last').remove();
			if ($ul.height() < height) toBig = false;
		} while (toBig);
	}
}

var updateCollapser = function() {
	if (jQuery("#inlineAccordion > div.inlineAccordionTab").length/2 >= accordionsOpen()) {
		jQuery("#expand").attr('src', '/images/spacer.gif');
	} else {
		jQuery("#expand").attr('src', '/images/spacer.gif');
	}
	if (accordionsOpen() == 1 || accordionsOpen() == 0) {
		jQuery("#accSpacer").height(myHeight);
	} else {
		jQuery("#accSpacer").height(totalHeight);
	}
}

	
});


/*


	
	
	
	
	activateRollovers = function () {
		// This nonsense is here because sometimes browsers try and run this bit before elements have their offset top and left defined
		if (jQuery("#secondaryNav>ul>li:eq(0)").offset().left != jQuery("#secondaryNav>ul>li:eq(1)").offset().left) {
			jQuery("#primaryLab").pacNav({ off: '/images/lab_instruments.png', on: '/images/lab_instruments_over.png', type: 'primary' });
			jQuery("#primaryProcess").pacNav({ off: '/images/process_analytics.png', on: '/images/process_analytics_over.png', type: 'primary' });
			jQuery("#primaryParts").pacNav({ off: '/images/parts_store.png', on: '/images/parts_store_over.png', type: 'primary' });
			jQuery("#primarySupport").pacNav({ off: '/images/customer_support.png', on: '/images/customer_support_over.png', type: 'primary' });
			jQuery("#primaryNews").pacNav({ off: '/images/news_and_events.png', on: '/images/news_and_events_over.png', type: 'primary' });
			jQuery("#primaryAbout").pacNav({ off: '/images/about_pac.png', on: '/images/about_pac_over.png', type: 'primary' });
			jQuery("#secondaryNav>ul>li").pacNav({type: 'secondary' });
			jQuery(".dropDownContainer").pacNav({type: 'dropdown' });
			jQuery("#zoomableImage").each( function () {
				myLeft = jQuery(this).offset().left + (jQuery(this).width());
				myTop = jQuery(this).offset().top + (jQuery(this).height());
				jQuery("#lightboxArrow").offset({ top: myTop, left: myLeft });
			});
		} else {
			setTimeout("activateRollovers()", 100);
		}
	};
	
	activateRollovers();
	mytabs = jQuery("#tabbedContent > div.tabs").tabs("#tabbedContent > div.panes > div");
	jQuery("#footerSlideshow > div.tabs").tabs("#footerSlideshow > div.panes > div", { rotate: true}).slideshow({autoplay:true, autopause:true });
	jQuery(".dropDownParent").tabs(".dropDownChild > div", {initialIndex: 1000, event:'mouseover', onBeforeClick:function () { stopTimeOut() }});
	jQuery(".timeOutKiller").bind("mouseover", function () {
		stopTimeOut();
	});
	
	*/
