// The ids used for the icebox div
var _divId = "icebox";

// show the browse image for an item in the icebox
var _showImage = false;

// icebox contains items
var _hasScenes = false;

var _mapFormId = "mapForm";
var _modeFormId = "modeForm";
var _resolutionFormId = "resolutionForm";

// scoping issues require the setters and getters (for now)
var iceboxJSON;
function setIceboxJSON(_json) {
	iceboxJSON = _json;
	return iceboxJSON;
}
function getIceboxJSON() {
	return iceboxJSON;
}

var fades = new Array("ff","ee","dd", "cc","bb","aa","99");
var fadeInterval = 200;
function fadeAndHide(divId) {
	fadeBackground(divId, fades.length - 1);
	setTimeout("get_element('"+divId+"').innerHTML = ''", fadeInterval * (fades.length));
}
function fadeBackground(divId, colorIx) {
	if (colorIx >= 0) {
		get_element(divId).style.backgroundColor = "#ffff" + fades[colorIx];
        if (colorIx === 0) {
            get_element(divId).style.backgroundColor = "transparent";
		}
        colorIx--;
        setTimeout("fadeBackground('"+divId+"',"+colorIx+")", fadeInterval);
	}
}

/*
	Override this method in the calling page for
	page-specific rendering. This method is called by
	all other methods below that modify the ICE tray.
*/
function loadPage() {
}

function listFileSizes() {
	var widthDegrees = 360;
	var heightDegrees = 180;
	// does the box contain a boundingBox?
	if (iceboxJSON.boundingBox !== undefined) {
		// determine the dimensions of the boundingBox
		widthDegrees = (iceboxJSON.boundingBox.lrlon+180.0) - (iceboxJSON.boundingBox.ullon+180.0);
		heightDegrees = (90.0-iceboxJSON.boundingBox.lrlat) - (90.0-iceboxJSON.boundingBox.ullat);
	}

	var list = '<table border="1" cellpadding="2" cellspacing="0" align="center"><tr>';
	var ct = 0;
	var maxOutputRes;
	var resetOutputRes = false;
	for (var i = 0; i < resolutions.length; i++) {
		if (iceboxJSON.commonRes <= resolutions[i].value) {
			ct++;
			var width = Math.ceil(widthDegrees / resolutions[i].value);
			var height = Math.ceil(heightDegrees / resolutions[i].value);
			
			// images that are smaller than 360 pixels might be too small,
			// so don't show those options unless it is the highest resolution
			// (i.e., the first one that will be shown)
			if ( width > 360 || height > 360 || ct == 1 ) {
				list += '<td width="100" align="center"><input type="radio" name="resolution" onclick="setOutputResolution('+resolutions[i].value+')" value="'+resolutions[i].value+'" class="radio" />'+resolutions[i].value+' degrees';
				list += '<br/>'+width+'x'+height;
				// an approximation of file sizes
				list += '<br/>'+FormatFileSize(((width * height)/4) * iceboxJSON.ICETray.length)+'</td>';
				
				if (ct == 1) { maxOutputRes = resolutions[i].value; }
			
			// if the resolution being skipped is the currently selected output resolution
			// then reset the output res to the highest available
			} else if (resolutions[i].value == iceboxJSON.outputRes) {
				resetOutputRes = true;
			}
		}
	}
	list += "</tr></table>";
	get_element("ice_resolutions").innerHTML = list;
	
	var checkedRes = iceboxJSON.outputRes;
	if (resetOutputRes) {
		setOutputResolution(maxOutputRes);
		checkedRes = maxOutputRes;
	}
	
	var form = get_form(_resolutionFormId);
	if(!form) {	return false; }
	setRadioCheckedValue(form.elements['resolution'], checkedRes);
}

