/* Function to addEventListener to onload
 * @param func - a function which should be executed once the page has loaded
 * http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 * it will work even if something has previously been assigned to window.onload
 * without using addLoadEvent itself. 
 */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

/*
 * Function to clear a text field
 * @param thefield
 *     the field to clear
 */
function cleartext(thefield) {
	if (thefield.defaultValue == thefield.value) {
		thefield.value = "";
	}
}

function GetAnchors() {
  if (document.getElementById) {
    var elements = new Array('a', 'area');
    for (var j=0; j < elements.length; j++) {
      var x = document.getElementsByTagName(elements[j]);
      for (var i=0;i<x.length;i++) {
        if (x[i].className.indexOf('newWindow') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "New Window");
        } else if (x[i].className.indexOf('popup') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Pop-up Window");
        } else if (x[i].className.indexOf('download') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Download");
        } else if (x[i].className.indexOf('downReportRR') != -1) {
          x[i].setAttribute("title", "Download Report");
        } else if (x[i].className.indexOf('html') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Download");
        } else if (x[i].className.indexOf('podcast') != -1) {
          x[i].setAttribute("title", "Podcast");
        } else if (x[i].className.indexOf('rss') != -1) {
          x[i].setAttribute("title", "RSS Feed");
        } else if (x[i].className.indexOf('external') != -1) {
          x[i].setAttribute("title", "Link to External Site");
        } else if (x[i].className.indexOf('reqPrintRR') != -1) {
          x[i].setAttribute("title", "Request Printed Copy");
        } else if (x[i].className.indexOf('reqPrint') != -1) {
          x[i].setAttribute("title", "Request Printed Copy");
        } else if (x[i].className.indexOf('wmv') != -1) {
					//for Ivestor section only
          x[i].setAttribute("title", "Listen to the webcast in Windows Media Player");
        } else if (x[i].className.indexOf('realAudio') != -1) {
					//for Ivestor section only
          x[i].setAttribute("title", "Listen to the webcast in Real Audio");
        } else if (isAssetDoc(x[i])) { // make sure all file extensions you wish to set custom title for are in isAssetDoc() below
          var fileExt = getFileExt(x[i]);
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].className=fileExt
         switch(fileExt) {
          case "doc":
            x[i].setAttribute("title", "Word document");
            break 
          case "ppt":
            x[i].setAttribute("title", "PowerPoint File");
            break            
           case "xls":
            x[i].setAttribute("title", "Excel File");
            break 
           default:
            x[i].setAttribute("title", fileExt.toUpperCase()+" file");
          }
        }
      }
    }
  }
}

function openNewWindow(e) {
    if (e == undefined || e.keyCode != 9) {
        if (isAssetDoc(this)) {
            var url = this.href;
            var parentHost = window.location.protocol + "//" + window.location.host;
            if (url.substring(0, parentHost.length) == parentHost) {
                url = url.substr(parentHost.length);
            } else if (url.substring(0, 23) == "http://www.chevron.com/") {
                url = url.substr(22);
            }
        }
        var features = '';
        var start;
        var end;
        var width;
        var height;
        var thisurl = this.href ? this.href : "";
        width = parseInt(getValueFromClass(this, 'w')) > 0 ? getValueFromClass(this, 'w') : '';
        height = parseInt(getValueFromClass(this, 'h')) > 0 ? getValueFromClass(this, 'h') : '';
        if (height.length > 0 || width.length > 0) {
            features += height.length > 0 ? 'height=' + height + ',' : '';
            features += width.length > 0 ? 'width=' + width + ',' : '';
        }
        features += getFeatures(this);

        if (features.length > 0) {
            if (features.substr(features.length - 1, 1) == ",")
                features = features.substr(0, features.length - 1);
            window.open(this.href, '_new', features);
        } else {
            window.open(this.href);
        }
        return false;
    }
    return true;
}

function getValueFromClass(obj, attrib) {
  if (obj.className.indexOf(" "+attrib) != -1) {
    start = obj.className.indexOf(" "+attrib) + 1
    end = obj.className.indexOf(" ", start);
    end = (end == -1) ? obj.className.length - start : end - start;
    var aLength = attrib.length;
    return obj.className.substr(start+aLength, end-aLength);
  } else {
    return "";
  }
}

