function objectCount(obj){
	var count = 0;
	for(var k in obj){
		if(obj.hasOwnProperty(k)){
			count++;
		}
	}
	return count;
}

function sortObj(arr){
	var sortedKeys = new Array();
	var sortedObj = {};
	
	for(var i in arr){
		sortedKeys.push(i);
	}
	function sortNumber(a, b){ return a - b; }
	sortedKeys.sort(sortNumber);
	
	for(var i in sortedKeys){
		sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
	}
	return sortedObj;
}

function roundTo(value, increment){
	var remain = value % increment;
	var roundValue = increment / 2;
	
	if(remain >= roundValue){
		var result = value - remain;
		return result += increment;
	}else{
		return value - remain;
	}
}

// IE support for addEventListener (called by xb.addEvent(element, event, function, capture))
var xb = {
	evntHash: [],
	ieGetUniqueID: function(_elem){
		if(_elem === window){return "theWindow";}
		else if(_elem === document){return "theDocument";}
		else{return _elem.uniqueID;}
	},
	addEvent: function(_elem, _evntName, _fn, _useCapture){
		var self = this;
		if(typeof _useCapture === "undefined") _useCapture = false;
		if(typeof _elem.addEventListener !== "undefined"){
			_elem.addEventListener(_evntName, _fn, _useCapture);
		}else if(typeof _elem.attachEvent !== "undefined"){
			var key = "{FNKEY::obj_" + self.ieGetUniqueID(_elem) +
					  "::evnt_" + _evntName + "::fn_" + _fn + "}",
				f = self.evntHash[key];
			if(typeof f !== "undefined") return;
			f = function(){
				_fn.call(_elem);
			};
			
			self.evntHash[key] = f;
			_elem.attachEvent("on" + _evntName, f);
			
			window.attachEvent("onunload", function(){
				_elem.detachEvent("on" + _evntName, f);
			});
			key = null;
		}else{
			_elem["on" + _evntname] = _fn;
		}
	},
	removeEvent: function(_elem, _evntName, _fn, _useCapture){
		var self = this;
		if(typeof _elem.removeEventListener !== "undefined"){
			_elem.removeEventListener(_evntName, _fn, _useCapture);
		}else if(typeof _elem.detachEvent !== "undefined"){
			var key = "{FNKEY::obj_" + self.ieGetUniqueID(_elem) +
					  "::evnt_" + _evntName + "::fn_" + _fn + "}",
				f = self.evntHash[key];
			if(typeof f !== "undefined"){
				_elem.detachEvent("on" + _evntName, f);
				delete self.evntHash[key];
			}
			key = null;
		}
	}
};

// IE Canvas Hack
(function($) {
	$.fn.CanvasHack = function() {
		var canvases = this.find('canvas').filter(function() {
			return $(this).css('position') == 'absolute';
		});
		
		canvases.wrap(function() {
			var canvas = $(this);
			var div = $('<div />').css({
				position: 'absolute',
				top: canvas.css('top'),
				left: canvas.css('left')
			});
			canvas.css({
				top: '0',
				left: '0'
			});
			return div;
		});
		
		return this;
	};
})(jQuery);

// The site object

ProPricing = {

	init: function(){
		// is this user on ie?
		if(typeof ie === "undefined") ie = false;
		if(typeof ie9 === "undefined") ie9 = false;
		// support for getting elements based on classes on older browsers
		if(document.getElementsByClassName == undefined){
			document.getElementsByClassName = function(className){
				var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
				var allElements = document.getElementsByTagName("*");
				var results = [];
				var element;
				for(var i = 0; (element = allElements[i]) != null; i++){
					var elementClass = element.className;
					if(elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)){
						results.push(element);
					}
				}
				return results;
			}
		}
		// placeholder support
		var placeholderTest = document.createElement("input");
		var supportsPlaceholder = "placeholder" in placeholderTest;
		if(!supportsPlaceholder){
			var els = document.getElementsByTagName("*");
			for(var i = 0; i < els.length; i++){
				if(els[i].nodeName.toLowerCase() === "input" || els[i].nodeName.toLowerCase() === "textarea"){
					var t = els[i];
					if(t.getAttribute("placeholder")){
						xb.addEvent(t, "blur", function(){
							if(this.value === "") this.value = this.getAttribute("placeholder");
						});
						xb.addEvent(t, "focus", function(){
							if(this.value === this.getAttribute("placeholder")) this.value = "";
						});
						if(t.value === "") t.value = t.getAttribute("placeholder");
					}
				}
			}
		}
		if(ie && !ie9){
			document.createElementOverride = document.createElement;
			document.createElement = function(type){
				if(type.toLowerCase() === "canvas"){
					var canvas = document.createElementOverride(type);
					if(typeof FlashCanvas != "undefined"){
						FlashCanvas.initElement(canvas);
					}
					return canvas;
				}else{
					return document.createElementOverride(type);
				}
			}
		}
		// IE canvas print hack
//		$('body').CanvasHack();
	},
	
	home: function(){
		var currSlide = 0,
			slideTimeout,
			$slideshow = $("#slideshow"),
			$slideReel = $slideshow.find("#slideshow-reel"),
			maxSlide = $slideReel.children().length -1,
			slideTime = 10000;
		
		function changeSlide(newSlide){
			currSlide = newSlide;
			
			if(currSlide > maxSlide){
				currSlide = 0;
			}else if(currSlide < 0){
				currSlide = maxSlide;
			}
			
			$slideReel.animate({
				left: currSlide * -854
			}, 400, 'swing', function(){
				$(".nav-item").removeClass("active");
				$("#slide-"+currSlide).addClass("active");
				slideTimeout = setTimeout(nextSlide, slideTime);
			});
		}
		
		function nextSlide(){
			changeSlide(currSlide + 1);
		}
		
		$("#slide-0").addClass("active");
		
		$(".nav-item").click(function(){
			clearTimeout(slideTimeout);
			changeSlide($(this).attr("rel"));
		});
		
		slideTimeout = setTimeout(nextSlide, slideTime);
	},
	
	news: function(){
		// check for current has
		var hash = window.location.hash.replace("#", "");
		if(hash !== ""){
			switch(hash){
				case "calendar":
					cargillTab.setActive(document.getElementsByClassName("calendar")[0].getElementsByTagName("a")[0], 'cargill-tab-content-1');
					break;
				case "videos":
					cargillTab.setActive(document.getElementsByClassName("videos")[0].getElementsByTagName("a")[0], 'cargill-tab-content-2');
					break;
				case "audio":
					cargillTab.setActive(document.getElementsByClassName("audio")[0].getElementsByTagName("a")[0], 'cargill-tab-content-3');
					break;
			}
		}
		$("#cargill-tab-nav li a").click(function(){
			var hash = $(this).parent("li").data("tab");
			window.location.hash = hash;
		});
	}

};

