/*global OpenLayers, document, jQuery */
var map, gmlParser, wktParser;
var allBounds = new OpenLayers.Bounds(146597, 192627, 229380, 250139);
var res = "auto";
var availableResolutions = [122, 86, 60, 25, 5, 2.5];
var vector_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
vector_style.strokeColor = "#664395";
vector_style.fillColor = "#c3ea8f";
vector_style.externalGraphic = "pin1.png";
vector_style.graphicXOffset = -8;
vector_style.graphicYOffset = -33;
vector_style.graphicZIndex = 1;
vector_style.graphicOpacity = 1;
vector_style.graphicWidth = 24;
vector_style.graphicHeight = 32;
var sel_style = OpenLayers.Util.extend({}, vector_style);
sel_style.externalGraphic = "pin1a.png";
var baseOptions = {maxResolution: res, resolutions: availableResolutions, projection: 'EPSG:27700', maxExtent: allBounds, displayInLayerSwitcher: false};
var overlayOptions = {maxResolution: res, resolutions: availableResolutions, projection: 'EPSG:27700', maxExtent: allBounds, isBaseLayer: false, style: vector_style, rendererOptions: {yOrdering: true}};
var vectorLayer = new OpenLayers.Layer.Vector('interpretation', overlayOptions);
var os_planed = new OpenLayers.Layer.WMS("os_planed", "http://eryr.net/tilecache", {layers: 'planed-os'}, baseOptions);

OpenLayers.Map.prototype.panToForcedSmooth = function (lonlat) {
    if (!this.panTween) {
        this.panTween = new OpenLayers.Tween(this.panMethod);
    }
    var center = this.getCenter();
    if (lonlat.lon === center.lon && lonlat.lat === center.lat) {
        return;
    }
    var from = {lon: center.lon, lat: center.lat};
    var to = {lon: lonlat.lon, lat: lonlat.lat};
    this.panTween.start(from, to, 50, {
        callbacks: {
            start: OpenLayers.Function.bind(function (lonlat) {
                    this.events.triggerEvent("movestart");
                }, this),
            eachStep: OpenLayers.Function.bind(function (lonlat) {
                    lonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
                    this.moveTo(lonlat, this.zoom, {'dragging': true, 'noEvent': true});
                }, this),
            done: OpenLayers.Function.bind(function (lonlat) {
                    lonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
                    this.moveTo(lonlat, this.zoom, {'noEvent': true});
                    this.events.triggerEvent("moveend");
                }, this)
        }
    });
};

function photoClick() {
    jQuery("a[rel*='lightbox']").lightBox().click();
}

function onFeatureHover(feature) {
    jQuery(".purpleBox").removeClass("purpleBox");
    var thisFeature = feature;
    var featureID = "#" + thisFeature.data.id;
    jQuery(featureID).addClass("purpleBox");
    var jQString = "#" + thisFeature.geometry.id.replace(/\./g, "\\\\\\\.");
    var linkDest;
    if (thisFeature.data.portal_type === "GeoLink") {
        linkDest = thisFeature.data.url;
    } else if (thisFeature.data.portal_type === "SiopImage") {
        linkDest = thisFeature.data.url;
    } else {
        linkDest = "#" + thisFeature.data.id;
    }
    var linkText = "<p class='popTitle'><b>" + thisFeature.data.tTip + "</b></p>";
    jQuery("#OBSmapPop").show();
    jQuery(jQString).unbind();
    if (thisFeature.data.portal_type === "SiopImage") {
        jQuery("a[rel*='lightbox']").attr({href: thisFeature.data.url + "/image_preview", title: "<a href='" + thisFeature.data.url + "'>" + thisFeature.data.title + " by " + thisFeature.data.creator + " " + thisFeature.data.rights + "</a>"});
        jQuery(jQString).click(photoClick);
        jQuery("#OBSmapPop")[0].innerHTML = "<div id='miniImagePop'><div id='miniSpin'><img src='spinner.gif' /></div><div id='miniImage'><img src='" + thisFeature.data.url + "/image_mini' /></div></div>";
    } else {
        jQuery("#OBSmapPop")[0].innerHTML = linkText;
        jQuery(jQString).click(function () {
            document.location = linkDest;
        });
    }
}

function onFeatureUnhover(feature) {
    
    jQuery("#OBSmapPop").hide();
    jQuery("#OBSmapPop").removeClass("miniImage");
}

function i8eListeners() {
    if (map.controls.length === 2) {
        var hoverControl = new OpenLayers.Control.SelectFeature(vectorLayer, {hover: true, onSelect: onFeatureHover, onUnselect: onFeatureUnhover, geometryTypes: ["OpenLayers.Geometry.Point"], selectStyle: sel_style});
        map.addControl(hoverControl);
        hoverControl.activate();
    }
}

