// JavaScript Document

var total_impressions = 0;
var total_spend = 0;
var total_availability = 0;

function update_ratecard_desired_spend_total () {
	var desired_spend_total = 0;
	var all_inputs= document.getElementsByTagName("input");

	for (i=0; i<all_inputs.length; i++){
		if (all_inputs[i].className== 'desired_spend' && all_inputs[i].value) {
			alert(all_inputs[i].value);
			desired_spend_total = desired_spend_total + all_inputs[i].value;
			alert(desired_spend_total);
		}
	}

	document.getElementById('desired_spend_total').innerHTML = desired_spend_total;
}


// calculates the total spend on the product page
function calculate_total_spend_value() {
	var impressions = document.getElementById('total_estimated_spend_dropdown').value;
	var ratecard = document.getElementById('ratecard_banner_cpm').value;
	var total_spend = ( impressions / 1000 ) * ratecard;
	if (total_spend.toFixed) { // checks to see if browser supports toFixed
		total_spend = total_spend.toFixed(2); //returns the number formated with two decimal points as is standard with currencies
	}
	total_spend = addCommas(total_spend); // turns number into a string, with the proper commas for formating.
	document.getElementById('total_estimated_spend_value').innerHTML = total_spend;
}


function calculate_impressions(zone_id) {
	var result = 0;
	var offer = 'offer_' + zone_id;
	var spend = 'spend_' + zone_id;
	var impressions = 'impressions_' + zone_id;
	
	offer = document.getElementById(offer);
	spend = document.getElementById(spend);
	impressions = document.getElementById(impressions);
   if ( !spend.value || !offer.value || offer.value == 0) {
		impressions.innerHTML = 0;
	} else { 
      spend_value = spend.value;
      offer_value = offer.value;
      spend_value = spend_value. replace(/,/, '');
      offer_value = offer_value. replace(/,/, '');	
		result = Math.round( (parseFloat(spend_value) / parseFloat(offer_value)) * 1000 );
		if (isNaN(result)) {
         impressions.innerHTML = 'Invalid';
      } else {
         impressions.innerHTML =  addCommas( result );
		}
	}
}

function update_impressions_calculation (array_of_zones) {
	for (i=0; i<array_of_zones.length; i++) {
			calculate_impressions(array_of_zones[i]);
	}
}
