var menu_obj = null;

function checkHover() {
   if (menu_obj) { menu_obj.find('ul').fadeOut('fast'); } 
}


function doMarkings(axes){
	var marks = [];
	var yticks = axes.yaxis.ticks;
	for(var i = 0; i < yticks.length; i++){
		var tick = yticks[i];
		marks.push({ yaxis: { from: tick.v, to: tick.v }, color: "#ddd"});		
	}
	marks.push({ xaxis: { from: 0, to: 0 }, color: "#ddd"});
	return marks;
}

function doTopQuartileMarkings(axes){
	var marks = doMarkings(axes);
	return marks;
}

function numberToCurrency(number) {
  currency = ""
  var parts = number.toString().split('.')
  var pattern = new RegExp(/(\-?)(\d+)(?=(\d\d\d)+(?!\d))/)
  var match = pattern.exec(parts[0])
  if(match){
    currency += match[1] + match[2] + currency_format.delimiter + match[3]
  } else {
    currency += parts[0]
  }
  if (parts[1]) {
    currency += currency_format.separator + parts[1]
  } else { 
    currency += currency_format.separator + 0 
  }
  return currency_format.format.replace(/%n/g, currency).replace(/%u/g, currency_format.unit);
}

function setMenuHover() {
  $('#navigation div.menu_heading').hover(function() {
      if (menu_obj) {
         menu_obj.find('ul').fadeOut('fast');
         menu_obj = null;
      }
      $(this).find('ul').fadeIn('fast');
   }, function() {
      menu_obj = $(this);
      setTimeout('checkHover()', 200);
   });
}

function createButtons() {
	$('a.button').append('<div class="button-left"></div>');
	$('a.button').append('<div class="button-right"></div>');
}


var target = {
    data: {},
    load: function () {
        var the_cookie = $.cookie('target');
        if (the_cookie) {
            this.data = $.evalJSON(the_cookie);
        }
        return this.data;
    },

    save: function (expires, path) {
        var d = expires || new Date(2020, 02, 02);
        var p = path || '/';
        $.cookie('target', $.toJSON(this.data));
	},

	remove: function (){
		$.cookie('target', null);
		this.data = {};
	}
}

/* Add all setup tasks that should be invoked
   after the page has loaded here */
$(document).ready(function() {
   setMenuHover();
   createButtons();
   	$('#language').clickMenu({arrowSrc:''});
});

$.fn.observe = function( time, callback ){
  return this.each(function(){
     var form = this, change = false;

     $(form.elements).keydown(function(){
         change = true;
     });

     setInterval(function(){
         if ( change ) callback.call( form );
         change = false;
     }, time * 1000);
  });
};

function addPlusIfPositive(num) {
  if (num > 0) {
    return '+' + num;
  } else {
    return num;
  }
}
var tqi_inv = 0;
// GRAPHING STUFF
var ci_ar = 0;
var ci_inv = 0;
var ci_ap = 0;

function rdiff(n1, n2){
  return addPlusIfPositive((Math.round(n1) - Math.round(n2))*-1);
}

function update_table_values(){
	$("#adj_ar_days").text(Math.round(co.ar_days));
	var diff_ar_days = (orig_co.ar_days - co.ar_days)*-1
	$("#diff_ar_days").text(rdiff(orig_co.ar_days, co.ar_days));
	$("#adj_ap_days").text(Math.round(co.ap_days));
	var diff_ap_days = (orig_co.ap_days - co.ap_days)*-1
	$("#diff_ap_days").text(rdiff(orig_co.ap_days, co.ap_days));
	$("#adj_inv_days").text(Math.round(co.inv_days));
	var diff_inv_days = (orig_co.inv_days - co.inv_days)*-1
	$("#diff_inv_days").text(rdiff(orig_co.inv_days, co.inv_days));
	// Cash increase calculations
    ci_ar =  diff_ar_days  * -1 * (co.revenue / 365.0); 
    ci_ap =  diff_ap_days  * (co.cogs / 365.0);
    ci_inv = diff_inv_days * -1 * (co.cogs / 365.0);
	
	$("#ci_ar").text(numberToCurrency(ci_ar.toFixed(1)));
	$("#ci_inv").text(numberToCurrency(ci_inv.toFixed(1)));
	$("#ci_ap").text(numberToCurrency(ci_ap.toFixed(1)));

	var total = (ci_ar + ci_inv + ci_ap).toFixed(1);
	$("#ci_total").text(numberToCurrency((ci_ar + ci_inv + ci_ap).toFixed(1)));
    $("#ci_total").append('<span class="millions">'+currency_format["magnitude"]+'</span>');

	if ($('#improvement-number').css('visibility', 'hidden')) {
		$('#improvement-number').css('visibility', 'visible');
		$('.hidden-colon').css('visibility', 'visible');
	}

	$("#improvement-number").text(numberToCurrency(total));
    $("#improvement-number").append('<span class="millions">'+currency_format["magnitude"]+'</span>');
}

