/*
	Function: __toMBit
	value: bit per millisecond
	return: a string like 1.1 or < 1.0 if result is less than 1.0.  
 */
function __toMBit(value){
	var base = 1024;
	value /= base;
	return value > 1.0 ? ''+Math.round(value * 10) / 10 : '< 1.0';
}

function __streamBelowDeck(estimate, estimateStr, recommended, recommendationStr, mbitStr) {
	var result = estimateStr;
	result += " " + __toMBit(estimate) + " " + mbitStr + ".";
	return result +" " + recommendationStr + " " + __toMBit(recommended) + " " + mbitStr + ".";
}

function __streamAboveDeck(estimate, estimateStr, okayStr, mbitStr) {
	var result = estimateStr;
	result += " " + __toMBit(estimate) + " " + mbitStr + ".";
	return result + " " + okayStr;
}

/**
 * Rounds a kbit value to mbit with one decimal.
 */
function _roundToMBit(value) {
	var result = Math.round(value / 100000) / 10;
	if (result > 0) {
		return result;
	}
	return "< 1.0";
}

/**
 * estimatedTime Time in seconds
 * daysStr Localized string for 'days'.
 * dayStr Localized string for 'day'.
 * hoursStr Localized string for 'hours'.
 * hourStr Localized string for 'hour'.
 * minsStr Localized string for 'minutes'.
 * minStr Localized string for 'minute'.
 * secsStr Localized string for 'seconds'.
 * secStr Localized string for 'second'.
 */
function _formatDownloadEstimate(estimatedTime, daysStr, dayStr, hoursStr, hourStr, minsStr, minStr, secsStr, secStr) {
	if(estimatedTime instanceof String){
		estimatedTime = parseInt(estimatedTime);
	}
	var days = Math.floor(estimatedTime / 86400);
	var rest = estimatedTime % 86400;
	var hours = Math.floor(rest / 3600);
	rest = rest % 3600;
	var minutes = Math.floor(rest / 60);
	rest = rest % 60;
	var seconds = rest;
	
	var result = "";
	if (days == 1) {
		result += "" + days + " " + dayStr + " ";
	} else if (days > 1)  {
		result += "" + days + " " + daysStr + " ";
	}
	if (hours == 1) {
		result += "" + hours + " " + hourStr + " ";
	} else if (hours > 1)  {
		result += "" + hours + " " + hoursStr + " ";
	}
	if (minutes == 1) {
		result += "" + minutes + " " + minStr + " ";
	} else if (minutes > 1)  {
		result += "" + minutes + " " + minsStr + " ";
	}
	// if (seconds == 1) {
	// 	result += "" + seconds + " " + secStr + " ";
	// } else if (seconds > 1)  {
	// 	result += "" + seconds + " " + secsStr + " ";
	// }
	return result;
}

/**
 * elementId The HTML id to insert the estimate into.
 * sampleURL The URL to the file that is to be used for download estimate.
 * sampleSize The file size, in bytes, of the file that is to be used for download estimate.
 * duration The duration, in seconds, of the product to be estimated.
 * bitrate The bitrate, in bits, of the product variation type.
 * daysStr Localized string for 'days'.
 * dayStr Localized string for 'day'.
 * hoursStr Localized string for 'hours'.
 * hourStr Localized string for 'hour'.
 * minsStr Localized string for 'minutes'.
 * minStr Localized string for 'minute'.
 * secsStr Localized string for 'seconds'.
 * secStr Localized string for 'second'.
 */
function _estimatedDownloadTime(elementId, sampleURL, sampleSize, duration, bitrate, daysStr, dayStr, hoursStr, hourStr, minsStr, minStr, secsStr, secStr) {
	var _COOKIE_NAME = "throughput=";
	var myCookie = document.cookie;
	var cookieIndex = myCookie.indexOf(_COOKIE_NAME);
	if (cookieIndex < 0) {
		var startTime = new Date().getTime();
		new Request({'method' : 'get',
			'onSuccess' : function(){
				var downloadTime = new Date().getTime() - startTime; // millies
				var throughput = Math.floor(sampleSize/downloadTime); // bits / millies
				var estimatedTime = Math.floor(((bitrate * duration) / throughput)/1000); // total seconds
				var tempDate = new Date();
				tempDate.setTime(tempDate.getTime() + 1000 * 60 * 3);
				document.cookie = _COOKIE_NAME + throughput + (";expires=" + tempDate.toGMTString());
				document.getElementById(elementId).innerHTML = _formatDownloadEstimate(estimatedTime, daysStr, dayStr, hoursStr, hourStr, minsStr, minStr, secsStr, secStr);				
			},
			'onFailure' : function(error){
				document.getElementById(elementId).innerHTML = "Unknown";
				if(window.console){console.error("Failed to load estimate file");}
			}
		}).get(sampleURL);		
	} else {
		var endIndex = myCookie.indexOf(";", cookieIndex);
		var throughput = endIndex < 0 ? myCookie.substring(cookieIndex+_COOKIE_NAME.length, myCookie.length) : myCookie.substring(cookieIndex+_COOKIE_NAME.length, endIndex);
		var estimatedTime = Math.floor(((bitrate * duration) / throughput)/1000);
		document.getElementById(elementId).innerHTML = _formatDownloadEstimate(estimatedTime, daysStr, dayStr, hoursStr, hourStr, minsStr, minStr, secsStr, secStr);
	}
}

