/**********************
		CONFIGURATION
/*********************/
var bolCursorLatLong = true; //-- Turns the "Cursor Lat./Long." feature on and off.


/*var btnCloseWindow_n = new Image();
btnCloseWindow_n.src = "/images/interface/popup/btn_close_window_n.gif";
var btnCloseWindow_a = new Image();
btnCloseWindow_a.src = "/images/interface/popup/btn_close_window_a.gif";*/


/*****************************************
            Ajax
*****************************************/
/**
 * Callback function that just sticks ajaxresponse in resultID and hides the Ajax indicator.
 * Use end_AjaxIndicator()
*/
function processAJAXResults(strAjaxResponse, resultID) {

    var objDest = document.getElementById(resultID);
    objDest.innerHTML = strAjaxResponse;

    end_AjaxIndicator();
};

/**
 * Handler class for Ajax requests.
 * @param str url - URL of the page the parameters are sent to.
 * @param callback - Name of the function to call
*/
function AJAXInteraction(url, callback, resultID) {
    var req = init();
    req.onreadystatechange = processRequest;

    function init() {
        if(window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    function processRequest () {
        if(req.readyState == 4) {
            if(req.status == 200) {
                if(callback) callback(req.responseText, resultID);
            } else {
                errstring = 'Unable to process request (error code ' + req.status + ').';
                if(callback) callback(errstring, resultID);
            }
        }
    }

    this.doGet = function() {
        req.open("GET", url, true);
        req.send(null);
    }

    this.doPost = function(body) {
        req.open("POST", url, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(body);
    }
};

/**
 * Initiates an Ajax request for the data layers.
*/
function getLayerList(pageURL, buttontype, resultID, year1, month1, day1, year2, month2, day2, image_on, image_band, checkboxes_array, public_site, username, groupname) {
    var idholder = document.getElementById('ajax_results_id');
    idholder.value = resultID;

    var url = 'http://' + pageURL;
    url += (url.substring(url.length - 1) == "/") ? 'getbuttons.asp' : '/getbuttons.asp'

    var params = 'buttontype=' + buttontype + '&startdate=' + year1 + month1 + day1 + '&enddate=' + year2 + month2 + day2 + '&image_on=' + image_on + '&image_band=' + image_band + '&public_site=' + public_site + '&username=' + username + '&groupname=' + groupname + '&checkboxes_array=' + checkboxes_array;

    var ai = new AJAXInteraction(url, processAJAXResults, resultID);
    ai.doPost(params);
};

/**
 * Wraps getLayerList() and shows Ajax indicators.
*/
function changeCursor(pageURL, buttontype, resultID, year1, month1, day1, year2, month2, day2, t_image_on, t_image_band, t_checkboxes_array, public_site, username, groupname) {
	start_AjaxIndicator();

	document.getElementById(resultID).innerHTML = 'Retrieving layers for ' + year1 + month1 + day1 + ' to ' + year2 + month2 + day2 + '...';

	window.setTimeout('getLayerList("'+ pageURL + '","' + buttontype + '","' + resultID + '","' + year1 + '","' + month1 + '","' + day1 + '","' + year2 + '","' + month2 + '","' + day2 + '","' + t_image_on + '","' + t_image_band + '","' + t_checkboxes_array + '","' + public_site + '","' + username + '","' + groupname + '")', 500);
};

/**
 * Generic callback function for Ajax that simply hides the indicator and puts the results into resultID element.
*/
function cb_genericAjax(strAjaxResponse, resultID) {
    end_AjaxIndicator();
    document.getElementById(resultID).innerHTML = strAjaxResponse;
};



/*****************************************
            Miscellaneous
*****************************************/
/**
 * Simple wrapper to set the image_name field.
*/
function setImageName(strImageName) {
  //if(document.MapForm.image_name.value) {
    document.MapForm.image_name.value = strImageName;
  //}
};

/**
 * Simple wrapper to set the image_on field.
*/
function setImageOn(strImageOn) {
	document.MapForm.image_on.value = strImageOn;
};

/**
 * Non-Simple wrapper to enable the select element with the given ID.
 * Basically, when enable one drop down box (or other element I suppose), we want to disable the previously enabled one (only one enabled element at a time)
 * ID of previously enabled element is in hidden img_band_enabled element.
 * Note this is called as an onClick due do IE bug when using onChange event of radio button. That is why it needs to check visibility (in case of double click etc)
 */
function enableSelect(strSelectID) {
	var newenabled = document.getElementById(strSelectID);
	if(newenabled.style.visibility=='hidden') {
		newenabled.disabled = '';
		newenabled.style.visibility = 'visible';
		newenabled.parentNode.style.visibility = 'visible';
		if(document.getElementById('img_band_enabled').value != 'none') {
			var oldenabled = document.getElementById('img_band_enabled').value;
			document.getElementById(oldenabled).disabled = 'disabled';
			document.getElementById(oldenabled).style.visibility = 'hidden';
			document.getElementById(oldenabled).parentNode.style.visibility = 'hidden';
		}
		document.getElementById('img_band_enabled').value = strSelectID;
	}
};

/**
 * Force the value of the select menus to the date for today.
*/
function select_today() {
	var objToday = new Date();
	document.select_day.Select_Day.selectedIndex = (objToday.getDate() - 1);
	document.select_day.Select_Day2.selectedIndex = (objToday.getDate() - 1);

	document.select_day.Select_Month.selectedIndex = (objToday.getMonth());
	document.select_day.Select_Month2.selectedIndex = (objToday.getMonth());

	document.select_day.Select_Year.selectedIndex = 0;
	document.select_day.Select_Year2.selectedIndex = 0;

	document.select_day.submit();
};

/**
 * Bookmarks the current map display and the image currently displayed (see: "Other Datasets").
*/
function CreateBookmark(top, bottom, left, right, mapwidth, mapheight, img, imgtext) {
    var URLstr;
    URLstr = location.href + '?FHS_on=off&cmd=bookmark&bookmarked=true&Top=' + top + '&Bottom=' + bottom + '&Left=' + left + '&Right=' + right + '&mapwidth=' + mapwidth + '&mapheight=' + mapheight;
    URLstr = URLstr.replace('#','');

    var d = new Date();
    var yr = d.getFullYear() + '';
    var FBAByMonthThisYear = 'layer_faa' + yr;

    var BookmarkLayers = new Array('layer_cadastre', 'layer_roads', 'layer_railrdl', 'layer_inwatera', 'layer_lga_area_gda_ll', 'layer_NationalParks2005', 'layer_BFC_Regions_10Apr04', 'layer_FESA_Regions28June05', 'layer_pastbound', 'layer_pastbound_lines', 'layer_polbndl', 'layer_builtupp', 'layer_continental_shelf_wa', 'layer_data250_r', 'layer_aus1deg', 'layer_aushalfdeg', 'layer_landsat_index', 'layer_stateboundaries', FBAByMonthThisYear, 'layer_dectenure_fill');

    for(var i=0; i < BookmarkLayers.length; i++) {
        if(document.MapForm[BookmarkLayers[i]] && document.MapForm[BookmarkLayers[i]].checked) {
            URLstr = URLstr + '&' + BookmarkLayers[i] + '=on';
        }
    }

    URLstr = URLstr + '&image_on=' + img + '&image_name=' + imgtext;

    if(window.sidebar) {
        window.sidebar.addPanel(document.title, URLstr, "");
    } else if (document.all) {
        window.external.AddFavorite(URLstr, document.title);
    }
};

/**
 * Toggles the image from having an expand or collapsed image. Compatable with ancient browsers.
*/
function SwapExpandImage(ImageID) {
    var Image;
    var elem;
    var hza;

    if(document.layers) { //IS NETSCAPE 4 or below
        Image = document.layers[ImageID].src;
    }

    if(document.getElementById) {
        hza = document.getElementById(ImageID);
        Image = hza.src;
    } else {
        if(document.all) { //IS IE 4 or 5 (or 6 beta)
            elem = document.all(ImageID);
            if (elem != null) Image = elem.src;
        }
    }

    if(Image.substring((Image.length-10), Image.length) == 'expand.gif') {
        //Image = 'Buttons/collapse.gif';
        Image = Image.replace('expand', 'collapse');
    } else {
        //Image = 'Buttons/expand.gif';
        Image = Image.replace('collapse', 'expand');
    }

    if(document.layers) { //IS NETSCAPE 4 or below
        document.layers[ImageID].src = Image;
    }

    if(document.getElementById) {
        hza = document.getElementById(ImageID);
        hza.src = Image;
    } else {
        if(document.all) { //IS IE 4 or 5 (or 6 beta)
            if(elem != null) elem.src = Image;
        }
    }
};

/**
 * Displays the lat/long at the point on the map the cursor is at.
*/
function get_LatLong() {
		if(bolCursorLatLong === true) {
	    var intTop = document.MapForm.Top.value;
	    var intLeft = document.MapForm.Left.value;
	    var intLatDiff = document.MapForm.Bottom.value - intTop;
	    var intLongDiff = document.MapForm.Right.value - intLeft;

	    var intLat = new Number(intTop) + (intLatDiff * (intMouseY / document.MapForm.mapheight.value));
	    var intLong = new Number(intLeft) + (intLongDiff * (intMouseX / document.MapForm.mapwidth.value));
	    intLat = intLat.toFixed(3);
	    intLong = intLong.toFixed(3);

	    $('cursorLatLong').innerHTML = intLat + ", " + intLong;
  	}
};

/**
 * Wrapper for polyline and polygon so the individual measurements for distances change with the total.
 *
 * @param intValue
 * @param strToUnit
 * @param strElmID
 * @param intDistancesCount - The number of lines making up the polyline/gon.
 *
 * @see convertMeasurement() in common.js
*/
function polyConversionWrapper(intValue, strToUnit, strElmID, intDistancesCount) {
	for(i = 1; i<=intDistancesCount; i++)
		convertMeasurement($("org_point" + i).innerHTML, strToUnit, "point" + i);

	convertMeasurement(intValue, strToUnit, strElmID);
};



/*****************************************
        MapForm Modifiers
*****************************************/
function print_image_only() {
		mt_prepareForPrint();

		var strOldCmd = document.MapForm.Cmd.value;
    document.MapForm.Cmd.value = "PRINTSETUP";
    document.MapForm.printmapwidth.value = document.MapForm.mapwidth.value;
    document.MapForm.printmapheight.value = document.MapForm.mapheight.value;
    document.MapForm.printmaptype.value = "map_only";

		//-- Submit the form to a new window.
		var strOldTarget = document.MapForm.target;
		document.MapForm.target = '_blank';
		document.MapForm.submit();

		//-- Restore to the previous values.
		document.MapForm.target = strOldTarget;
    document.MapForm.Cmd.value = strOldCmd;
};

function printA3_portrait() {
		mt_prepareForPrint();

		var strOldCmd = document.MapForm.Cmd.value;
    document.MapForm.Cmd.value = "PRINTSETUP";
    document.MapForm.printmapwidth.value = "780";
    document.MapForm.printmapheight.value = "1150";
    document.MapForm.printmaptype.value = "full";

		var strOldTarget = document.MapForm.target;
		document.MapForm.target = '_blank';
		document.MapForm.submit();

		document.MapForm.target = strOldTarget;
    document.MapForm.Cmd.value = strOldCmd;
};

function printA3_landscape() {
		mt_prepareForPrint();

		var strOldCmd = document.MapForm.Cmd.value;
    document.MapForm.Cmd.value = "PRINTSETUP";
    document.MapForm.printmapwidth.value = "1100";
    document.MapForm.printmapheight.value = "800";
    document.MapForm.printmaptype.value = "full";

		var strOldTarget = document.MapForm.target;
		document.MapForm.target = '_blank';
		document.MapForm.submit();

		document.MapForm.target = strOldTarget;
    document.MapForm.Cmd.value = strOldCmd;
};

function printA4_landscape() {
		mt_prepareForPrint();

		var strOldCmd = document.MapForm.Cmd.value;
    document.MapForm.Cmd.value = "PRINTSETUP";
    document.MapForm.printmapwidth.value = "700";
    document.MapForm.printmapheight.value = "450";
    document.MapForm.printmaptype.value = "full";

		var strOldTarget = document.MapForm.target;
		document.MapForm.target = '_blank';
		document.MapForm.submit();

		document.MapForm.target = strOldTarget;
    document.MapForm.Cmd.value = strOldCmd;
};

function printA4_portrait() {
		mt_prepareForPrint();

		var strOldCmd = document.MapForm.Cmd.value;
    document.MapForm.Cmd.value = "PRINTSETUP";
    document.MapForm.printmapwidth.value = "420";
    document.MapForm.printmapheight.value = "700";
    document.MapForm.printmaptype.value = "full";

		var strOldTarget = document.MapForm.target;
		document.MapForm.target = '_blank';
		document.MapForm.submit();

		document.MapForm.target = strOldTarget;
    document.MapForm.Cmd.value = strOldCmd;
};

function change_k490_year(newyr) {
	document.MapForm.K490_year.value = newyr;
	document.MapForm.Cmd.value = "UPDATE";
	document.MapForm.submit();
};

function change_sst_year(newyr) {
	document.MapForm.SST_year.value = newyr;
	document.MapForm.Cmd.value = "UPDATE";
	document.MapForm.submit();
};

function change_ndvi_year(newyr) {
	document.MapForm.NDVI_year.value = newyr;
	document.MapForm.Cmd.value = "UPDATE";
	document.MapForm.submit();
};

function change_fh_year(newyr) {
	document.MapForm.FH_year.value = newyr;
	document.MapForm.Cmd.value = "UPDATE";
	document.MapForm.submit();
};

function change_sm_year(newyr) {
	document.MapForm.SM_year.value = newyr;
	document.MapForm.Cmd.value = "UPDATE";
	document.MapForm.submit();
};

function onPointXY(x, y) {
    //alert("onPointXY: x=" + x + "  y=" + y )
};

function onLayerSwitch() {
    document.body.style.cursor = 'wait';
    document.MapForm.Cmd.value = "UPDATE";
    document.MapForm.submit();
};

function onLayerSwitch_expand_mapwidth() {
    document.MapForm.Cmd.value = "UPDATE";
    document.MapForm.expand_mapwidth.value = "on";
    document.MapForm.submit();
};

function onLayerSwitch_collapse_mapwidth() {
    document.MapForm.Cmd.value = "UPDATE";
    document.MapForm.collapse_mapwidth.value = "on";
    document.MapForm.submit();
};

function onLayerSwitch_expand_mapheight() {
    document.MapForm.Cmd.value = "UPDATE";
    document.MapForm.expand_mapheight.value = "on";
    document.MapForm.submit();
};

function onLayerSwitch_collapse_mapheight() {
    document.MapForm.Cmd.value = "UPDATE";
    document.MapForm.collapse_mapheight.value = "on";
    document.MapForm.submit();
};

function onLayerSwitch_expand_to_fit() {
    document.MapForm.Cmd.value = "UPDATE";

    var arrDimenssions = getWindowSize();
    document.MapForm.browser_width.value = arrDimenssions[0];
    document.MapForm.browser_height.value = arrDimenssions[1];
    document.MapForm.expand_to_fit.value = "on";
    document.MapForm.submit();
};

function onOverviewMapClick() {
    document.MapForm.Cmd.value = "UPDATE";
    document.MapForm.submit();
};

function ZoomFull() {
    document.MapForm.Cmd.value = "MAP";
    document.MapForm.submit();
};

function onZoomBox(left, top, right, bottom) {
    ms_setXY(left, top);
    ms_setXY2(right, bottom);
    document.MapForm.submit();
};

function onZoomXY(x, y) {
		ms_setXY(x, y);
		document.MapForm.submit();
};

function onClickXY(x, y) {
    document.MapForm.map_x.value = x;
    document.MapForm.map_y.value = y;
    document.MapForm.submit();
};

function onPixelValue(x, y, YAxisMin, YAxisMax) {
    document.MapForm.map_x.value = x;
    document.MapForm.map_y.value = y;
    document.MapForm.pixel_value_y_axis_min.value = YAxisMin;
    document.MapForm.pixel_value_y_axis_max.value = YAxisMax;
    document.MapForm.submit();
};

function OnButton(ButtonName) {
		//-- Reset all buttons to be "up".
    document.MapForm.Cmd.value = ButtonName;
    document.MapForm.LastCmd.value = ButtonName;
    document.TOOL_ZOOMIN.src = "shared/buttons/in_up.gif";
    document.TOOL_ZOOMOUT.src = "shared/buttons/out_up.gif";
    document.TOOL_PAN.src = "shared/buttons/pan_up.gif";
    document.TOOL_IDENTIFY.src = "shared/buttons/id_up.gif";
    document.TOOL_RECT.src = "shared/buttons/rect_up.gif";
    document.TOOL_LINE.src = "shared/buttons/line_up.gif";
    document.TOOL_POLYLINE.src = "shared/buttons/polyline_up.gif";
    document.TOOL_POLYGON.src = "shared/buttons/polygon_up.gif";

    if(document.PixelValue_1)
        document.PixelValue_1.src = "shared/buttons/pixel_value_up.gif";

    if(document.PixelValue_2)
        document.PixelValue_2.src = "shared/buttons/pixel_value_50_up.gif";

    if(document.PixelValue_3)
        document.PixelValue_3.src = "shared/buttons/pixel_value_blue_up.gif";


		//-- Change the state of the button that was selected.
		switch(ButtonName) {
			case TOOL_ZOOMIN:
				document.TOOL_ZOOMIN.src = "shared/buttons/in_dn.gif";
				break;

			case TOOL_ZOOMOUT:
				document.TOOL_ZOOMOUT.src = "shared/buttons/out_dn.gif";
				break;

			case TOOL_PAN:
				document.TOOL_PAN.src = "shared/buttons/pan_dn.gif";
				break;

			case TOOL_IDENTIFY:
				document.TOOL_IDENTIFY.src = "shared/buttons/id_dn.gif";
				break;

			case "PixelValue_1":
				document.PixelValue_1.src = "shared/buttons/pixel_value_dn.gif";
				ButtonName = TOOL_PIXEL_VALUE_1;

				document.MapForm.Cmd.value = "PixelValue";
				document.MapForm.LastCmd.value = "PixelValue";
				break;

			case "PixelValue_2":
				document.PixelValue_2.src = "shared/buttons/pixel_value_50_dn.gif";
				ButtonName = TOOL_PIXEL_VALUE_2;

				document.MapForm.Cmd.value = "PixelValue";
				document.MapForm.LastCmd.value = "PixelValue";
				break;

			case "PixelValue_3":
				document.PixelValue_3.src = "shared/buttons/pixel_value_blue_dn.gif";
				ButtonName = TOOL_PIXEL_VALUE_3;

				document.MapForm.Cmd.value = "PixelValue";
				document.MapForm.LastCmd.value = "PixelValue";
				break;

			case TOOL_RECT:
				document.TOOL_RECT.src = "shared/buttons/rect_dn.gif";
				document.MapForm.Cmd.value = TOOL_ZOOMIN; //-- Fixes a bug when you would measure, refresh and then zoom in without selecting the tool.
				break;

			case TOOL_LINE:
				document.TOOL_LINE.src = "shared/buttons/line_dn.gif";
				document.MapForm.Cmd.value = TOOL_ZOOMIN;
				break;

			case TOOL_POLYLINE:
				document.TOOL_POLYLINE.src = "shared/buttons/polyline_dn.gif";
				document.MapForm.Cmd.value = TOOL_ZOOMIN;
				break;

			case TOOL_POLYGON:
				document.TOOL_POLYGON.src = "shared/buttons/polygon_dn.gif";
				document.MapForm.Cmd.value = TOOL_ZOOMIN;
				break;
		}

    TB_setTool(ButtonName);
    TB_updateCursor(); //-- Restore crosshair cursor after objMapCanvas.clear()
};



//-- Utility functions for setting coordinate fields in MapForm.
function ms_setXY(x, y) {
	document.MapForm.map_x.value = x;
	document.MapForm.map_y.value = y;
};

function ms_setXY2(x, y) {
	document.MapForm.map_x2.value = x;
	document.MapForm.map_y2.value = y;
};

function ms_setRect(x1, y1, x2, y2) {
	ms_setXY(x1, y1);
	ms_setXY2(x2, y2);
};

function ms_setPoly(strPointsX, strPointsY) {
  document.MapForm.pointsX.value = strPointsX;
  document.MapForm.pointsY.value = strPointsY;
};