function isAssetDoc(obj) {
  var types = new Array("pdf", "doc", "xls", "ppt", "cvxn");
  var fileExt = getFileExt(obj);
  
  for(i=0; i<types.length;i++) {
    if (types[i] == fileExt) {
      return true;
    }
  }
  return false;
}

function getFileExt(obj) {
    var url = obj.href;
    var ext = url.substr(url.lastIndexOf(".") + 1);

    if (ext == "cvxn") {
        ext = url.substr(url.lastIndexOf(".") - 3, 3);
    }

    return ext;
}

function getFeatures(obj) {
  var features = "";
  if (obj.className.indexOf(" scroll") != -1) {
    features += "scrollbars=yes,";
  }
  return features;
}

// grab root url for use in email page form
var url = location.href;
var urlArr = url.split('#',1);
var rooturl = urlArr[0];
	//alert(rooturl);

/*
 * rClearText
 * Clears an input box if text is equal to default text onfocus. Adds default back on blur if input box is empty
 */
function rClearText(el) {
	this.initialize(el);
}
rClearText.prototype = {
	initialize: function(el) {
		$(el).focus(function() {
			if (el[0].value == el[0].defaultValue) { // Text hasn't been changed yet
				el[0].value = '';
			}
		});
		$(el).blur(function() {
			if (el[0].value == '') { // Text hasn't been changed yet
				el[0].value = el[0].defaultValue;
			}
		});
	}
}
function rClearTextFocus(el) {
	if (el.value == el.defaultValue) { // Text hasn't been changed yet
		el.value = '';
	}
}

function rClearTextBlur(el) {
	if (el.value == '') { // Text hasn't been changed yet
		el.value = el.defaultValue;
	}
}
 
/*
 * rDropDown
 * Adds class of 'hover' to LI onmouseover. Removes class onmouseout. Adds iFrame fix for IE
 */
function rDropDown() {
	this.initialize();
}
rDropDown.prototype = {
	open: false,
	timeout: false,
	openLi: null,
	initialize: function() {
	    var userAgent = navigator.userAgent.toLowerCase()
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1)
            $("#topnav > ul").addClass('macFF');
            
		var lis = $("#topnav > ul > li");
		for (var i=0; i<lis.length; i++) {
			$(lis[i]).bind('mouseover', {parentThis: this, li:lis[i]}, function(params) {
				params.data.parentThis.show(params.data.li);
			});
			$(lis[i]).bind('mouseout', {parentThis: this, li:lis[i]}, function(params) {
				params.data2 = params.data;
				params.data.parentThis.timeout = setTimeout(function() {
					params.data = params.data2;
					params.data.parentThis.hide(params.data.li);
				}, 1);
			});
			$(lis[i]).bind('click', {parentThis: this, li:lis[i]}, function(params) {
			    $(params.data.li).find("a").blur();
			    params.data.parentThis.hide(params.data.li);
			});
		}
	},
	show: function(li) {
		if (this.openLi && this.openLi != li) {
			this.hide(this.openLi);
		}
		if(this.timeout){
			clearTimeout(this.timeout);
			this.timeout = false;
		}
		if(this.open){
			return;
		}
		if ($(li).hasClass('hasSub')) {
			$(li).addClass('hoverSub');
		}
		else {
			$(li).addClass('hover');
		}
		this.openLi = li;
		this.open = true;
		this.iframeFix(li);
	},
	hide: function(li) {
		if(!this.open){
			return;
		}
		$(li).removeClass('hover');
		$(li).removeClass('hoverSub');
		this.open = false;
		if (this.iframe) {
			this.iframe.style.display = "none";
		}
	},
	iframeFix: function(li) {
		if(!document.all) {
			//return;
		}
		
		var subnav = $('div.subnav', li)[0];
		if (subnav) {
			if (!this.iframe) {
				this.iframe = document.createElement('iframe');
				this.iframe.style.position = 'absolute';
				this.iframe.frameBorder = 0;
				this.iframe.style.filter = 'alpha(opacity=0)';
				this.iframe.style.zIndex = -1;
				document.body.appendChild(this.iframe);
			}
			this.iframe.style.display = "block";
			this.iframe.style.top = $(subnav).offset().top + 'px';
			this.iframe.style.left = $(subnav).offset().left + 'px';
			this.iframe.style.width = $(subnav).width() + 'px';
			this.iframe.style.height = $(subnav).height() + 'px';
		}
	}
}