AdvantageFactor = {

	currentQuestion: 1,
	
	init: function(){
		var self = this;
		$(".question").change(function(){
			var question = $(this).attr("class").match(/(\d+)/);
			var nextQuestion = parseInt(question[0]) + 1;
			if(nextQuestion === 10){
				$(".active").removeClass("active");
				$("#questionnaireSubmit").attr("disabled", false).removeClass("disabled");
			}else if(self.currentQuestion < nextQuestion){
				self.currentQuestion = nextQuestion;
				$(".active").removeClass("active");
				$("#question_" + nextQuestion).addClass("active").removeClass("inactive");
				$("." + nextQuestion).removeProp("disabled");
			}
		});
		$("#questionnaireSubmit").click(function(evnt){
			evnt.preventDefault();
			self.calculate();
		});
		$("#reset").click(function(event){
			self.reset(event);
		});
	},
	
	reset: function(event){
		var self = this;
		event.preventDefault();
		self.currentQuestion = 1;
		$("#questionnaireSubmit").attr("disabled", true).addClass("disabled");
		$("input[type='radio']").removeProp("checked").prop("disabled", "disabled");
		$(".question.1").removeProp("disabled");
		$("#question_2,#question_3,#question_4,#question_5,#question_6,#question_7,#question_8,#question_9").removeClass("active").addClass("inactive");
		$("#question_1").addClass("active");
		$("#questionnaireSubmit").prop("disabled", "disabled");
		if(!$("#questionnaire").is(":visible")){
			$(".result").fadeOut("fast", function(){
				self.clearScale();
				$("#advantage-factor-copy").removeClass("faded");
				$("#questionnaire").fadeIn("fast");
			});
		}
	},
	
	printPage: function(){
		$('input:checked').attr("disabled", true);
		
		// html for the print window
		var content = document.createElement("div");
		content.id = "print-content";
		content.innerHTML = document.getElementsByClassName("logo_area")[0].innerHTML + document.getElementById("main_content").innerHTML;
		var wrapper = document.createElement("div");
		wrapper.appendChild(content);
		var html = "<html>";
		html += document.getElementsByTagName("head")[0].innerHTML;
		html += wrapper.innerHTML;
		html += "</html>";
		
		// create the print window
		var printWindow = window.open("");
		// check for popup blockers
		if(printWindow == null || typeof(printWindow) == 'undefined'){
			alert("Please disable your popup blocker to use this function.");
		}else{
			printWindow.document.write(html);
			printWindow.document.close();
			
			// edit the content
			printWindow.document.getElementById("advantage-factor-copy").style.display = "none";
			printWindow.document.getElementsByClassName("result")[0].style.display = "none";
			printWindow.document.getElementById("questionnaire").style.display = "block";
			printWindow.document.getElementById("buttons").style.display = "none";
			printWindow.document.getElementById("factor-scale").style.marginTop = 0;
			
			var radio = printWindow.document.getElementsByTagName("input");
			for(var r = 0; r < radio.length; r++){
				if(radio[r].disabled){
					radio[r].checked = true;
					radio[r].disabled = false;
				}
			}
			
			// focus on the print window
			printWindow.focus();
			printWindow.print();
			printWindow.close();
		}
	},
	
	edit: function(){
		var self = this;
		$(".result").fadeOut("fast", function(){
			self.clearScale();
			$("#advantage-factor-copy").removeClass("faded");
			$("#questionnaire").fadeIn("fast");
		});
	},
	
	clearScale: function(){
		$("#factor-scale-overlay").css("height", "573px");
		$("#factor-box").fadeOut("fast", function(){
			$(this).css("top", "595px");
		});
	},
	
	calculate: function(){
		var self = this,
			sum =
				parseInt($("input[name='question1']:checked").val()) +
				parseInt($("input[name='question2']:checked").val()) +
				parseInt($("input[name='question3']:checked").val()) +
				parseInt($("input[name='question4']:checked").val()) +
				parseInt($("input[name='question5']:checked").val()) +
				parseInt($("input[name='question6']:checked").val()) +
				parseInt($("input[name='question7']:checked").val()) +
				parseInt($("input[name='question8']:checked").val()) +
				parseInt($("input[name='question9']:checked").val());
		var factor = (52 - ((sum / 10) - 13));
		if(factor <= 5){
			var move = factor * 15;
		}else{
			var move = ((factor - 5) * 10);
			if((move % 5) === 0){
				move = move + (move / 5);
			}
			if(factor >= 25 && factor <= 30){
				move = move + 40;
			}else if(factor > 30 && factor <= 35){
				move = move + 30;
			}else if(factor >= 45){
				move = move + 8;
			}else if(factor > 35){
				move = move + 20;
			}else{
				move = move + 60;
			}
		}
		$("#factor-scale-overlay").animate({
			height: '-=' + move
		}, 400, function(){
			// fancy stuff here
			$("#advantage-factor-copy").addClass("faded");
			$("#your-advantage-factor").text(factor + "%");
			$("#factor-box").css("top", 595 - move).fadeIn("slow");
			$(".result").load("ajax/factor", { "factor" : factor }, function(){
				$("#questionnaire").fadeOut("fast", function(){
					$(".result").fadeIn("fast", function(){
						$("#print").click(function(evnt){
							evnt.preventDefault();
							self.printPage();
						});
						$("#reset").click(function(event){
							self.reset(event);
						});
						$("#edit").click(function(event){
							event.preventDefault();
							$("input").attr("disabled", false);
							self.edit();
						});
					});
				});
			});
		});
	}

};

