﻿//
// Shop Map script interface.
// Written By: David Martin Copyright 2009 I.T. Beyond Pty Ltd.
//
// Interface for ExplorOz Shop Map system.
// Requires prototype.js
// Requires OpenLayers.js
//
var PlaceMap, DispProj, DataProj, ppnt, VectorLayer, style_mark;
var MapPopUp = null;
var OLTimeout = 1;

function deserialize(responseText) {
    var features = new OpenLayers.Format.GeoRSS().read(responseText);
    if (features) {
        $jq('#' + HintID).text('');$jq('#PlaceName').css('background-color', 'white');
        if (features.constructor != Array) { features = [features]; }
        if (features.length == 0) { $jq('#PlaceName').css('background-color', 'red'); $jq('#OLReload').hide(); return; } else {
        if (features.length == 1) {
            var fll = features[0].geometry.getBounds().getCenterLonLat();
            $jq("#" + ExtentID).value = fll.lon.toFixed(4) + ' ' + fll.lon.toFixed(4) + ' ' + fll.lat.toFixed(4) + ' ' + fll.lat.toFixed(4);
            $jq("#aspnetForm").submit();  return;
        }
        var pointlist = [];
        for (var i = 0; i < features.length; ++i) {
            pointlist.push(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(features[i].geometry.getBounds().getCenterLonLat().lon, features[i].geometry.getBounds().getCenterLonLat().lat), null, style_mark));
        } VectorLayer.addFeatures(pointlist);$jq('#' + HintID).html('<h4 style="margin:0px">Results</h4>Multiple places found click the base of your selected marker for results.');
    }
    }
    $jq('#OLReload').hide();
}

function showPlaces() {
    var theItem = $jq('#PlaceName').val();
    if (theItem.length > 0) {
        $jq('#OLReload').show();
        VectorLayer.destroyFeatures();
        theurl = BaseURL + '/Places/OutputPlaceGEORSS.aspx?n=' + theItem;
        $jq.ajax({ url: theurl, processData: false,
            success: function(html) { deserialize(html) },
            failure: function() { alert('Places get result failed...') }
        });
    } return false;
}

function loadMaps() {
    if (typeof OpenLayers == 'undefined') { OLTimeout++; if (OLTimeout < 30) { setTimeout(function() { loadMaps() }, 1000); } else { alert("There has been an error loading the mapping system - please try refresh"); } return (false); }
    DispProj = new OpenLayers.Projection("EPSG:4326");
    DataProj = new OpenLayers.Projection("EPSG:900913");
    var options = {
        displayProjection: DispProj,
        projection: DataProj,
        maxExtent: new OpenLayers.Bounds(11056838.559733333, -5778405.80544, 18854333.528855554, -885416.91662),
        minScale: 41500000,
        units: "m",
        controls: []
    };
    PlaceMap = new OpenLayers.Map('nav_map', options);

    var shopmap = new OpenLayers.Layer.MapServer("Shop Map", "http://maps.exploroz.com/getMap.aspx", { 'cmds': 'map.layer[oceansea].class[0].style[0]=color 244 244 244&map.imagecolor=244 244 244' }, { gutter: 0, singleTile: true });
    style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_mark.externalGraphic = 'http://www.exploroz.com/Scripts/Openlayers/img/marker.png';
    style_mark.backgroundGraphic = 'http://www.exploroz.com/Scripts/Openlayers/img/marker_shadow.png';
    style_mark.graphicYOffset = -20;
    style_mark.backgroundYOffset = -17;
    style_mark.backgroundXOffset = 0;
    style_mark.graphicZIndex = 11;
    style_mark.backgroundGraphicZIndex = 10;
    style_mark.pointRadius = 10;
    style_mark.graphicOpacity = 1;
    style_mark.rendererOptions = { yOrdering: true };
    VectorLayer = new OpenLayers.Layer.Vector("Vector Layer");
    PlaceMap.addLayers([shopmap, VectorLayer]);

    var control = new OpenLayers.Control();
    OpenLayers.Util.extend(control, { draw: function() { this.box = new OpenLayers.Handler.Box(control, { "done": this.notice }); this.box.activate(); },
    notice: function(bounds) {
    $jq('#OLReload').show(); ; var ll = PlaceMap.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom)).transform(DataProj, DispProj);
    var ur = PlaceMap.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top)).transform(DataProj, DispProj);
        if (isNaN(ll.lon)) {
            var cp = PlaceMap.getLonLatFromPixel(new OpenLayers.Pixel(bounds.x, bounds.y)).transform(DataProj, DispProj); $jq('#' + ExtentID).val(cp.lon.toFixed(4) + ' ' + cp.lon.toFixed(4) + ' ' + cp.lat.toFixed(4) + ' ' + cp.lat.toFixed(4));
        } else { $jq('#' + ExtentID).val(ll.lon.toFixed(4) + ' ' + ur.lon.toFixed(4) + ' ' + ll.lat.toFixed(4) + ' ' + ur.lat.toFixed(4)); }
        VectorLayer.destroy();
        theForm.submit();
        }
    });

    PlaceMap.addControl(control);   
    PlaceMap.addControl(new OpenLayers.Control.MousePosition());
    PlaceMap.zoomToMaxExtent();
    showVectorfromQueryString()
    $jq('#OLReload').hide();
}

function showVectorfromQueryString() {
    var me = querySt('me');
    if (me != null) {
        ep = unescape(me.replace(/\+/g, ' ')).split(' ');
        lllon = parseFloat(ep[0]); urlon = parseFloat(ep[1]); lllat = parseFloat(ep[2]); urlat = parseFloat(ep[3]);
        if (urlon == lllon) {
            var pointFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(urlon, urlat).transform(DispProj, DataProj), null, style_mark);
            VectorLayer.addFeatures([pointFeature]);
        } else {
        var poly = new OpenLayers.Bounds(lllon, lllat, urlon, urlat).toGeometry().transform(DispProj, DataProj);
            var polygonFeature = new OpenLayers.Feature.Vector(poly);
            VectorLayer.addFeatures([polygonFeature]);
        }
    }
}

function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
    return null;
}

function runOnLoad(func) { 
  if ($jq.browser.msie) { 
    if (typeof(window.onload) == 'function') { 
      var old_init = window.onload; 
      window.onload = function() { 
        old_init(); 
        func(); 
      }; 
    } else { 
      window.onload = func; 
    } 
  } else { // Not IE 
    $jq(document).ready(func); 
  } 
}