function setIcon(feature) {
    if (feature.data.portal_type) {
        feature.style.externalGraphic = "marker-" + feature.data.portal_type + ".png";
    }
    if (feature.data.icon && feature.data.file) {
        feature.style.externalGraphic = feature.data.icon;
    }
}

function updateFeatures(layer) {
    for (var i = 0; i < layer.features.length; i++) {
        var currentFeature = layer.features[i];
        if (!currentFeature.data.i9d && !!currentFeature.geometry) {
            currentFeature.data.i9d = true;
            if (currentFeature.geometry.CLASS_NAME === "OpenLayers.Geometry.Point") {
                setIcon(currentFeature);
                currentFeature.data.tTip = currentFeature.data.title;
            } else if (currentFeature.geometry.CLASS_NAME === "OpenLayers.Geometry.LineString") {
                currentFeature.style.strokeWidth = 4;
            }
        }
    }
    i8eListeners();
    layer.redraw();
}

function addSecondaryFeatures(featureList) {
    for (var i = 0; i < featureList.length; i++) {
        
        OpenLayers.Request.issue({
            method: "get",
            url: featureList[i],
            callback: function (r) {
                vectorLayer.addFeatures(gmlParser.read(r.responseText));
                updateFeatures(vectorLayer);
            }
            
            
        });
    
        
        
    }
}

function setButtonTooltip(divID, text) {
    jQuery(divID).mouseover(function () {
        jQuery("#OBSmapPop")[0].innerHTML = "<p class='popTitle'><b>" + text + "</b></p>";
        jQuery("#OBSmapPop").show();
    });

}

function initButton(divID, buttonFunction, buttonToolTip) {
    jQuery(divID).click(buttonFunction);
    setButtonTooltip(divID, buttonToolTip);
    jQuery(divID).mouseout(function () {
        jQuery("#OBSmapPop").hide();
    });
}

function subtleResize() {
    var c = map.getCenter();
    var tlp = new OpenLayers.Pixel(0, 0);
    var otl = map.getLonLatFromPixel(tlp);
    map.updateSize();
    var ntl = map.getPixelFromLonLat(otl);
    var dp = new OpenLayers.Pixel(ntl.x - tlp.x, ntl.y - tlp.y);
    map.pan(dp.x, dp.y, {animate: false});
    map.panToForcedSmooth(c);
    return true;
}

function toggleMapSize() {
    if (jQuery("#map").width() < 400) {
        jQuery("#map").animate({width: "680px"}).animate({height: "472px"}, subtleResize);
        setButtonTooltip("#mBlargeMap", "Shrink map");
    } else {
        jQuery("#map").animate({height: "298px"}).animate({width: "298px"}, subtleResize);
        setButtonTooltip("#mBlargeMap", "Expand map");
    }
}

jQuery(document).ready(function () {
    map = new OpenLayers.Map('map', {controls: [new OpenLayers.Control.MouseDefaults()], units: 'km', restrictedExtent: allBounds});
    map.events.remove("resize");
    map.controls[0].defaultWheelUp = function () {};
    map.controls[0].defaultWheelDown = function () {};
    var mousePos = new OpenLayers.Control.MousePosition();
    map.addControl(mousePos);
    jQuery("#" + mousePos.div.id.replace(/\./g, "\\\\\\\.")).hide();
    map.addLayers([os_planed, vectorLayer]);
    wktParser = new OpenLayers.Format.WKT();
    gmlParser = new OpenLayers.Format.GML();
    var cleanURL = String(document.location).split("#")[0].split("?")[0];
    map.zoomToMaxExtent();
    initButton("#mBzoomIn", function () {
        map.zoomIn();
    }, "Zoom in");
    initButton("#mBzoomOut", function () {
        map.zoomOut();
    }, "Zoom out");
    initButton("#mBlegend", function () {
        jQuery("a[rel*='legend']").lightBox().click();
    }, "Show legend");
    initButton("#mBlargeMap", function () {
        toggleMapSize();
    }, "Expand map");
    map.events.register("mousemove", map, function (e) {
        var cssObj = {left: mousePos.lastXy.x + 16, top: mousePos.lastXy.y};
        jQuery("#OBSmapPop").css(cssObj);
    });
    jQuery("#OBSmapPop").hide();
    var wkt_req = new OpenLayers.Ajax.Request(cleanURL + '/getGeometry', {
        method: "get",
        onComplete: function (response) {
            vectorLayer.addFeatures(wktParser.read(response.responseText), {});
            vectorLayer.features[0].style.graphicZIndex = 0;
            //map.addLayer(vectorLayer); //added here to make MSIE6 play ball
            var b = vectorLayer.features[0].geometry.getBounds();
            map.zoomToExtent(b);
            var featureList = [cleanURL + '/loilayer?bounding_box=' + b.toBBOX(), cleanURL + '/featuresxml', cleanURL + '/picturesxml?BBOX=' + b.toBBOX()];
            addSecondaryFeatures(featureList);
        }
    });
});