/*
 * ajaxForm
 * Handles AJAX for form submission. Returns a taconite XML string.
 */
function ajaxForm(frm) {
	$.ajax({
		type: "POST",
		url: frm.action,
		data: $(frm).serialize()
	});
}


	// Disable keypress for tab to prevent double-firing when tab key is held down
	$(document).unbind("keypress").keypress(function(e) {
		if (e.keyCode == 9) {
			return false;
		}
	});
	

/*
 * onLoad functions
 * Initializes our functions on page load
 */
$(document).ready(function() {
   //new rClearText($("#Search input"));
    new rDropDown();
    // add .last class to last LI item within Breadcrumb
   // $("div#Breadcrumb ul li:last-child").addClass("last");

});

// Popup window
function openPopup( e ) {
    document.getElementById( e ).style.visibility      = 'visible';
};

function closePopup( e ) {
    document.getElementById( e ).style.visibility      = 'hidden';
};

addLoadEvent(GetAnchors);

//**************************************************************************************************************//
// CR homepage banner behavior.

function dynamicContentHeader(contentDisplayItems, navItems, thumbnailSelection, defaultStoryClass) {
	this.contentItems = [];
	this.currentContent = null;
	this.cycleIntervalId;
	this.timeoutIntervalId;
	this.mouseActivityTimer = 0;
	this.cycleDelay = 5;
	this.cycleRestartTimeout = 60;

	for (var i=0; i < contentDisplayItems.length; i++) {
		this.contentItems.push(new dynamicHeaderItem(contentDisplayItems[i], navItems[i], i, this));
	}

	contentDisplayItems.css("z-index", 1);
	navItems.css("z-index", 7);

	this.thumbnailSelection = thumbnailSelection;
	thumbnailSelection.css("z-index", 8).remove();

	var engine = this;
	this.scopedResetMouseActivityTimer = function() { engine.resetMouseActivityTimer() };
	this.scopedNextContentItem = function() { engine.nextContentItem() };
	this.scopedCheckMouseActivityTimer = function() { engine.checkMouseActivityTimer() };

	var defaultStoryIndex = 0;
	if (defaultStoryClass != undefined) {
	    var defaultStoryDiv = contentDisplayItems.filter(defaultStoryClass);
	    if (defaultStoryDiv.length > 0) {
	        defaultStoryIndex = contentDisplayItems.index(defaultStoryDiv[0]);
	    }
	}

	this.startCycle();
	this.showContentAt(defaultStoryIndex);
}

dynamicContentHeader.prototype = {

	nextContentItem: function() {
		this.showContentAt((this.currentContent.index + 1) % this.contentItems.length);
	},

	showContentAt: function(i) {
		this.showContent(this.contentItems[i]);
	},

	showContent: function(contentItem, instant) {
		var previousContent = this.currentContent;
		this.currentContent = contentItem;
		contentItem.select(previousContent, instant);
		$(this.currentContent.navItem).prepend(this.thumbnailSelection);
	},

	resetMouseActivityTimer: function() {
		this.mouseActivityTimer = 0;
	},
	
	checkMouseActivityTimer: function() {
		this.mouseActivityTimer++;
		if (this.mouseActivityTimer == this.cycleRestartTimeout) {
			this.startCycle();
		}
	},

	startCycle: function(startNow) {
		$(document).unbind("mousemove", this.scopedResetMouseActivityTimer);
		clearInterval(this.timeoutIntervalId);
		clearInterval(this.cycleIntervalId);
		this.cycleIntervalId = setInterval( this.scopedNextContentItem, 1000 * this.cycleDelay);
		if (startNow == true) {
			this.nextContentItem();
		}
	},
	
	stopCycle: function() {
		this.mouseActivityTimer = 0;
		$(document).bind("mousemove", this.scopedResetMouseActivityTimer);
		clearInterval(this.cycleIntervalId);
		clearInterval(this.timeoutIntervalId);
		this.timeoutIntervalId = setInterval( this.scopedCheckMouseActivityTimer, 1000);
	}
}

