/* 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();
    }
  }
}

var gaPageName = "";

/*
 * 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('html') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Download");
        //} else if (x[i].className.indexOf('external') != -1) {
          //x[i].onkeypress = openNewWindow;
          //x[i].onclick = openNewWindow;
          //x[i].setAttribute("title", "Offsite Link");
        } 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 (x[i].className.indexOf('catchCode') != -1) {
          //Will not add if one of the above is used,
          //so opneNewWindow also checks
          x[i].onkeypress = gaCatchCode;
          x[i].onclick = gaCatchCode;
        } 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 gaCatchCode(e) {
  urchinTracker(GetGAPath(this));
}

function GetGAPath(obj) {
  return "/catchcode/" + getValueFromClass(obj, 'ga');
}

function openNewWindow(e) {
  if (this.className.indexOf('catchCode') != -1) {
    urchinTracker(GetGAPath(this));
  } else 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);  
    }
    urchinTracker(url);
  }
  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;
}

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");
  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;
  return url.substr(url.lastIndexOf(".")+1);
}

function getFeatures(obj) {
  var features = "";
  if (obj.className.indexOf(" scroll") != -1) {
    features += "scrollbars=yes,";
  }
  return features;
}

// Flash Deep Linking
function track( param ) {
	// code here for call to tracking analytics
}
function track( param )	{
	// code here for call to tracking analytics
}
	// 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 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);
			});
		}
	},
	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';
		}
	}
}

/*
 * rPromoBox
 * Toggles open/closed state for promo boxes
 */
function rPromoBox() {
	this.initialize();
}
rPromoBox.prototype = {
	initialize: function() {
		var promos = $('div.promo');
		for (var i=0; i<promos.length; i++) {
			var els = new Object();
			els.openDiv = $('div.open', promos[i]);
			els.openDivHeader = $('h3 a', els.openDiv);
			els.closedDiv = $('div.closed', promos[i]);
			els.closedDivHeader = $('h3 a', els.closedDiv);
			els.nav = $('ul.promoNav', promos[i])[0];
			if (els.nav) {
				this.initNav(promos[i], els.nav);
			}
			$(els.openDivHeader).bind('click', {parentThis: this, els: els}, function(params) {
				params.data.parentThis.hide(params);
				return false;
			});
			$(els.closedDivHeader).bind('click', {parentThis: this, els: els}, function(params) {
				params.data.parentThis.show(params);
				return false;
			});
		}
	},
	show: function(params) {
		$(params.data.els.closedDiv).hide();
		$(params.data.els.openDiv).show();
	},
	hide: function(params) {
		$(params.data.els.openDiv).hide();
		$(params.data.els.closedDiv).show();
	},
	initNav: function(el, nav) {
		var els = new Object();
		els.one = $('div.one', el)[0];
		els.two = $('div.two', el)[0];
		els.navOne = $('li.one a', nav)[0];
		els.navTwo = $('li.two a', nav)[0];
		$(els.navOne).bind('click', {parentThis: this, els: els}, function(params) {
			params.data.parentThis.pageOne(params);
			return false;
		});
		$(els.navTwo).bind('click', {parentThis: this, els: els}, function(params) {
			params.data.parentThis.pageTwo(params);
			return false;
		});
	},
	pageOne: function(params) {
		$(params.data.els.navTwo).removeClass('selected');
		$(params.data.els.navOne).addClass('selected');
		$(params.data.els.two).hide();
		$(params.data.els.one).show();
	},
	pageTwo: function(params) {
		$(params.data.els.navOne).removeClass('selected');
		$(params.data.els.navTwo).addClass('selected');
		$(params.data.els.one).hide();
		$(params.data.els.two).show();
	}
}

/*
 * ajaxForm
 * Handles AJAX for form submission. Returns a taconite XML string.
 */

function ajaxForm(frm) {
	$.ajax({
		type: "POST",
		url: frm.action,
		data: $(frm).serialize()
	});
}

/*
 * validateForm
 * Validates form for thickboxes
 */

