
var graph_data = new Array();
var graph_colors = new Array();

function initializeFields() {

	numrows = 1;

	var fieldset = Array(
		'price_point_1',
		'gross_margin_1',
		'product_views_1',
		'current_conversion_1',
		'conversion_lift_1',
		'video_cost_1'
	);

	for (var this_field in fieldset) {
		document.getElementById(fieldset[this_field]).onkeyup = calculateROI;
	}

	document.getElementById('conversion_lift_presets').onchange = conversionLiftPresets;
	document.getElementById('average_conversion_presets').onchange = averageConversionPresets;
	document.getElementById('average_margin_presets').onchange = averageMarginPresets;
	document.getElementById('video_cost_presets').onchange = videoCostPresets;

	document.getElementById('product_name_1').focus();

}


function calculateROI() {

	// Clean non-alpha characters

	if (typeof(this.value) != 'undefined') {
		
		var id = this.id;
		id_tokens = id.split('_');
		base_field_name = id_tokens[0] + '_' + id_tokens[1];

		if (base_field_name != 'product_name') {
			this.value = this.value.replace(/[^0-9.]/g, ''); 
		}
	}

	var new_graph_data = new Array();
	var new_graph_colors = new Array();

	for (i = 1; i <= numrows; i++) {
	
		var product_name_field = 'product_name_' + i;
		var price_point_field = 'price_point_' + i;
		var gross_margin_field = 'gross_margin_' + i;
		var product_views_field = 'product_views_' + i;
		var current_conversion_field = 'current_conversion_' + i;
		var current_profit_field = 'current_profit_' + i;
		var conversion_lift_field = 'conversion_lift_' + i;
		var video_cost_field = 'video_cost_' + i;
		var new_profit_field = 'new_profit_' + i;
		var break_even_field = 'break_even_' + i;
		var min_inventory_field = 'min_inventory_' + i;

		var price_point = document.getElementById(price_point_field).value;
		var gross_margin = document.getElementById(gross_margin_field).value;
		var product_views = document.getElementById(product_views_field).value;
		var current_conversion = document.getElementById(current_conversion_field).value;

		if (
			price_point != '' &&
			gross_margin != '' &&
			product_views != '' &&
			current_conversion != '' 
		   ) {

			var profit_per_item = (gross_margin * price_point) / 100;
			var items_sold = (product_views * current_conversion) / 100;
			var current_profit = profit_per_item * items_sold;
			
			document.getElementById(current_profit_field).value = parseInt(current_profit);

		} else {
	
			document.getElementById(current_profit_field).value = '';
		}

		if (document.getElementById(current_profit_field).value != '') {


			var conversion_lift = document.getElementById(conversion_lift_field).value;

			if (conversion_lift != '')  {

				var conversion_increase = (current_conversion * conversion_lift) / 100;
				var new_conversion = parseFloat(current_conversion) + conversion_increase;

				var new_items_sold = (product_views * new_conversion) / 100;
				var new_profit = profit_per_item * new_items_sold;

				document.getElementById(new_profit_field).value = parseInt(new_profit);
			}
		}

		if ((document.getElementById(video_cost_field).value != '') && (document.getElementById(new_profit_field).value != '')) {

			var video_cost = document.getElementById(video_cost_field).value;

			var items_sold_lift = new_items_sold - items_sold;
			var additional_gross_revenue = items_sold_lift * profit_per_item;

			var break_even = video_cost / additional_gross_revenue;

			break_even = Math.round(break_even*100) / 100;

			document.getElementById(break_even_field).value = break_even;

			var min_inventory = (video_cost / profit_per_item);

			document.getElementById(min_inventory_field).value = Math.ceil(min_inventory);
			
		}

		if ((document.getElementById(current_profit_field).value != '') && (document.getElementById(new_profit_field).value != '')) {

			if (document.getElementById(product_name_field).value != '') {
				var product_name = document.getElementById(product_name_field).value;
			} else {
				var product_name = '*';
			}

			this_array_key = new_graph_data.length;
			this_array_key2 = new_graph_data.length + 1;

			if (this_array_key < 9) {

			new_graph_data[this_array_key] = [product_name, current_profit];
			new_graph_data[this_array_key2] = [product_name, new_profit];

			new_graph_colors[this_array_key] = '#888888';
			new_graph_colors[this_array_key2] = '#41CC00';

			}
		}
	}

	if (new_graph_data.length > 0) {

		ua = navigator.userAgent.toLowerCase();
		ie  = (ua.indexOf("msie") && document.all && ua.indexOf("netscape") == -1);

		if (typeof(ie) == 'undefined') {

			drawGraph(new_graph_data,new_graph_colors);
		}
	}
	
}

