// All functions which enable user's interaction with WhiteSnow interface are defined
// Note: some functions require a parameter n to be passed in.
// n simply indicates which map is currently active 
// 0 - the arctic map is active
// 1 - the antarctic map is active
// 2 - the "All Regions" tab is active, which doesn't contain a map
function clearSelection(n) {
	selectionMarkerLayers[n].clearMarkers();
	
	//clean the info in lon and lat forms in search.jsp 
	for (var i = 0; i < 4; i++) {
		var num = (i + 1).toString();
		document.getElementById("lon_" + num).value = "";
		document.getElementById("lat_" + num).value = "";
	}
	
	document.getElementById("showAvailable").checked = false;
	polygonLayers[n].destroyFeatures();
	points.length = 0;
    lonlats[n].length = 0;  
}

function clearFootprints(n) {
	if (resultsIdArrays[n].length > 0) {
		for (var i = 0; i < resultsIdArrays[n].length; i ++) {
			removeSelectionFromArray(resultsIdArrays[n][i]);
		}
	}
	
	resultsLayers[n].destroyFeatures();
	resultsIdArrays[n].length = 0;
	resultsVectorArrays[n].length = 0;
	resultsMarkerArrays[n].length = 0;
	briefPopupIdArrays[n].length = 0;
	briefPopupContentArrays[n].length = 0;
}

function clearResults(n) {
	document.getElementById("results").src = "results.jsp";
	document.getElementById("metadata").src = "";
	document.getElementById("Rdata").src = "";
	
	document.getElementById("freekey").value = "";
	document.getElementById("id").value = "";
	document.getElementById("rsmonth").value = "Jan";
	document.getElementById("rsday").value = "1";
	document.getElementById("rsyear").value = "1997";
	document.getElementById("smonth").value = "Jan";
	document.getElementById("sday").value = "1";
	document.getElementById("syear").value = "1980";
	document.getElementById("emonth").value = "em";
	document.getElementById("eday").value = "ed";
	document.getElementById("eyear").value = "ey";
	document.getElementById("remonth").value = "Jan";
	document.getElementById("reday").value = "28";
	document.getElementById("reyear").value = "2007";
	document.getElementById("direction").value = "Ascending";
	document.getElementById("beam").value = "FINE";
	layout.getRegion('east').getTabs().activate("search_div"); 
	
	layout.getRegion('east').getTabs().disableTab("results_div");
	layout.getRegion('east').getTabs().disableTab("R1_data");
	layout.getRegion('east').getTabs().disableTab("metadata_popup");
}

function clearSearch(n) {
	clearSelection(n);   
	clearFootprints(n);
	clearResults(n);
}

// Preprocess the search criteria and pass them to searchprocess1.0.jsp
// Puts together the date as one day+month+year and points etc
function goSearch(n) {
	document.getElementById("metadata").src = "";
	var cat = document.getElementById("category").value;
	var start_date, end_date;
	
	// Format the dates
	if(cat == "2") {
		start_date = new Date(document.getElementById("rsmonth").value + " " + document.getElementById("rsday").value + ", " + document.getElementById("rsyear").value);
		end_date = new Date(document.getElementById("remonth").value + " " + document.getElementById("reday").value + ", " + document.getElementById("reyear").value);
	}
	else {
		start_date = new Date(document.getElementById("smonth").value + " " + document.getElementById("sday").value + ", " + document.getElementById("syear").value);
		end_date = new Date(document.getElementById("emonth").value + " " + document.getElementById("eday").value + ", " + document.getElementById("eyear").value);
	}
	
	if (start_date > end_date) {
		search_flag = false;
		Ext.MessageBox.alert('Search Error', 'Your end date cannot be before your start date.');
		return;
	}
	
	clearFootprints(n);
	document.getElementById("results").src = "results.jsp";
	
	var searchp = "";
	var useAOI = true; //what is this used for?
	var src;
	var dest = projGlobal; 
	search_flag = true;
	src = projArctic;
	if (n == 0) {
		src = projArctic; 
	} else if (n == 1) {
		src = projAntarctic; 
	}
	document.getElementById("searchform").target = "results";
	
	if (cat=="2") {
		//Area of interest must be selected for RADARSAT-1
		if (lonlats[n].length == 0) {
			Ext.MessageBox.alert('Search Error', 'Please select an area of interest.');
            return;
		}
	}
	
	if (lonlats[n].length == 3 || lonlats[n].length == 2 || lonlats[n].length == 1) {
		Ext.MessageBox.alert('Search Error', 'Please select four points on map');
		clearSearch(n);
		return;
	}
   
	// All Regions is selected 
	if (n==2 || lonlats[n].length != 4) {
		useAOI = false;
	}

	// All Regions is not selected
	// Searching either the arctic or antarctic regions for area of interest selected
	if (useAOI == true) {
		// If the user selects exactly 4 points on the arctic or antarctic map
		for (var i = 0; i < lonlats[n].length; i ++) {
			var point= new OpenLayers.Geometry.Point(lonlats[n][i].lon, lonlats[n][i].lat);
			OpenLayers.Projection.transform(point, src, dest); 
			searchp += point.x.toString() + ";" + point.y.toString();
			
			if ( i < lonlats[n].length - 1) {
				searchp += ";";
			}
		}
	// All Regions is  not selected and Area of interest is also not selected
	} else if (n != 2){
		// make sure only search within the boundaries of the arctic map or antarctic map
		for (var i = 0; i < 4; i ++) {
			var point= new OpenLayers.Geometry.Point(wholeMapLonlats[n][i].lon, wholeMapLonlats[n][i].lat); 
			searchp += point.x.toString() + ";" + point.y.toString();
			
			if ( i < 3) {
				searchp += ";";
			}
		}
	}
	
	activateResultsTab();
	
	if (document.getElementById("searchform").showAvailable.checked == 1) {
		document.getElementById("searchform").showAvailable.value="1";
	} 
	else {
		document.getElementById("searchform").showAvailable.value="0";
	}
	
	document.getElementById("searchform").spoints.value = searchp;
	document.getElementById("searchform").submit();
	
	return true;
}

