$(function() {
    // preload rollover imagery
    var imageArray = [];
    var newImage = new Image();
    newImage.src = "/images/arrow_right_blue_small.png";
	  imageArray[imageArray.length] = newImage;
    $("#components ul.piped-list img, #primary-nav img[@class != 'selected']").each(function(i) {
        newImage = new Image();
        newImage.src = $(this).attr("src").replace(".png", "_hover.png");
		    imageArray[imageArray.length] = newImage;
	  });

	$("ul.piped-list>li:not(:last-child)").append("<span>|</span>");
	$("#components ul.piped-list img, #primary-nav img[@class != 'selected']").hover(function() {
		$(this).attr("src", $(this).attr("src").replace(".png", "_hover.png"));
	}, function() {
		$(this).attr("src", $(this).attr("src").replace("_hover.png", ".png"));
	});
	 $('h4 a').mouseover(function() {
            $(this).children('img').attr("src", "/images/arrow_right_red.png");
        }).mouseout(function() {
            $(this).children('img').attr("src", "/images/arrow_right_blue_small.png");
        });
    if ($("h1").html() == "Microsoft Word" || $("h1").html() == "Merchandise")
    {
        $("#content ul").css("width","380px");
        $("#content dl").css("width","380px");
    }
    if ($("h1").html() == "Merchandise" || $("h1").html() == "Brand Match Game")
    {
        $("#content").css("width","620px");
        // adjust for IE
		/*@cc_on
			@if (@_jscript_version >= 5.5)
                $("#left").css("margin-left","-820px");
            @end
		@*/
        $("#content .examples p").css("width","620px");
    }
	$("#relatedfaqs dt").hover(function()
	{
	    $(this).css("text-decoration", "underline");
	},
	function ()
	{
	    $(this).css("text-decoration", "none");
	});
	$("#primary-nav").appendTo("#footer");
    $("#primary-nav>li").hover(function()
	    {
		    var ieLeftOffset = 0;
		    var ieTopOffset = 0;
		    // adjust for IE
		    /*@cc_on
			    @if (@_jscript_version >= 5.5)
				    ieLeftOffset = 0;
				    ieTopOffset = -1;
				    //$("#components").css("z-index","-1");
				    //$("#components ul.piped-list a img").css("z-index","-1");
			    @end
		    @*/
		    $(this).children("ul").css("left", (this.offsetLeft + ieLeftOffset - 0) + "px").css("top", (ieTopOffset + 22) + "px").css("width", "165px").css("z-index", "20000").show();	
		    $("object[@data$='wmv']").css("visibility", "hidden");
		    $("object>param[@value$='wmv']:eq(0)").parent("object").css("visibility", "hidden");	    
	    },
	    function ()
	    {
		    $(this).children("ul").hide();
		    // adjust for IE
		    /*@cc_on
			    @if (@_jscript_version >= 5.5)
				    //$("#components").css("z-index","0");
				    //$("#components ul.piped-list a img").css("z-index","0");
			    @end
		    @*/
		    $("object[@data$='wmv']").css("visibility", "visible");
		    $("object>param[@value$='wmv']:eq(0)").parent("object").css("visibility", "visible");	    
	    }
    );
	
	$("#my-links/ul/li/a").addClass("parent-open");
	$("#my-links/ul/li/a").click(function() {
		$("ul", $(this).parents("li")).toggle();
		$(this).toggleClass("parent-open");
		$(this).blur();
	});
	$("#relatedfaqs dd").hide();
	$("#relatedfaqs dt").click(function() {
		$("#relatedfaqs dd").hide();
		$(this).next().toggle();
	});
	$("#relatedfaqs dd span.close").click(function() {
		$(this).parents('dd:first').hide();
	});
	initOverLabels();
	$("input.cyansubmit").mouseover(function() {
		$(this).attr("src", "/images/join.png");
	}).mouseout(function() {
		$(this).attr("src", "/images/go.png");
	});
	$("input.whitesubmit").mouseover(function() {
		$(this).attr("src", "/images/go.png");
	}).mouseout(function() {
		$(this).attr("src", "/images/join.png");
	});
	$("div.examples a").click(function() {
		window.open(this.href);
		return false;
	});
	//$("#content div.column").equalHeight();
	/* My Saved Advertisements */
	$("a.deleteAd").click(function()
		{
			return confirm('Are you sure that you would like to delete this advertisement?');
		}
	);
	$("a.viewAd").click(function()
		{
			window.open($("#" + this.id.replace(/_View/, "_NameLink")).attr("href"), "new", 'width=840,height=540,resizable=yes,scrollbars=yes,status=yes');
			return false;
		}
	);
	/* \my saved ads */
	$("a[@href$='chooselogo/default.aspx'], a[@href$='chooselogo/']").click(function()
		{
			window.open(this.href, "logo", 'width=840,height=540,resizable=yes,scrollbars=yes,status=yes');
			return false;
		}
	);
	$("a[@href$='createad/default.aspx'], a[@href$='createad/']").click(function()
		{
			window.open(this.href, "ad", 'width=840,height=655,resizable=yes,scrollbars=yes,status=yes');
			return false;
		}
	);
	
	// background flicker in IE6
	/*@cc_on
		@if (@_jscript_version <= 5.7)
			if (document && document.execCommand) {
				try { document.execCommand("BackgroundImageCache",false,true); }
				catch (e) { }
			}
			// hasLayout fix
			$(".hasLayout").css("zoom", "1.0");
        @end
	@*/
	$("a[@title='Email Page']").attr("href","mailto:?subject=" + escape("Chevron Brand & Advertising Center") + "&body=" + escape(document.title + ":\n\nhttp://www.chevronbrand.com" + window.location.pathname + window.location.search));
	addToolTips();
	
	// content that is too wide will displace the left menu in IE6
	/*@cc_on
	@if (@_jscript_version <= 5.6)
		if ($("#middle").length > 0 && $("#left").length > 0)
		{
			var middleoverflow = $("#middle").width() - $("#middle").css("width").replace("px", "");
			if (middleoverflow > 0) {
				var newleftmargin = $("#left").css("margin-left").replace("px", "") - middleoverflow;
				$("#left").css("margin-left", newleftmargin);
			}
		}
	@end
	@*/
	
	// enter key search submit
	$("input[@id$=txtSearch]").keydown(function(e)
		{
			if (e.keyCode == 10 || e.keyCode == 13)
			{
				$("input[@id$=butSearch]").click();
				return false;
			}
		}
    );
    
 	// enter key login submit
	$("input[@id$=UserName], input[@id$=Password]").keydown(function(e)
		{
			if (e.keyCode == 10 || e.keyCode == 13)
			{
				$("input[@id$=LoginButton]").click();
				return false;
			}
		}
   );
   
    // IE print page breaks
    if ($("middle").length > 0)
    {
        $("#middle #content div.column").prev("p").css("page-break-after", "always");
    }

    // links that open in a new window  
    $("a.new, a[@href$=ppt], a.external").click(function()
        {
          window.open(this.href);
          return false;
        }
    );
    
    // IE object fix for "click to activate" issue
    /*@cc_on
    @if (@_jscript_version >= 5.0)
        fixObjects();
        $(document).bind("unload", function() {
            $("object").each(function(i) {
                this.outerHTML = "";
            });
        });
    @end
    @*/
    
    /* NiceSpots Login */
    $("#NiceSpots").bind("click", function () {
        var formHtml = '<form action="https://www.nicespots.com/nicespots/popup.php" method="post" id="nicespotsForm" target="_self">loading<input type="hidden" name="colorSetIDIn" value="14" />.<input type="hidden" name="clientID" value="16" />.<input type="hidden" name="userName" value="chevron@nicespots.com" />.<input type="hidden" name="password" value="chevronenergy" />.</form>';
		if ((navigator.appVersion.indexOf("IE 7.0") > 0) && (navigator.appVersion.indexOf("NT 6.0") > 0))
		{
		    // special case for IE7.0 on Vista
		    var nsw = window.open("about:blank", "_self");
		    nsw.document.write(formHtml);
		    $("#nicespotsForm", nsw.document).submit();
		    history.back();
		}
		else
		{
			var nsw = window.open("about:blank");
		    nsw.document.write(formHtml);
		    $("#nicespotsForm", nsw.document).submit();
		}
        
        return false;
    });
});