CurrentCharts = {

	options: {},
	currStep: "contract",
	g: {},
	h: {},
	gVisibility: [true, false, false, false, false, false],
	hVisibility: [false, false, false, false, false],
	rendered: false,
	
	init: function(){
		var self = this;
		$('input[type="checkbox"]').prop("checked", false).prop("disabled", true);
		$('input[name="market"]').prop("checked", true);
		// hedged login
		$("#hedged-password").keypress(function(e){
			if(e.which == 13){
				self.hedgedLogin(e);
			}
		});
		$("#hedged-submit").click(function(event){
			self.hedgedLogin(event);
		});
		// reset button
		$("#reset").click(function(evnt){
			evnt.preventDefault();
			self.reset();
		});
		// print button
		$("#print").click(function(evnt){
			evnt.preventDefault();
			if(self.rendered === false){
				alert("Please finish the selection process.");
			}else{
				self.printPage();
			}
		});
		// set up Dygraph
		self.g = new Dygraph(
			document.getElementById("chart"),
			[["","","","","","",""],["","","","","","",""]],
			{
				title: "Contract Results vs Market",
				width: 800,
				height: 400,
				labels: ["Date", "Market Price", "CargillPros", "Kluis Commodities", "DiversiPro", "PacerPro", "ProMax"],
				labelsDiv: document.getElementById("chart-labels"),
				legend: "always",
				drawXGrid: false,
				xlabel: "Date",
				ylabel: "Price",
				yAxisLabelWidth: 80,
				visibility: self.gVisibility,
				colors: [ "#666", "#b60039", "#6999c6", "#cc6633", "#91a54d", "#544d84" ]
			}
		);
		self.h = new Dygraph(
			document.getElementById("hedged-chart"),
			[["","","","","",""],["","","","","",""]],
			{
				title: "Percent Hedged",
				width: 800,
				height: 200,
				labels: ["Date", "CargillPros", "Kluis Commodities", "DiversiPro", "PacerPro", "ProMax"],
				labelsDiv: document.getElementById("hedged-chart-labels"),
				legend: "always",
				drawXGrid: false,
				xlabel: "Date",
				ylabel: "Percent",
				gridLineColor: "#333",
				highlightCircleSize: 8,
				yAxisLabelWidth: 80,
				visibility: self.hVisibility,
				colors: ["#b60039", "#6999c6", "#cc6633", "#91a54d", "#544d84"]
			}
		);
		$("#chart").append('<div id="chart-overlay"></div>').append('<div id="step-help-container"><div id="step-help"><p>Select <span id="current-step-text">Contract</span> above.</p></div></div>');
		// watch for clicks
		$(".contract-click").click(function(evnt){
			evnt.preventDefault();
			self.contract(this);
		});
		$(".commodity").click(function(evnt){
			evnt.preventDefault();
			self.commodity(this);
		});
		$(".month").click(function(evnt){
			evnt.preventDefault();
			self.month(this);
		});
		$(".year").click(function(evnt){
			evnt.preventDefault();
			self.year(this);
		});
		$(".length").click(function(evnt){
			evnt.preventDefault();
			self.length(this);
		});
		$(".change-contract").click(function(evnt){
			self.graphChange(this);
		});
	},
	
	printPage: function(){
		var self = this;
		// add ids to the canvas elements
		$.each($("canvas"), function(index, el){
			if(index === 0){
				// graph
				$(el).attr("id", "theGraph");
			}else if(index === 2){
				// hedged
				$(el).attr("id", "theHedgedGraph");
			}
		});
		
		var graph = document.getElementById("theGraph");
		var graphData = graph.toDataURL("image/png");
		var hedged = document.getElementById("theHedgedGraph");
		var hedgedData = hedged.toDataURL("image/png");
		
		$.ajax({
			type: "POST",
			url: "ajax/save_canvas",
			data: {
				type: "current",
				contract: self.options["contract"],
				otherContracts: self.hVisibility,
				commodity: self.options["commodity"],
				month: self.options["month"],
				year: self.options["year"],
				length: self.options["length"],
				graph: graphData,
				hedged: hedgedData
			},
			dataType: "json",
			success: function(msg){
				// html for the print window
				var content = document.createElement("div");
				content.id = "print-content";
				content.innerHTML = $(".logo_area").html() + $("#main_content").html();
				var wrapper = document.createElement("div");
				wrapper.appendChild(content);
				var html = "<html>";
				html += document.getElementsByTagName("head")[0].innerHTML;
				html += wrapper.innerHTML;
				html += '<script src="/js/jquery-1.6.1.min.js"></script>';
				html += '<script>var graphImg = "'+msg.graph+'";var hedgedImg = "'+msg.hedged+'"</script>';
				html += '<script src="/js/print-current.js"></script>';
				html += "</html>";
				
				// create print window
				var printWindow = window.open("");
				// check for popup blockers
				if(printWindow == null || typeof(printWindow) == 'undefined'){
					alert("Please disable your popup blocker to use this function.");
				}else{
					printWindow.document.write(html);
					printWindow.document.close();
					
					// print the print window
					printWindow.focus();
				}
			}
		});
	},
	
	formatPrice: function(int){
		var string = int.toString().split(".");
		if(string[1] === undefined){
			string[1] = "0000";
		}else if(string[1].length > 4){
			string[1] = string[1].substr(0, 4);
		}else if(string[1].length < 4){
			var zerosToAdd = 4 - string[1].length;
			for(i=0;i<zerosToAdd;i++){
				string[1] = string[1] + "0";
			}
		}
		return "$" + string[0] + "." + string[1];
	},
	
	formatPercent: function(y){
		if(y === 1) return "100%";
		y = y.toString().substr(2, 4);
		if(y.length > 2){
			y = y.substr(0, 2);
		}else if(y.length < 2){
			for(var i = 0; 2 - y.length; i++){
				y = y + "0";
			}
		}
		return y + "%";
	},
	
	graphChange: function(el){
		this.gVisibility[el.id] = el.checked;
		this.g.setVisibility(el.id, el.checked);
		if(el.id != "0"){
			this.hVisibility[parseInt(el.id) - 1] = el.checked;
			this.h.setVisibility(parseInt(el.id) - 1, el.checked);
		}
	},
	
	select: function(el){
		// check if any siblings have class of selected
		if($(el).siblings("li").hasClass("selected")){
			// remove class
			$(el).siblings("li").removeClass("selected");
		}
		$(el).addClass("selected");
	},
	
	nextStep: function(el, rawExp, text){
		el.parent("div").addClass("active");
		var exp = new RegExp(rawExp);
		el.children("li").each(function(){
			if($(this).data("value").toString().match(exp)){
				$(this).addClass("active");
			}
		});
		$("#current-step-text").text(text);
	},
	
	backStep: function($steps, step){
		var self = this;
		// disable all checkboxes
		$('input[type="checkbox"]').prop("disabled", true).not("#0").prop("checked", false);
		// set visibility to zero
		self.gVisibility = [true, false, false, false, false, false];
		// if not contract back step
		if(step !== "Commodity"){
			// get contract number
			var contractId = $('input[name="' + self.options["contract"] + '"]').attr("id");
			// select contract checkbox
			$("#"+contractId).prop("checked", true);
			// make contract line visible
			self.gVisibility[contractId] = true
		}
		// clear the chart if it's rendered
		if(self.rendered){
			// empty the chart
			var date = new Date();
			date = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
			self.g.updateOptions({
				file: [[new Date(),"","","","","",""]],
				dateWindow: [ Date.parse(date), Date.parse(date) ]
			});
			self.h.updateOptions({
				file: [[new Date(),"","","","",""]]
			});
			// add the overlay
			$("#chart").append('<div id="chart-overlay"></div>').append('<div id="step-help-container"><div id="step-help"><p>Select <span id="current-step-text">' + step + '</span> above.</p></div></div>');
			self.rendered = false;
		}
		$steps.parent("div").removeClass("active");
		$steps.children("li").removeClass("selected").removeClass("active");
	},
	
	reset: function(){
		var self = this;
		self.backStep($("#length, #year, #month, #commodity, #contract"), "Contract");
		self.nextStep($("#contract"), ".", "Contract");
		self.gVisibility = [true, false, false, false, false, false];
		self.g.updateOptions({
			visibility: self.gVisibility
		});
		self.hVisibility = [false, false, false, false, false];
		self.h.updateOptions({
			visibility: self.hVisibility
		});
		$('input[type="checkbox"]').prop("checked", false);
		$('input[name="market"]').prop("checked", true);
	},
	
	contract: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "contract") self.backStep($("#length, #year, #month, #commodity"), "Commodity");
		if(self.options["contract"] !== undefined){
			self.gVisibility = [true, false, false, false, false, false];
			self.g.updateOptions({
				visibility: self.gVisibility
			});
			self.hVisibility = [false, false, false, false, false];
			self.h.updateOptions({
				visibility: self.hVisibility
			});
			$('input[type="checkbox"]').prop("checked", false);
			$('input[name="market"]').prop("checked", true);
		}
		self.select(el);
		self.options["contract"] = value;
		$("#step-help").text("Getting Commodities...");
		$.get("ajax/valid_commodities", { type: "current", contract: value }, function(exp){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			self.nextStep($("#commodity"), exp, "Commodity");
		});
		self.currStep = "commodity";
		$('input[name="' + value + '"]').prop("checked", true);
		self.gVisibility[$(el).data("id")] = true;
		self.g.setVisibility($(el).data("id"), true);
		self.hVisibility[parseInt($(el).data("id")) - 1] = true
		self.h.setVisibility(parseInt($(el).data("id")) - 1, true);
	},
	
	commodity: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "commodity") self.backStep($("#length, #year, #month"), "Option Month");
		self.select(el);
		self.options["commodity"] = value;
		$("#step-help").text("Getting Months...");
		$.get("ajax/valid_months", { type: "current", contract: self.options["contract"], commodity: value }, function(exp){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			self.nextStep($("#month"), exp, "Option Month");
		});
		self.currStep = "month";
	},
	
	month: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "month") self.backStep($("#length, #year"), "Option Year");
		self.select(el);
		self.options["month"] = value;
		$("#step-help").text("Getting Years...");
		$.get("ajax/valid_years", { type: "current", contract: self.options["contract"], commodity: self.options["commodity"], month: value }, function(exp){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			self.nextStep($("#year"), exp, "Option Year");
		});
		self.currStep = "year";
	},
	
	year: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "year") self.backStep($("#length"), "Length");
		self.select(el);
		self.options["year"] = value;
		$("#step-help").text("Getting Contract Lengths...");
		$.get("ajax/length", { type: "current", contract: self.options["contract"], commodity: self.options["commodity"], month: self.options["month"], year: value }, function(yrs){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			var data = yrs.replace(",", "|");
			// contract length
			self.nextStep($("#length"), data, "Contract Length");
			self.currStep = "length";
		});
	},
	
	length: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		self.currStep = "length";
		self.select(el);
		self.options["length"] = value;
		self.renderChart();
	},
	
	renderChart: function(){
		var self = this,
			contract = this.options["contract"],
			commodity = this.options["commodity"],
			month = this.options["month"],
			year = this.options["year"],
			contractLength = this.options["length"],
			csvLocation = "/csv/current/" + commodity.replace("+", "").toLowerCase() + "/" + month.toLowerCase() + "/" + year + "/" + contractLength + "yr/",
			price = csvLocation + "price.csv",
			hedged = csvLocation + "hedged.csv",
			contracts = [ "cargill", "kluis", "diversipro", "pacerpro", "promax" ];
		$("#step-help").text("Rendering Chart");
		$.getJSON("ajax/current_chart", { commodity: commodity, month: month, year: year, length: contractLength }, function(info){
			$('input[type="checkbox"]').prop("disabled", false);
			$('input[name="' + contract + '"]').prop("disabled", true);
			for(var index = 0; index < contracts.length; index++){
				if(info[contracts[index]] === "false"){
					$("#" + (index + 1)).prop("disabled", true).prop("checked", false);
					self.gVisibility[index + 1] = false;
					self.hVisibility[index] = false;
				}
			}
			$("#chart-overlay, #step-help-container").remove();
			self.g = new Dygraph(
				document.getElementById("chart"),
				price,
				{
					title: "Contract Results vs Market",
					width: 800,
					height: 400,
					labels: ["Date", "Market Price", "CargillPros", "Kluis Commodities", "DiversiPro", "PacerPro", "ProMax"],
					labelsDiv: document.getElementById("chart-labels"),
					legend: "always",
					drawXGrid: false,
					xlabel: "Date",
					ylabel: "Price",
					pointSize: 5,
					strokeWidth: 3,
					highlightCircleSize: 8,
					gridLineColor: '#333',
					xValueFormatter: function(x){
						var date = new Date(x);
						var label = date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
						return label;
					},
					yAxisLabelFormatter: function(x){
						return self.formatPrice(x);
					},
					yValueFormatter: function(y){
						return self.formatPrice(y);
					},
					yAxisLabelWidth: 80,
					visibility: self.gVisibility,
					colors: [ "#666", "#b60039", "#6999c6", "#cc6633", "#91a54d", "#544d84" ],
					dateWindow: [ Date.parse(info["start"].replace(/\-/g, "/")).valueOf(), Date.parse(info["end"].replace(/\-/g, "/")).valueOf() ]
				}
			);
			self.h = new Dygraph(
				document.getElementById("hedged-chart"),
				hedged,
				{
					title: "Percent Hedged",
					width: 800,
					height: 200,
					labels: ["Date", "CargillPros", "Kluis Commodities", "DiversiPro", "PacerPro", "ProMax"],
					labelsDiv: document.getElementById("hedged-chart-labels"),
					legend: "always",
					drawXGrid: false,
					xlabel: "Date",
					ylabel: "Percent",
					gridLineColor: "#333",
					pointSize: 5,
					strokeWidth: 3,
					highlightCircleSize: 8,
					yAxisLabelFormatter: function(y){
						return self.formatPercent(y);
					},
					yValueFormatter: function(y){
						return self.formatPercent(y);
					},
					yAxisLabelWidth: 80,
					visibility: self.hVisibility,
					colors: ["#b60039", "#6999c6", "#cc6633", "#91a54d", "#544d84"],
					dateWindow: [ Date.parse(info["start"].replace(/\-/g, "/")).valueOf(), Date.parse(info["end"].replace(/\-/g, "/")).valueOf() ]
				}
			);
			self.rendered = true;
		});
	},
	
	hedgedLogin: function(evnt){
		$.ajax({
			type: "POST",
			url: "ajax/hedged_password",
			data: { password: $("#hedged-password").val() },
			success: function(msg){
				if(msg == true){
					$("#hedged-login").hide();
					$("#hedged-chart, #hedged-chart-labels").show();
				}else{
					//console.log("incorrect password!");
				}
			}
		});
	}

};