function activateResultsTab() {
	layout.getRegion("east").getTabs().getTab("results_div").enable();
	layout.getRegion('east').getTabs().activate("results_div");
}

// quick key words search
function goQuickSearch() {
	document.getElementById("results").src = "results.jsp";
	document.getElementById("quick_form").target = "results";
	activateResultsTab();
	
	document.getElementById("quick_form").submit();
	return true;
}

// login button
function loginButton() {
	if (document.getElementById("logbtn").value=="Log In")
	{
		parent.dialog.setTitle('Log In'); 
		parent.document.getElementById('metadata').src = "/whitesnow/Whitesnow/loginPage/logon2.jsp?id=0&category=0&name=0&date=0&login=1";
		parent.dialog.show();  
	}
	else
	{
		parent.dialog.setTitle('Log Out'); 
		parent.document.getElementById('metadata').src = "/whitesnow/Whitesnow/loginPage/logout.jsp?id=0&category=0&name=0&date=0&login=1";
		parent.dialog.show();  
	}
}

// Convert OpenLayers.Geometry.LinearRing to OpenLayers.Feature.Vector
function openConvert(linear_ring) {
	var open_poly = new OpenLayers.Geometry.Polygon([linear_ring]);
	var open_vector_of_interest = new OpenLayers.Feature.Vector(open_poly,null,default_style);
	return open_vector_of_interest;
}

// Convert arrays of coordinates to OpenLayers.Geometry.LinearRing
function openConvertLinear(xCoords, yCoords, n) {		
   var src = projGlobal, dest, xTemp;
   var open_points = new Array();  // applied to store four points rechieved from Oracle
   var open_MutiplePoints = new Array(); // store points used to create polygon in openlayer 
   dest = projArctic;
	if (n == 0) {
     	dest = projArctic;
  	} else if (n == 1) {
     	dest = projAntarctic;
  	}
	//create polygons with arc boundaries
	for (var i = 0; i < xCoords.length; i ++) { //? assume xcoords and ycoords are the same?
		open_points[i] = new OpenLayers.Geometry.Point(xCoords[i], yCoords[i]);
		  //alert(xCoords[i]+"  "+ yCoords[i]);//testing code
		if (i>0) {   // create points between point[i-1] and point[i] in order to make arc-like boundaries
			if ((open_points[i].y - open_points[i-1].y) > -0.0001 && (open_points[i].y - open_points[i-1].y)<0.0001){ //ensure two points has the same lat coordinates
				xTemp = open_points[i].x - open_points[i-1].x;
				if (xTemp >0){
					for (var j=0; j<xTemp; j++){  // add one point for one lontitude degree
						open_MutiplePoints.push(new OpenLayers.Geometry.Point( open_points[i-1].x + j, yCoords[i] ));
					}
				}
				else{     
					xTemp = -xTemp;
					for (var j=0; j<xTemp; j++){
						open_MutiplePoints.push(new OpenLayers.Geometry.Point(open_points[i-1].x - j, yCoords[i]));
					}
				}

			}
		}
		open_MutiplePoints.push(new OpenLayers.Geometry.Point(xCoords[i], yCoords[i]));
	}
	//testing code alert(open_MutiplePoints.length);
	for (var i =0; i < open_MutiplePoints.length; i++){
		OpenLayers.Projection.transform(open_MutiplePoints[i], src, dest); 
		if (open_MutiplePoints[i] == null ) return null;
	}

	open_MutiplePoints.push(open_MutiplePoints[0]);  // create a closed ring 
	var open_ring = new OpenLayers.Geometry.LinearRing(open_MutiplePoints);
	return open_ring; 
}