function _formatDuration(minutes, hoursStr, hourStr, minsStr, minStr){
	if(minutes instanceof String){
		minutes = parseInt(duration);
	}
	var hours = Math.floor(minutes / 60);
	var timeStr = "";
	if(hours > 0){
		minutes = minutes - hours * 60;
		timeStr += hours;
		timeStr += hours < 2 ? hourStr : hoursStr;
	}
	timeStr += minutes;
	timeStr += minutes == 1 ? minStr : minsStr;	
	return timeStr;
}

function _estimateDurationBasedDownloadTime(duration, elementId, sampleURL, hoursStr, hourStr, minsStr, minStr, dlElement){
	var _COOKIE_NAME = "dwnloadest=";
	var myCookie = document.cookie;
	var ind = myCookie.indexOf(_COOKIE_NAME);
	if(ind < 0){
		var startTime = new Date().getTime();
		new Request({'method' : 'get',
			'url' : sampleURL,
			'onSuccess' : function(){
				eta = (new Date().getTime() - startTime) * ((1541108462 / 512000 / 20) * 21);
				var minutes = Math.floor(eta / 60 / 1000);
				var tempDate = new Date();
				tempDate.setTime(tempDate.getTime() + 1000 * 60 * 3);
				document.cookie = _COOKIE_NAME + minutes + (";expires=" + tempDate.toGMTString());
				new Element('dd', {'html' : _formatDuration(minutes, hoursStr, hourStr, minsStr, minStr)}).inject(dlElement, 'after');				
			},
			'onFailure' : function(){
				alert(error);
				document.getElementById(elementId).innerHTML = "Unknown";				
			}
		}).get();
	}else{
		var ind2 = myCookie.indexOf(";", ind);
		var myValue = ind2 < 0 ? myCookie.substring(ind+_COOKIE_NAME.length, myCookie.length) : myCookie.substring(ind+_COOKIE_NAME.length, ind2);
		new Element('dd', {'html' : _formatDuration(myValue, hoursStr, hourStr, minsStr, minStr)}).inject(dlElement, 'after');
	}
}
function setup(){
 	var sampleURL = $('pf-downloadest-url');
 	if(!$defined(sampleURL)){return;}
 	sampleURL = sampleURL.get('href'); 
	var chain = new Chain();
	var idCounter = 1;
	var fillInStreamEstimate = function(bandwidth){
		document.getElementById(elementId).innerHTML = _formatDownloadEstimate(estimatedTime, daysStr, dayStr, hoursStr, hourStr, minsStr, minStr, secsStr, secStr);
	};
	var onOfferingLoaded = function(offering, element){
		var elementId = '_pf-download-est-'+(idCounter++);
		new Element('dt', {'html' : offering.trafficEstimateLabel, 'id' : elementId}).inject(element, 'top');
		var size = 691755 * 8;
		if($defined(offering.hourString)){// download
			chain.chain(function(duration){
				var speed = size / duration;
				var eta = (Math.round(1541108462 / speed * 8 / 1000 / 60));			
				new Element('dd', {'html' : _formatDuration(eta, offering.hoursString, offering.hourString,
					offering.minutesString, offering.minuteString)}).inject($(elementId), 'after');
				return true;		
			});			
		}else{
			chain.chain(function(duration){// stream
				var deck = offering.bitrate / 1000;// bitrate required per milli
				var speed = size / duration; // bits loaded per milli						
				var userString = speed > deck ?
					__streamAboveDeck(speed, offering.streamEstimateLabel, offering.streamSuccessLabel, offering.streamMbitLabel): 
					__streamBelowDeck(speed, offering.streamEstimateLabel, deck, offering.streamRecommendationLabel, offering.streamMbitLabel);					 				
				var ev = new Element('dd', {'html' : userString}).inject($(elementId), 'after');
				return true;
			});
		}		
	};
	var onOfferingsLoaded = function(){		
		var cookie = Cookie.read('dwnloadest');
		if(cookie){			
			while(chain.callChain(parseInt(cookie)));
		}else{
			var startTime = new Date().getTime();
			new Request({'method' : 'get', 'url' : sampleURL,
				'onSuccess' : function(){
					var time = new Date().getTime() - startTime;
					Cookie.write('dwnloadest', time, {'duration': 1.0 / 24.0 / 2.0});
					while(chain.callChain(time));				
				},
				'onFailure' : function(){
					alert(error);
					document.getElementById(elementId).innerHTML = "Unknown";				
				}
			}).send();
		}
	};
	PFPortal.app.addEvent('offeringLoaded', onOfferingLoaded);
	PFPortal.app.addEvent('offeringsLoaded', onOfferingsLoaded);
}setup();