function fixObjects()
{
    $("object").each(function(i) {
        if(this.outerHTML) {
            if(this.data) {
                this.removeAttribute('data');
            }
            var flashVars;
            $(this).find("param").each(function(j) {
                if(this.name.toLowerCase() == 'flashvars') {
                    flashVars = this.value;
                }
            });
            this.outerHTML = this.outerHTML.replace(/<param name="FlashVars" value="">/ig, "<param name='FlashVars' value='" + flashVars + "'>");
        }
    });
}

function addToolTips()
{
	// add better tooltips to info items
	$("em.tooltip").each(function() 
		{
			$(this).after("<p class=\"tooltip\" style=\"display: none;\">" + this.title + "</p>").empty().append("<img src=\"/images/help.png\" width=\"11\" height=\"11\" alt=\"help\" />");
			this.title = "";
			$(this).mouseover(function()
				{
					$(this).next().show();
				}
			);
			$(this).mouseout(function()
				{
					$(this).next().hide();
				}
			);
		}
	);
}

function initOverLabels() {
	$("label.overlabel[@for]").each(function() {
		var label = $(this);
		label.attr("class", "overlabel-apply");
		var field = $("#" + label.attr("for"));
		if (field.val() !== "") {
			label.hide();
		}
		field.focus(function() {
			label.hide();
		}).blur(function() {
			if (field.val() === "") {
				label.show();
			}
		});
		label.click(function() {
			field.trigger("focus");
		});
	});	
}