function change_graph(e, ui){
	// update table values
	update_table_values();
    // tqi_ar = (co.cash - co.ar  + orig_co.ar);
    // tqi_ap = (tqi_ar + co.ap  - orig_co.ap);
    // tqi_inv = (tqi_ap - co.inv + orig_co.inv);
    tqi_ar = co.cash + new Number(ci_ar.toFixed(1));
    tqi_ap = tqi_ar + new Number(ci_ap.toFixed(1));
    tqi_inv = tqi_ap + new Number(ci_inv.toFixed(1));
	if((tqi_inv) < 0){
		$('#negative-cash').show();
	}else{
		$('#negative-cash').hide();
	}
    // FOR DEBUGGING
    // $("#negative-cash").show();
    // $("#negative-cash").html(
    //                          "co.cash:"+co.cash
    //                          +"<br>co.ar:"+co.ar +" co.ar_days:"+co.ar_days
    //                          +"<br>co.ap:"+co.ap +" co.ap_days:"+co.ap_days
    //                          +"<br>co.inv:"+co.inv +" co.inv_days:"+co.inv_days
    //                          +"<br>orig_co.ar:"+orig_co.ar
    //                          +"<br>orig_co.ap:"+orig_co.ap
    //                          +"<br>orig_co.inv:"+orig_co.inv     
    //                          +"<br>tqi_ar:"+tqi_ar
    //                          +"<br>tqi_ap:"+tqi_ap
    //                          +"<br>tqi_inv:"+tqi_inv
    //                          )
	
	value_data.data = [[0, co.cash], 
	                   [1, tqi_ar],  	
					   [2, tqi_ap],          
                       [3, tqi_inv], 
	                   [4, tqi_inv]];
	plot.setData([placeholder, value_data, cash_data]);	
	plot.setupGrid();
	plot.draw();
	
	styleYaxisTicks();
}

function x2Ticks(axis) {
  var t = [[0.25, numberToCurrency(orig_co.cash.toFixed(1))], 
	[1.25, $("#ci_ar").text()],
	[2.25, $("#ci_ap").text()],
	[3.25, $("#ci_inv").text()],
	[4.25, numberToCurrency(tqi_inv.toFixed(1))]];
  return t;
}


function styleYaxisTicks() {
	/* This is a little trick to put in dollars and commas in the y-axis ticks.
	   It was originally in the document.ready section of the top_quartile_improvement
	 	 page, but needs to be here instead because the chart redraws after every
	   slider move. */
	$('.tickLabel').each( function(){
 		if (parseInt(this.innerHTML)) {
			// If test removed by Gregg to fix problem w/U.S. currency
			// not being converted (March 17, 2009)
 		    //if(!this.innerHTML.match(currency_format.unit)){ 
                this.innerHTML = numberToCurrency(this.innerHTML)
            //}
			if (navigator.userAgent.indexOf('MSIE 7') >= 0) {
				$(this).css('right', ((parseInt(this.style.right) || 0) + 33) + "px");
			}
			else if (navigator.userAgent.indexOf('MSIE') >= 0) {
	       		this.style.right = ((parseInt(this.style.right) || 0) + 4) + "px";
			} 
		else {
			this.style.right = ((parseInt(this.style.right) || 0) + 32) + "px";
		}
 	}
 	})
}

function update_slider_value(e, ui){
    value = ($("#"+this.id).slider("value")/factor)

	change = false;
	if(this.id == "slider_ar_days"){
		co.ar_days = value;
		update_company_ar();
	}else if(this.id == "slider_ap_days"){
		co.ap_days = value;
		update_company_ap();
	}else if(this.id == "slider_inv_days"){
		co.inv_days = value;
		update_company_inv();
	}
	update_company_form();
	change_graph(e,ui);

	$("#"+this.id+"_value").text(Math.round(value));
};

function update_company(){
	update_company_ar();
	update_company_inv();
	update_company_ap();
}

function update_company_ar(){
	co.ar =  (((co.ar_days  * co.revenue) / 365.0));
}

function update_company_inv(){
	co.inv = (((co.inv_days * co.cogs )   / 365.0));	
}		

function update_company_ap(){
	co.ap =  (((co.ap_days  * co.cogs)    / 365.0));
}

function update_company_form(){
	$("#company_cogs").val(co.cogs);
	$("#company_ar").val(co.ar);
	$("#company_ap").val(co.ap);
	$("#company_inv").val(co.inv);
	$("#company_cash").val(co.cash);
	$("#company_revenue").val(co.revenue);
	$("#company_ar_days").val(co.ar_days);
	$("#company_ap_days").val(co.ap_days);
	$("#company_inv_days").val(co.inv_days);
	target.data = {ar_days: co.ar_days, ap_days: co.ap_days, inv_days: co.inv_days};
	target.save();
}

function mouseOverOnBarFunction (c, e, pos, ev ) { 
    try{
		if (pos){
			selectedItem = pos.datapoint ? pos.datapoint[2] : null;	
			if (selectedItem){
				infoText  = '<span style="white-space: nowrap;"><b>' + numberToCurrency(selectedItem.val.toFixed(places)) + ' </b>'+currency_format["magnitude"]+'<br/>';
				if(selectedItem.days){
					infoText += selectedItem.days.toFixed(places) +" days<br/>";
				}
				infoText += '</span>';
				showTooltip(e.pageX, e.pageY,infoText);
			}
		}else{
			$("div#tooltip").hide(200);
		}
	}catch(e){
		console.log(e);
	}
}

function showTooltip(x, y, contents) {
  var tooltip = jQuery('div#tooltip').length > 0 ? jQuery('div#tooltip').html(contents) : jQuery('<div id="tooltip">' + contents + '</div>').appendTo("body");
 
  var padding = 10, 
      left = x + padding, 
      top = y + padding;
  if (left >= window.innerWidth - tooltip.width() - padding*2) //check whether it overlaps right side of browser
      left = left - tooltip.width() - padding*4;
  tooltip.css( {
      position: 'absolute',
      top: top,
      left: left,
      'z-index': 100,
      'background-color': '#fee',
         opacity: 0.80
  }).show();
}

function place_on_slider(value, min, max, actual_size) { 
  return ((value - min) / max) * (actual_size - 3);
};


function goToCustomPeerGroup() {
	$('form#company_input').attr('action', '/industries/custom_peer_group')
	$('form#company_input')[0].submit()
}