/*
	AJAX methods for retrieving and manipulating contents of ICEBox
*/
function listIcebox(showImage) {
	if (showImage !== undefined) {
		_showImage = showImage;
	}

	var div = get_element(_divId);
	var iceTray = iceboxJSON.ICETray;
	var newHTML = "";
	if (iceTray.length > 0) {
		_hasScenes = true;
		newHTML += "<ul>";
		for (var i = 0; i < iceTray.length; i++) {
			newHTML += "<li class=\"iceitem\">"+ iceTray[i].name ;
			if (_showImage) {
				newHTML += '<br/><img src="/RenderData?si='+iceTray[i].sceneImageId+'&cs=rgb&widthFit=180&heightFit=180&format=PNG"/><br/>';
			}
			newHTML += "<div style=\"text-align: right;\" ><a onclick=\"removeSceneImage("+ iceTray[i].sceneImageId + ");\" class=\"fakeref iceremove\">remove</a></div>";
			newHTML += "</li>";
		}
		newHTML += "</ul>";
	} else {
		_hasScenes = false;
		newHTML = "<p><em>You must select one to three images before you can perform any analysis.</p><p>Look for 'Analyze this image' and click on that link to add to your analysis queue.</em></p>";
	}
	div.innerHTML = newHTML;
}

var listIceboxCallback = function(o) {
	if(o.responseText !== undefined) {
		setIceboxJSON( eval( '(' + o.responseText + ')' ) );
		loadPage();
	}
};

// Callback for displaying error message as a result of AJAX request.
// This is not where messages from the app side are displayed.
var listIceboxError = function(o) {
	if(o.responseText !== undefined){
		var div = get_element(_divId);
		div.innerHTML = "There was an error in retrieving the analysis list: " + o.statusText;
	}
};

var iceboxCallback = {
	success:listIceboxCallback,
	failure:listIceboxError
};

var processMessages = function(o) {
	if(o.responseText !== undefined){
		var div = get_element(o.argument.divId);
		setIceboxJSON( eval( '(' + o.responseText + ')' ) );
		if (iceboxJSON.SuccessMessage !== undefined) {
			div.innerHTML = "<span class=\"message\">"+iceboxJSON.SuccessMessage+"</span>";
			fadeAndHide(o.argument.divId);
		} else if (iceboxJSON.ErrorMessage !== undefined) {
			div.innerHTML = "<span class=\"error_message\">"+iceboxJSON.ErrorMessage+"</span>";
		} else {
			// clear any content that may have been there
			div.innerHTML = "";
		}
	}
};

var showErrorMessage = function(o) {
	if(o.responseText !== undefined){
		var div = get_element(o.argument.divId);
		div.innerHTML = "<span class=\"error_message\">"+o.argument.errorMessage+"</span>";
	}
};

function setIceMode(modeStr) {
	if (modeStr === undefined) {
		return false;
	}
	YAHOO.util.Connect.asyncRequest('GET', "/j/ICETray.html?mode="+modeStr, 
		{success:processMessages, failure:showErrorMessage, 
			argument:{ errorMessage:"There was an error saving the mode",
				divId:"modeMessage"} });
}

function setBoundingBox() {
	var form = get_form(_mapFormId);
	if (!form) {
		return false;
	}
	
	var params = "maxLat="+form.maxLat.value;
	params += "&minLat="+form.minLat.value;
	params += "&minLon="+form.minLon.value;
	params += "&maxLon="+form.maxLon.value;
	
	YAHOO.util.Connect.asyncRequest('GET', "/j/ICETray.html?"+params, 
		{
		success:function(o) {processMessages(o); listFileSizes();}, 
		failure:showErrorMessage, 
		argument:{
			errorMessage:"There was an error saving the bounding box",
			divId:"bboxMessage" }
		});
}

function loadICEBox() {
	YAHOO.util.Connect.asyncRequest('GET', "/j/ICETray.html", 
		iceboxCallback);
}

function addSceneImage(sceneImageId) {
	YAHOO.util.Connect.asyncRequest('GET', "/j/ICETray.html?add=" + sceneImageId,
		{success:function(o) {processMessages(o); loadPage();},
		 failure:showErrorMessage, 
		 argument:{
		 	errorMessage:"There was an error adding the image",
			divId:"iceboxMessage"} });
}

function removeSceneImage(sceneImageId) {
	YAHOO.util.Connect.asyncRequest('GET', "/j/ICETray.html?remove=" + sceneImageId, 
		iceboxCallback);
}

function setOutputResolution(resolution) {
	YAHOO.util.Connect.asyncRequest('GET', "/j/ICETray.html?resolution="+resolution, 
		{success:processMessages, failure:showErrorMessage, 
			argument:{ errorMessage:"There was an error saving the output resolution",
				divId:"outputResolutionMessage"} });
}