///////////////////////////////////////////////////////////////////////////
//

function dynamicHeaderItem(contentItem, navItem, index, engine) {
	this.index = index;
	this.navItem = navItem;
	this.contentItem = contentItem;
	this.engine = engine;
	var this2 = this;
	$(this.navItem).children("a").attr("href", "#");
	$(this.navItem).click(function(e){
		this2.onItemClick();
		e.stopPropagation();
        e.preventDefault();
	});
}

dynamicHeaderItem.prototype = {
	select: function(previousContent, instant) {
		if (previousContent) {
			previousContent.deselect();
		}

		var duration = instant ? 10 : 1000;
		$(this.navItem).filter(".navItemUnselected").removeClass("navItemUnselected");
		$(this.navItem).addClass("navItemSelected");
		$(this.contentItem).css("z-index", 9).fadeIn(duration, function() {
			if (previousContent && previousContent.contentItem != this) {
				$(previousContent.contentItem).fadeOut(0);
			}
		});
	},

	deselect: function() {
		$(this.navItem).addClass("navItemUnselected");
		$(this.navItem).filter(".navItemSelected").removeClass("navItemSelected");
		$(this.contentItem).css("z-index", 1);
	},

	onItemClick: function() {
		this.engine.showContent(this, true);
		this.engine.stopCycle();
	}
}

///////////////////////////////////////////////////////////////////////////
// AR/CR Home Banner ready items

$(document).ready(function() {
var sectionPrefixes = ["arHome", "crHome", "nextHome", "ar2010Home"];
    var i = 0;
    while (i < sectionPrefixes.length) {
        var sectionIdPrefix = "#" + sectionPrefixes[i];
        if ($(sectionIdPrefix + "DisplayArea").length > 0) {
            mainHeader = new dynamicContentHeader(
		        $(sectionIdPrefix + "DisplayArea .displayItem"),
		        $(sectionIdPrefix + "NavArea .navItem"),
		        $(sectionIdPrefix + "NavArea .thumbnailSelection")
	        );
            break;
        }
        i++;
    }
});

///////////////////////////////////////////////////////////////////////////
// Video ID deeplinking in hash
// fixes the fact that ie7 now reports itself as MSIE 6.0 compatible

$(document).ready(function () {
    var videoIdRegex = /\bvideoid=([^&?]*)/i;
    var videoThickboxOpened = false;
    var queryVideoIdMatch = videoIdRegex.exec(location.search)
    var queryVideoId = queryVideoIdMatch != null ? queryVideoIdMatch[1] : undefined;
    $("a.thickboxVideoJavascriptRefresh").each(function (i) {
        var $this = $(this);
        var videoIdMatch = videoIdRegex.exec(this.href);
        if (videoIdMatch != null) {
            var videoId = videoIdMatch[1];
            this.href = '?videoId=' + videoId;
            $this.removeClass("thickbox");
            $this.unbind("click");
            if (!videoThickboxOpened && videoId == queryVideoId) {
                var $accordion = $this.parents('.accordion');
                videoThickboxOpened = true;
                if ($accordion.length > 0) {
                    var $drawer = $this.parents('.box');
                    var $header = $drawer.prev('h3');
                    setTimeout(function () {
                        window.drawers.hideAllDrawers();
                        window.drawers.showDrawers($drawer);
                    }, 1000);
                }
            }
        }
    });
});

  

// framebuster scripts
var sThisURL = unescape(window.location.pathname);

function doFramesBuster() {
    if (top.location.href.indexOf('.chevron.com') == -1 && top.location != self.location)
        breakFrames();
}

function breakFrames() {
    top.location.replace(sThisURL);
}    

$(document).ready(function(){
    doFramesBuster()
});

var addthis_config = {
    services_exclude: 'print, email'
};