function requestMe() {
	parent.dbrequestfrm.document.requestform.submit();
}

//Generate the footprint (polygon and tear drop) of a metadata RECORD
//Called from requestcoords.jsp
//@param ID: recordId
function pushSelectionValues(ID) {
	var n = getActiveMapNumber();
	var check = true;
	var vector;
	// Check if the footprint for this metadata set already exists
	if (resultsIdArrays[n].length > 0) {
		for (var i = 0; i < resultsIdArrays[n].length; i ++) {
			if (resultsIdArrays[n][i] == ID) {
				check = false;
				break;
			}
		}
	}
	// if the footprint does not exist
	if (check == true) {
    	// Generate a ploygon representing the footprint
    	var coordString = parent.dbrequestfrm.document.requestform.fetched_array.value;
    	// alert("coordstring = "+ coordString);  //testing code 
    	var coords = coordString.split(";");
 		// var isPoint = -1;
 		var xCoords = new Array();
 		var yCoords = new Array();
 		for (var i = 0, j = 1; i < coords.length; i += 2, j += 2) {
       		xCoords[i / 2] = parseFloat(coords[i]);
       		yCoords[j / 2 - 0.5] = parseFloat(coords[j]);
       		
    	}
 		//Check if coordinates belong to active map, if not do nothing
 		var linear_ring = openConvertLinear(xCoords, yCoords, n);
 		if (linear_ring!=null) {
 			resultsIdArrays[n].push(ID);
 			vector = openConvert(linear_ring);
 			resultsVectorArrays[n].push(vector);
 			//var poly = new OpenLayers.Geometry.Polygon([linear_ring]);
	      	var point = new OpenLayers.Geometry.Point((xCoords[0] + xCoords[2]) / 2, (yCoords[0] + yCoords[2]) / 2);
          	var src = projGlobal, dest;
          	dest = projArctic;
          	if (n == 0) {
          		dest = projArctic;   
          	} else if (n == 1) {
          		dest = projAntarctic;
          	}
          	OpenLayers.Projection.transform(point, src, dest);
          	var marker = new OpenLayers.Feature.Vector(point);
          	resultsMarkerArrays[n].push(marker);
      		// Draw the footprint
          	resultsLayers[n].addFeatures([vector]);
          	resultsLayers[n].drawFeature(vector, select_style);
          	resultsLayers[n].addFeatures([marker]);
          	resultsLayers[n].drawFeature(marker, resultsMarkerSelectStyle);
 		}
	}
}

/// Highlight the footprint on the map
function highlightFeature(ID) {
   var n = getActiveMapNumber();
   var pos = -1; 

   // Check if this footprint exists
	for (var i = 0; i < resultsIdArrays[n].length; i ++) {
		if (resultsIdArrays[n][i] == ID) {
			pos = i;
			resultsLayers[n].drawFeature(resultsVectorArrays[n][pos], select_style);
			resultsLayers[n].drawFeature(resultsMarkerArrays[n][pos], resultsMarkerSelectStyle);
			break;
		}
	}
	
}

//Unhighlight the footprint on the map
function unhighlightFeature(ID) {
   var n = getActiveMapNumber();
      // Check if this footprint exists, if it exists, unhighlight the footprint and the marker
	for (var i = 0; i < resultsIdArrays[n].length; i ++) {
		if (resultsIdArrays[n][i] == ID) {
			resultsLayers[n].drawFeature(resultsVectorArrays[n][i], default_style);
			resultsLayers[n].drawFeature(resultsMarkerArrays[n][i], resultsMarkerDefaultStyle);
			break;
		}
	}
}

//Remove a footprint of a metadata set
function removeSelectionFromArray(ID) {
   var n = getActiveMapNumber();
   // Check if this footprint exists, if it exists,remove it
	if (resultsIdArrays[n].length > 0) {
		for (var position = 0; position < resultsIdArrays[n].length; position ++) {
			if (resultsIdArrays[n][position] == ID) {
				resultsLayers[n].removeFeatures([resultsVectorArrays[n][position]]);
				resultsIdArrays[n].splice(position, 1);
				resultsVectorArrays[n].splice(position, 1);
				resultsLayers[n].removeFeatures([resultsMarkerArrays[n][position]]);
				resultsMarkerArrays[n].splice(position, 1);
				break;
			}
		}
	}
}