HistoricalCharts = {

	options: {},
	currStep: "contract",
	g: {},
	gVisibility: [true, false, false, false, false, false],
	finalPrices: {},
	rendered: false,
	chartData: {},
	chartCount: 10,
	currentTab: "tab-1",
	
	init: function(){
		var self = this;
		$("#tab-nav li").click(function(){
			self.currentTab = $(this).data("tab");
			$("#tab-nav li").removeClass("active");
			$(this).addClass("active");
			$(".tab-content").addClass("hidden");
			$("#" + $(this).data("tab")).removeClass("hidden");
			if($(this).data("tab") == "tab-2" && !$.isEmptyObject(self.chartData)){
				self.renderDaysChart();
			}
		});
		$('input[type="checkbox"]').prop("checked", false).prop("disabled", true);
		$('input[name="market"]').prop("checked", true);
		// reset button
		$("#reset").click(function(evnt){
			evnt.preventDefault();
			self.reset();
		});
		// print button
		$("#print").click(function(evnt){
			evnt.preventDefault();
			if(self.rendered === false){
				alert("Please finish the selection process.");
			}else{
				self.printPage();
			}
		});
		// set up Dygraph
		self.newChart();
		$("#chart").append('<div id="chart-overlay"></div>').append('<div id="step-help-container"><div id="step-help"><p>Select <span id="current-step-text">Contract</span> above.</p></div></div>');
	},

	renderDaysChart: function(){
		var self = this;
		// create the chart object
		var chart = new google.visualization.ColumnChart(document.getElementById("market-chart"));
		// draw the chart
		chart.draw(self.chartData, {
			width: 800,
			height: 400,
			chartArea: {
				width: 700
			},
			isStacked: true,
			colors: [ "#E5B22E", "#B6264E" ],
			legend: "none",
			gridlineColor: "#999",
			fontName: "Helvetica",
			hAxis: {
				title: "Price",
				slantedText: false,
				showTextEvery: Math.round(self.chartCount / 10)
			},
			vAxis: {
				title: "Days on Market",
				slantedText: false,
				baselineColor: "#333",
				color: "#222"
			}
		});
		google.visualization.events.addListener(chart, "ready", function(){
			// remove the italics from the chart labels
			if(document["evaluate"]){
				var chartDiv = document.getElementById("market-chart"),
					iframe = chartDiv.firstChild,
					frameDocument = (iframe.contentWindow || iframe.contentDocument).document,
					italicElements = frameDocument.evaluate(".//*[@font-style='italic']", frameDocument, null, 4, null),
					axis1 = italicElements.iterateNext(),
					axis2 = italicElements.iterateNext();
				if(axis1){
					axis1.removeAttribute("font-style");
				}
				if(axis2){
					axis2.removeAttribute("font-style");
				}
			}
		});
	},
	
	newChart: function(){
		var self = this;
		self.g = new Dygraph(
			document.getElementById("chart"),
			[["","","","","","",""],["","","","","","",""]],
			{
				title: "Contract Results vs Market",
				width: 800,
				height: 400,
				labels: ["Date", "Market Price", "CargillPros", "Kluis Commodities", "DiversiPro", "PacerPro", "ProMax"],
				labelsDiv: document.getElementById("chart-labels"),
				legend: "always",
				drawXGrid: false,
				xlabel: "Date",
				ylabel: "Price",
				highlightCircleSize: 0,
				gridLineColor: '#333',
				yAxisLabelWidth: 80,
				visibility: self.gVisibility,
				colors: [ "#666", "#b60039", "#6999c6", "#cc6633", "#91a54d", "#544d84" ]
			}
		);
	},
	
	printPage: function(){
		var self = this;
		// add an id to the chart
		$.each($("canvas"), function(index, el){
			if(index === 0){
				$(el).attr("id", "theGraph");
			}
		});
		
		var graph = document.getElementById("theGraph");
		var graphData = graph.toDataURL("image/png");
		
		$.ajax({
			type: "POST",
			url: "ajax/save_canvas",
			data: {
				type: "historical",
				contract: self.options["contract"],
				otherContracts: self.gVisibility,
				commodity: self.options["commodity"],
				month: self.options["month"],
				year: self.options["year"],
				length: self.options["length"],
				graph: graphData
			},
			dataType: "json",
			success: function(msg){
				var content = document.createElement("div");
				content.id = "print-content";
				content.innerHTML = $(".logo_area").html() + $("#main_content").html();
				var wrapper = document.createElement("div");
				wrapper.appendChild(content);
				
				// html for days on market
				var marketChart = document.getElementById("market-chart");
				marketChart = marketChart.getElementsByTagName("iframe")[0];
				marketChart = marketChart.contentWindow.document.body.innerHTML;
				
				var html = "<html>";
				html += document.getElementsByTagName("head")[0].innerHTML;
				html += wrapper.innerHTML;
				html += '<script src="/js/jquery-1.6.1.min.js"></script>';
				html += '<script>var graphImg = "' + msg.graph + '";var marketChart = \'' + marketChart.replace("'", "\\'").replace(/(\r\n|\n|\r)/gm, "") + '\';</script>';
				html += '<script src="/js/print-historical.js"></script>';
				html += "</html>";
				
				// create print window
				var printWindow = window.open("");
				if(printWindow == null || typeof(printWindow) == 'undefined'){
					alert("Please disable your popup blocker to use this function.");
				}else{
					printWindow.document.write(html);
					printWindow.document.close();
					
					// print the window
					printWindow.focus();
				}
			}
		});
	},
	
	formatPrice: function(int, len){
		if(len === undefined) len = 4;
		var string = int.toString().split(".");
		if(string[1] === undefined){
			string[1] = "";
			for(var i = 0; i < len; i++){
				string[1] = string[1] + "0";
			}
		}else if(string[1].length > len){
			string[1] = string[1].substr(0, len);
		}else if(string[1].length < len){
			var zerosToAdd = len - string[1].length;
			for(i=0;i<zerosToAdd;i++){
				string[1] = string[1] + "0";
			}
		}
		return "$" + string[0] + "." + string[1];
	},
	
	formatPercent: function(y){
		if(y === 1) return "100%";
		y = y.toString().substr(2, 4);
		if(y.length > 2){
			y = y.substr(0, 2);
		}else if(y.length < 2){
			for(var i = 0; 2 - y.length; i++){
				y = y + "0";
			}
		}
		return y + "%";
	},
	
	priceBubble: function(contract){
		var self = this;
		fullContractName = {
			cargill: "CargillPros",
			diversipro: "DiversiPro",
			kluis: "Kluis",
			pacerpro: "PacerPro",
			promax: "ProMax"
		};
		if(self.rendered){
			var price = self.formatPrice(self.finalPrices[contract]);
		}else{
			var price = "";
		}
		$(".final-prices").append('<span class="final-price ' + contract + '-bubble"><p>' + fullContractName[contract] + '<br />Final Price<br /><strong>' + price + '</strong></p></span>');
	},
	
	graphChange: function(el){
		var self = this,
			contract = $(el).attr("name");
		self.gVisibility[el.id] = el.checked;
		if(self.rendered){
			self.g.setVisibility(el.id, el.checked);
			if(el.checked && contract !== "market"){
				$("#" + contract).show();
				self.priceBubble(contract);
			}else if(contract !== "market"){
				$("#" + contract).remove();
			}
		}
	},
	
	select: function(el){
		// check if any siblings have class of selected
		if($(el).siblings("li").hasClass("selected")){
			// remove class
			$(el).siblings("li").removeClass("selected");
		}
		$(el).addClass("selected");
	},
	
	nextStep: function(el, rawExp, text){
		el.parent("div").addClass("active");
		var exp = new RegExp(rawExp);
		el.children("li").each(function(){
			if($(this).data("value").toString().match(exp)){
				$(this).addClass("active");
			}
		});
		$("#current-step-text").text(text);
	},
	
	backStep: function($steps, step){
		var self = this;
		// disable all checkboxes
		$('input[type="checkbox"]').prop("disabled", true).not("#0").prop("checked", false);
		// set visibility to zero
		self.gVisibility = [true, false, false, false, false, false];
		// remove all price bubbles
		$(".final-prices").hide().html("");
		// if not contract back step
		if(step !== "Commodity"){
			// get contract number
			var contractId = $('input[name="' + self.options["contract"] + '"]').attr("id");
			// select contract checkbox
			$("#"+contractId).prop("checked", true);
			// make contract line visible
			self.gVisibility[contractId] = true
			// add price bubble for selected contract
			self.priceBubble(self.options["contract"]);
		}
		// clear the chart if it's rendered
		if(self.rendered){
			// empty the chart
			self.newChart();
			$("#market-chart").html("<p>Please finish selecting options from above.</p>");
			// add the overlay
			$("#chart").append('<div id="chart-overlay"></div>').append('<div id="step-help-container"><div id="step-help"><p>Select <span id="current-step-text">' + step + '</span> above.</p></div></div>');
			self.rendered = false;
		}
		$steps.parent("div").removeClass("active");
		$steps.children("li").removeClass("selected").removeClass("active");
	},
	
	reset: function(){
		var self = this;
		self.backStep($("#length, #year, #month, #commodity, #contract"), "Contract");
		self.nextStep($("#contract"), ".", "Contract");
		self.gVisibility = [true, false, false, false, false, false];
		self.g.updateOptions({
			visibility: self.gVisibility
		});
		$('input[type="checkbox"]').prop("checked", false);
		$('input[name="market"]').prop("checked", true);
	},
	
	contract: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "contract") self.backStep($("#length, #year, #month, #commodity"), "Commodity");
		if(self.options["contract"] !== undefined){
			self.gVisibility = [true, false, false, false, false, false];
			self.g.updateOptions({
				visibility: self.gVisibility
			});
			$(".final-prices").html("");
			$('input[type="checkbox"]').prop("checked", false);
			$('input[name="market"]').prop("checked", true);
		}
		self.select(el);
		self.options["contract"] = value;
		$("#step-help").text("Getting Commodities...");
		$.get("ajax/valid_commodities", { type: "historical", contract: value }, function(exp){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			self.nextStep($("#commodity"), exp, "Commodity");
		});
		self.currStep = "commodity";
		$('input[name="' + value + '"]').prop("checked", true);
		self.gVisibility[$(el).data("id")] = true;
		self.priceBubble(value);
	},
	
	commodity: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "commodity") self.backStep($("#length, #year, #month"), "Option Month");
		self.select(el);
		self.options["commodity"] = value;
		$("#step-help").text("Getting Months...");
		$.get("ajax/valid_months", { type: "historical", contract: self.options["contract"], commodity: value }, function(exp){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			self.nextStep($("#month"), exp, "Option Month");
		});
		self.currStep = "month";
	},
	
	month: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "month") self.backStep($("#length, #year"), "Option Year");
		self.select(el);
		self.options["month"] = value;
		$("#step-help").text("Getting Years...");
		$.get("ajax/valid_years", { type: "historical", contract: self.options["contract"], commodity: self.options["commodity"], month: value }, function(exp){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			self.nextStep($("#year"), exp, "Option Year");
		});
		self.currStep = "year";
	},
	
	year: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		if(self.currStep !== "year") self.backStep($("#length"), "Length");
		self.select(el);
		self.options["year"] = value;
		$("#step-help").text("Getting Contract Lengths...");
		$.get("ajax/length", { type: "historical", contract: self.options["contract"], commodity: self.options["commodity"], month: self.options["month"], year: value }, function(yrs){
			$("#step-help").html('<p>Select <span id="current-step-text"></span> above.</p>');
			var data = yrs.replace(",", "|");
			// contract length
			self.nextStep($("#length"), data, "Contract Length");
			self.currStep = "length";
		});
	},
	
	length: function(el){
		if(!$(el).hasClass("active")) return false;
		var self = this,
			value = $(el).data("value");
		self.currStep = "length";
		self.select(el);
		self.options["length"] = value;
		self.renderChart();
	},
	
	renderChart: function(){
		var self = this,
			contract = this.options["contract"],
			commodity = this.options["commodity"],
			month = this.options["month"],
			year = this.options["year"],
			contractLength = this.options["length"],
			csvLocation = "/csv/historical/" + year + "/" + month.toLowerCase() + "/" + contractLength + "yr/" + commodity.toLowerCase() + ".csv";
		$("#step-help").text("Rendering Chart");
		$.get(csvLocation, function(csv){
			$('input[type="checkbox"]').prop("disabled", false);
			$('input[name="' + contract + '"]').prop("disabled", true);
			var count = {}
				lines = csv.split("\n");
			$.getJSON("ajax/historical_info", { year: year, month: month, commodity: commodity, length: contractLength, contract: contract }, function(info){
				var disable = [];
				// disabled checkboxes if the contract doesn't apply
				if(info.cargill == "false") disable.push(1);
				if(info.kluis == "false") disable.push(2);
				if(info.diversipro == "false") disable.push(3);
				if(info.pacerpro == "false") disable.push(4);
				if(info.promax == "false") disable.push(5);
				$.each(disable, function(index, value){
					$("." + value + "-bubble").prop("disabled", true).prop("checked", false);
					self.gVisibility[value] = false;
				});
				// parse days on market
				$.each(lines, function(num, line){
					if(num !== 0 && line != ""){
						var tmp = line.split(",");
						// keep track of days on market (0.10 increments)
						var marketPrice = tmp[1];
						var round = Math.round(marketPrice * Math.pow(10, 1)) / Math.pow(10, 1);
						if(count[round] === undefined){
							count[round] = 1;
						}else{
							count[round] = count[round] + 1;
						}
					}
				});
				// price bubbles
				self.finalPrices = {
					cargill: roundTo(info.cargill_close, .0025),
					diversipro: roundTo(info.diversipro_close, .0025),
					kluis: roundTo(info.kluis_close, .0025),
					pacerpro: roundTo(info.pacerpro_close, .0025),
					promax: roundTo(info.promax_close, .0025)
				};
				$("." + contract + "-bubble strong").text(self.formatPrice(self.finalPrices[contract]));
				$(".final-prices").show();
				// display the chart
				self.g = new Dygraph(
					document.getElementById("chart"),
					csvLocation,
					{
						title: "Contract Results vs Market",
						width: 800,
						height: 400,
						labels: ["Date", "Market Price", "CargillPros", "Kluis Commodities", "DiversiPro", "PacerPro", "ProMax"],
						labelsDiv: document.getElementById("chart-labels"),
						legend: "always",
						drawXGrid: false,
						xlabel: "Date",
						ylabel: "Price",
						pointSize: 5,
						strokeWidth: 3,
						highlightCircleSize: 0,
						gridLineColor: '#333',
						xValueFormatter: function(x){
							var date = new Date(x);
							var label = date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
							return label;
						},
						yAxisLabelFormatter: function(x){
							return self.formatPrice(x);
						},
						yValueFormatter: function(y){
							return self.formatPrice(y);
						},
						yAxisLabelWidth: 80,
						visibility: self.gVisibility,
						colors: [ "#666", "#b60039", "#6999c6", "#cc6633", "#91a54d", "#544d84" ],
						underlayCallback: function(canvas, area, g){
							var startDate = new Date(info.start_date).getTime();
							var endDate = new Date(info.end_date).getTime();
							var bottomLeft = g.toDomCoords(startDate, 0);
							var topRight = g.toDomCoords(endDate, 0);
							var left = bottomLeft[0];
							var right = topRight[0];
							canvas.fillStyle = "rgba(232, 232, 167, 0.6)";
							canvas.fillRect(left, area.y, right - left, area.h);
						}
					}
				);
				$("#chart-overlay, #step-help-container").remove();
				self.rendered = true;
				// google chart
				var gData = new google.visualization.DataTable();
				self.chartCount = objectCount(count);
				// define the columns
				gData.addColumn("string", "Price");
				gData.addColumn("number", "Days on Market");
				gData.addColumn("number", "Days on Market");
				// how many rows?
				gData.addRows(objectCount(count));
				// add the data
				var index = 0;
				$.each(sortObj(count), function(price, days){
					var x = self.formatPrice(price).split(".");
					var y = x[0] + ".";
					y += x[1].substr(0, 2);
					gData.setValue(index, 0, y);
					if(price == info.final_price){
						gData.setValue(index, 2, days);
					}else{
						gData.setValue(index, 1, days);
					}
					index++;
				});
				self.chartData = gData;
				if(self.currentTab === "tab-2"){
					self.renderDaysChart();
				}
			});
		});
	}

};