$.fn.equalHeight = function(){
	var max_height = 0;
	
	this.each(function(){
	    var bottom = this.offsetTop + $(this).height();
		if (bottom > max_height) {
		    max_height = bottom;
		}
	});
	
	this.each(function(){
	    var cur_height = $(this).height();
	    
	    // we don't want to touch the div we are trying to match up against, so test to see if the height of the div is smaller than what we are trying to match
	    if (max_height - this.offsetTop > cur_height)
	    {
	        // remove bottom padding since the div will grow anyway, then get current height again
	        this.style.paddingBottom = 0;	    
	        cur_height = $(this).height();
	    
	        // remove top padding and calculate what it was so we can add it later. keeping padding will skew the height.
	        this.style.paddingTop = 0;
	        var pad_top = cur_height - $(this).height();
    	    
	        var new_height = max_height - this.offsetTop - pad_top;
		    $(this).css("height", new_height);
		    $(this).css("padding-top", pad_top);
		}
	});
};

/* 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 = ['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('printPage') != -1) {
		    x[i].onkeypress = printPage;
		    x[i].onclick = printPage;
		    x[i].setAttribute("title", "Print Page");
		// see chevron_ga.js for new ga code
        //} 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])) {
          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 printPage() {
    window.print();
}
  
function getValueFromClass(obj, attrib) {
    if (obj.className.indexOf(" " + attrib) != -1) {
        var start = obj.className.indexOf(" " + attrib) + 1;
        var 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 openNewWindow(e) {
  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'), 10)>0 ? getValueFromClass(this, 'w') : '';
  height = parseInt(getValueFromClass(this, 'h'), 10)>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 isAssetDoc(obj) {
  var types = ["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;
}

function rAccordin() {
	this.initialize();
}
rAccordin.prototype = {
	initialize: function() {
        // close all drawers except first
        $('div.accordion> div:not(#a1)').hide().addClass("printOnly").css("display","");
        $('div.accordion > h3:first').removeClass("closed").addClass("open");
        
        //override first drawer open by adding closeFirst class to first h3 element in accordion
        $('div.accordion > h3.closeFirst').removeClass("open").addClass("closed");
                
        // if there is a qs parameter, open only that drawer
        try {
            var qs = new Querystring();
            if(qs.get("d")) {
                $('div.accordion> div').hide().addClass("printOnly").css("display","").siblings('h3').removeClass("open").addClass("closed");
                var p1 = qs.get("d");
                $('div#' + p1).show().removeClass("printOnly").css("display","");
                $('div#' + p1).prev('.closed').removeClass("closed").addClass("open");
            }
        }
        catch(qserr) {
        }
        
        // open and close drawers on mouseclick
        $('div.accordion> h3').click(function() {
            $(this).next('div').slideToggle('fast', function () {
                $(this).toggleClass('printOnly').show().css("display","");
            });
            // Close other drawers
            /*$(this).next('div').siblings('div').slideUp('fast', function () {
                $(this).addClass('printOnly').show().css("display","");
            }); */
            $(this).toggleClass("open");
            $(this).toggleClass("closed");
        });
        
        $('div.accordion> h3').mouseover(function() {
            $(this).css("text-decoration", "underline");
            $(this).css("color", "#4082C6");
            $(this).css("cursor", "pointer");
        });
        
        $('div.accordion> h3').mouseout(function() {
            $(this).css("text-decoration", "none");
        });
        
    }
};

addLoadEvent(GetAnchors);

$(document).ready(function(){
	new rAccordin();
});