function drawGraph(this_graph_data,this_graph_colors) {

        if (areArraysEqual(graph_data,this_graph_data)) {

                // Do nothing

        } else {

                graph_data = this_graph_data;
		graph_colors = this_graph_colors;

		var graph_size = graph_data.length * 108; 

		if (typeof(myChart) == 'undefined') {
                	myChart = new JSChart('graph', 'bar');
	                myChart.setDataArray(graph_data);
			myChart.colorizeBars(graph_colors);
			myChart.setTitle('Video Revenue Lift');
 			myChart.setTitleColor('#8E8E8E');
 			myChart.setAxisNameX('');
 			myChart.setAxisNameY('');
 			myChart.setAxisColor('#C4C4C4');
			myChart.setAxisNameFontSize(16);
 			myChart.setAxisNameColor('#999');
			myChart.setAxisValuesColor('#7E7E7E');
 			myChart.setBarValuesColor('#7E7E7E');
 			myChart.setAxisPaddingTop(60);
			myChart.setAxisPaddingRight(40);
 			myChart.setAxisPaddingLeft(40);
			myChart.setAxisPaddingBottom(40);
 			myChart.setTextPaddingLeft(105);
 			myChart.setTitleFontSize(11);
 			myChart.setBarBorderWidth(1);
			myChart.setBarBorderColor('#C4C4C4');
 			myChart.setBarSpacingRatio(30);
			myChart.setGrid(false);
 			myChart.setSize(graph_size, 321);
			//myChart.setBackgroundImage('chart_bg.jpg');
		}

                myChart.setDataArray(graph_data);
                myChart.colorizeBars(graph_colors);
                myChart.setSize(graph_size, 321);

                myChart.draw();
        }
}

function areArraysEqual(array1,array2) {

   var temp = new Array();

   if (array1.length != array2.length) {
      return false;
   }

   for (var i=0; i<array1.length; i++) {
   
	key = (typeof array1[i]) + "~" + array1[i];
	
	if (temp[key]) { temp[key]++; } else { temp[key] = 1; }
   }

   for (var i=0; i<array2.length; i++) {
   
      key = (typeof array2[i]) + "~" + array2[i];
      
      if (temp[key]) {
      
         if (temp[key] == 0) { return false; } else { temp[key]--; }
         
      } else { 
         return false;
      }
   }

   return true;
}


function conversionLiftPresets() {

	new_conversion_value = this.options[this.selectedIndex].value;
	
	for (i = 1; i <= numrows; i++) {

		var this_conversion_field = 'conversion_lift_' + i;
		document.getElementById(this_conversion_field).value = new_conversion_value; 
	}

	calculateROI();
}

function averageConversionPresets() {

        new_conversion_value = this.options[this.selectedIndex].value;

        for (i = 1; i <= numrows; i++) {

                var this_conversion_field = 'current_conversion_' + i;
                document.getElementById(this_conversion_field).value = new_conversion_value;
        }

        calculateROI();
}

function averageMarginPresets() {

        new_margin_value = this.options[this.selectedIndex].value;

        for (i = 1; i <= numrows; i++) {

                var this_margin_field = 'gross_margin_' + i;
                document.getElementById(this_margin_field).value = new_margin_value;
        }

        calculateROI();
}