function validateForm(frm) {
	var errors = new Array();
	
	for (var i=0; i<frm.elements.length; i++) {
		$(frm.elements[i].parentNode.parentNode).removeClass('error');
		if ($(frm.elements[i]).is('.req')) {
			// Not empty
			if(frm.elements[i].value.match(/^\s*$/)) {
				errors.push(frm.elements[i].name + ' cannot be empty');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
			// publication not chosen on printed copy request form	
			if(frm.elements[i].value.match("Select From List")) {
				errors.push(frm.elements[i].name + " cannot be 'Select From List'");
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
		}
		else if ($(frm.elements[i]).is('.email')) {
			// Valid email
			if(frm.elements[i].value.match(/^\s*$/)) {
				// Not empty
				errors.push(frm.elements[i].name + ' cannot be empty');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
			else if(!frm.elements[i].value.match(/^[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+$/)) {
				// Valid email
				errors.push(frm.elements[i].name + ' is not a valid email');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
		}
		else if ($(frm.elements[i]).is('.email2')) {
			// email2 matches email
			if(frm.elements[i].value != $('.email', frm)[0].value) {
				errors.push('Email addresses do not match');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
		}
	}
	if (errors.length > 0) {
		var errorMsg = '<h3>Important Message: Before you can continue there are a few errors to correct ...</h3>';
		errorMsg += '<ul>';
		for (var i=0; i<errors.length; i++) {
			errorMsg += '<li>'+ errors[i] + '</li>';
		}
		errorMsg += '</ul>';
		$('.errorBox', frm)[0].innerHTML = errorMsg;
		$('.errorBox', frm).show();
		
	}
	else {
		ajaxForm(frm);
	}
}

//hack thickbox to have a callback
tb_show2 = tb_show;
window.tb_show = function() {
	var a = arguments;
	tb_show2.apply(this, a);
	//setTimeout('tb_callback()', 100);
	tb_callback();
}
//The thickbox callback function
function tb_callback() {
	// Add wrappers
	var TB_window = $('#TB_window')[0];
	var container = document.createElement('div');
	container.id = "TB_wrapper";
	var imgContainer = document.createElement('div');
	imgContainer.id = "TB_popupImg";
	container.appendChild(imgContainer);
	var contentPad = document.createElement('div');
	contentPad.id = "TB_contentPad";
	container.appendChild(contentPad);
	var content = document.createElement('div');
	content.id = "TB_content";
	contentPad.appendChild(content);
	while(TB_window.childNodes.length > 0) {
		content.appendChild(TB_window.childNodes[0]);
	}
	TB_window.appendChild(container);
	
	// Remove text nodes from TB_closeAjaxWindow
	var TB_closeAjaxWindow = $('#TB_closeAjaxWindow')[0];
	for (var i=0; i<TB_closeAjaxWindow.childNodes.length; i++) {
		if (TB_closeAjaxWindow.childNodes[i].nodeType == '3') {
			TB_closeAjaxWindow.removeChild(TB_closeAjaxWindow.childNodes[i]);
		}
	}
}

addLoadEvent(function() {
	new rPromoBox();
});

/*
 * onLoad functions
 * Initializes our functions on page load
 */
$(document).ready(function(){
	new rClearText($("#Search input"));
	new rDropDown();

    // add enter key event to search text box in search container
    $("#Search input[@id$=search]").keydown(function(e) {
        if (e.keyCode == 10 || e.keyCode == 13) {
            $("#Search input:image").click();
            return false;
        }
    });

    // add enter key event to search text box in content container
    $("#Content input[@id$=SearchTerms]").keydown(function(e) {
        if (e.keyCode == 10 || e.keyCode == 13) {
            $("#Content input[@id$=Search]").click();
            return false;
        }
    });
    
    // send search queries directly to search page
    $("#Search input:image").click(function() {
        var searchVal = $("#Search input[@id$=search]").val();
        var appPath = (location.pathname.indexOf("/ChevronWebSite") >= 0) ? "/ChevronWebSite" : "";
        searchVal = escape(searchVal);
        window.location.href = appPath + "/search/?text=" + searchVal + "&Header=FromHeader";
        return false;
    }).keypress(function() {
        $(this).click();
    });
    
    // global search page functionality
    if ($("#Content select[@id$=ContentType], #Content select[@id$=Month], #Content select[@id$=Year]").length >= 5) {
        // disable month/year
        $("#Content select[@id$=ContentType]").bind("change", function() {
            if (this.selectedIndex != 0) {
                $("#Content fieldset>div:eq(2), #Content fieldset>div:eq(3)").show();
            } else {
                $("#Content fieldset>div:eq(2), #Content fieldset>div:eq(3)").hide();
            }
        }).trigger("change");
    }
});


// Popup window
  function openPopup( e ) {
    document.getElementById( e ).style.visibility      = 'visible';
    };

  function closePopup( e ) {
    document.getElementById( e ).style.visibility      = 'hidden';
    };

// Goto URL

function goTo(url,target){

 if (target=="_blank") {
 var OpenWindow=window.open("/transfer.aspx?url="+escape(url));
 OpenWindow.focus();
 }
 else {
	location.href = url; 
 }
}

addLoadEvent(GetAnchors);