// Called when user clicks on the map
// A polygon representing the user's selection is drawn on the map
function drawUniversalSelection(n) {
	points.length = 0;
   selectionMarkerLayers[n].clearMarkers(); 
	for (var i = 0; i < lonlats[n].length; i ++) {
      if (lonlats[n][i] != null) {
         var marker = new OpenLayers.Marker(new OpenLayers.LonLat(lonlats[n][i].lon, lonlats[n][i].lat), new OpenLayers.Icon("img/target2.png", icon_size));
         selectionMarkerLayers[n].addMarker(marker);
   		var p = new OpenLayers.Geometry.Point(lonlats[n][i].lon, lonlats[n][i].lat);
   		points.push(p);
      }		
	}
				
	if (lonlats[n].length > 1) {
		points.push(points[0]);
	}

	points_ring = new OpenLayers.Geometry.LinearRing(points);
	area_of_interest_polygon = new OpenLayers.Geometry.Polygon(points_ring);	
	area_of_interest_feature = new OpenLayers.Feature.Vector(area_of_interest_polygon,null,vector_style);
	polygonLayers[n].destroyFeatures();
	polygonLayers[n].addFeatures([area_of_interest_feature]);
}

// Set the values of the HTML elements which store
// the longitudes and latitudes of the points selected by the user
function setOutputPoints(n) {
   var src; 
   src = projArctic;
   if (n == 0) {
      src = projArctic;
   } else if (n == 1){
      src = projAntarctic;
   }
   var dest = projGlobal; 
	for (var i = 0; i < 4; i ++) {
		var num = (i + 1).toString();
      if (i < lonlats[n].length) {
         var point = new OpenLayers.Geometry.Point(lonlats[n][i].lon, lonlats[n][i].lat);
   		OpenLayers.Projection.transform(point, src, dest); 
   		document.getElementById("lon_" + num).value = point.x;
   		document.getElementById("lat_" + num).value = point.y;
      } else {
   		document.getElementById("lon_" + num).value = "";
   		document.getElementById("lat_" + num).value = "";         
      }		
	}
}

// Apply any changes made manually by the user
//Daniel: recreate lonlats list to reproject the points (inefficient)
function getOutputPoints(n) {
   var src = projGlobal;
   var dest= projArctic; 
   if (n == 0) {
      dest = projArctic; 
   } else if (n == 1) {
      dest = projAntarctic; 
   }
   lonlats[n] = new Array();
	for (var i = 0; i < 4; i ++) {
		var num = (i + 1).toString();
		var lon_value = document.getElementById("lon_" + num).value;
		var lat_value = document.getElementById("lat_" + num).value;	
		if (lon_value != "" && lat_value != "") {     // need to restrict the input value 
         var point = new OpenLayers.Geometry.Point(lon_value, lat_value);
         OpenLayers.Projection.transform(point, src, dest);
         lonlats[n].push(new OpenLayers.LonLat(point.x, point.y));
		}
	}
   setOutputPoints(n);
	drawUniversalSelection(n);   
}

function deleteLastPoint(n) {
	var num = (lonlats[n].length).toString();
	if (lonlats[n].length > 1) {
      lonlats[n].pop();
		document.getElementById("lon_" + num).value = "";
		document.getElementById("lat_" + num).value = "";
		getOutputPoints(n);
	}
	else if (lonlats[n].length == 1){
      clearMarks(n);
	}
}

function frameRefresh() {
	document.getElementById('results').src = "results.jsp";
	document.getElementById('dbrequestfrm').src = "dbrequest.jsp";
	document.getElementById('searchoptions').src = "search.jsp";
}

//Called when mouse over a footprint
function onFeatureSelect(feature) {
	var n = getActiveMapNumber();
	var searchResults = results;
	var pos = 0;

	// Check if this feature exists
	for (var j = 0; j < resultsIdArrays[n].length; j ++) {
		if (resultsMarkerArrays[n][j] == feature) {
			pos = j;
			break;
		}
	}

	// Go to the page of the search results which the result
	// associated with this footprint is on and highlight the result
	var page_num = searchResults.getPageFromId(resultsIdArrays[n][pos]);
	if (page_num==searchResults.currentPage) {} 
      else {
		searchResults.gotoPage(page_num);

      }
	searchResults.goDimTr(resultsIdArrays[n][pos]+'_row');
}

//Called when mouse out a footprint
function onFeatureUnselect(feature) {
	var searchResults = results;
	var n = getActiveMapNumber();
	
	var pos = 0;
	// Check if this feature exists
	for (var j = 0; j < resultsIdArrays[n].length; j ++) {
		if (resultsMarkerArrays[n][j] == feature) {
			pos = j;
			break;
		}
	}
	searchResults.goLiteTr(resultsIdArrays[n][pos]+'_row');
}

// Return an integer indicating which map is active
function getActiveMapNumber() {
	var activeTabId = layout.getRegion("center").getTabs().getActiveTab().id;
	if (activeTabId == "arctic") {
		return 0;
	} 
	else if (activeTabId == "antarctic") {
		return 1;
	}
	return -1;
}