function videoCostPresets() {

        new_video_value = this.options[this.selectedIndex].value;

        for (i = 1; i <= numrows; i++) {

                var this_video_field = 'video_cost_' + i;
                document.getElementById(this_video_field).value = new_video_value;
        }

        calculateROI();
}



function addRow(rows_to_add) {

	new_fields = Array(
                Array('product_name','field_input','25',''),
                Array('price_point','field_input','5','$'),
                Array('gross_margin','field_input','2','%'),
                Array('product_views','field_input','8','/month'),
                Array('current_conversion','field_input','2','%'),
                Array('current_profit','calculated_input','7','$'),
                Array('conversion_lift','field_input','2','%'),
                Array('new_profit','calculated_input','7','$'),
                Array('video_cost','field_input','5','$'),
                Array('break_even','calculated_input','2',' months'),
                Array('min_inventory','calculated_input','2','')
	);

	var newrow_num = numrows + 1;

	var this_table =  document.getElementById('field_table');
  	var last_row = this_table.rows.length;
  	var this_new_row = this_table.insertRow(last_row);

	for (i = 0; i < new_fields.length; i++) {

		var field_name = new_fields[i][0];
		var field_class = new_fields[i][1];
		var field_size = new_fields[i][2];
		var field_text = new_fields[i][3];

		var this_field_cell = this_new_row.insertCell(i);

 		this_field_cell.setAttribute("class",field_class);
 		this_field_cell.setAttribute("className",field_class);

		if (field_text == '$') {
 			this_field_cell.innerHTML = field_text;
		}

		var this_input_field = document.createElement("input");
 		this_input_field.id = field_name + '_' + newrow_num;
 		this_input_field.type = "text";
 		this_input_field.size = field_size;

		this_field_cell.appendChild(this_input_field);

		if (field_text != '$') {
			this_field_cell.innerHTML = (this_field_cell.innerHTML + field_text);
		}

		field_name = this_input_field.id;
		document.getElementById(field_name).onkeyup = calculateROI;

	}

	numrows++;

	if (typeof(rows_to_add) != 'undefined') {
		if (rows_to_add > 1) {
			rows_to_add = (rows_to_add - 1);
			addRow(rows_to_add);
		}
	}
}

function addMultipleRows() {

	select_menu = document.getElementById('multiple_rows');
	num_rows_to_add = select_menu.options[select_menu.selectedIndex].value;
	
	addRow(num_rows_to_add);
}

function addSampleData() {

	sample_data = new Array();
	sample_data[0] = Array('XLT Handbag','120','35','1000','2.5','20','200');
	sample_data[1] = Array('Pro Series Watch','60','43','1250','2.8','30','250');
	sample_data[2] = Array('Hi-Tek Sneakers','50','27','3000','3','30','150');
	sample_data[3] = Array('Chair Massager','350','20','2358','1.7','45','600');
	sample_data[4] = Array('Diamond Earrings','700','60','800','2.1','30','120');

	if (numrows < 5) {

		addRow(sample_data.length - 1);
	}

	for (i = 0; i < sample_data.length; i++) {
		
		field_num = i + 1;

                var product_name_field = 'product_name_' + field_num;
                var price_point_field = 'price_point_' + field_num;
                var gross_margin_field = 'gross_margin_' + field_num;
                var product_views_field = 'product_views_' + field_num;
                var current_conversion_field = 'current_conversion_' + field_num;
                var conversion_lift_field = 'conversion_lift_' + field_num;
                var video_cost_field = 'video_cost_' + field_num;

		document.getElementById(product_name_field).value =  sample_data[i][0];
		document.getElementById(price_point_field).value =  sample_data[i][1];
		document.getElementById(gross_margin_field).value =  sample_data[i][2];
		document.getElementById(product_views_field).value =  sample_data[i][3];
		document.getElementById(current_conversion_field).value =  sample_data[i][4];
		document.getElementById(conversion_lift_field).value =  sample_data[i][5];
		document.getElementById(video_cost_field).value =  sample_data[i][6];
	}

	calculateROI();
}



