/*global OpenLayers, jQuery*/
var VLayerName;
var map;
var popLock = false;
var allBounds = new OpenLayers.Bounds(146597,192627,229380,250139);
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 = -11;
        vector_style.graphicYOffset = -32;
        vector_style.graphicHeight = 32;
        vector_style.graphicWidth = 24;

        vector_style.graphicOpacity = 1;
        vector_style.pointRadius = 22;

var    sel_style = OpenLayers.Util.extend({},vector_style);
       sel_style.externalGraphic = "pin1a.png";
var baseOptions = {maxResolution: "auto",
                    resolutions:availableResolutions,
                    projection: 'EPSG:27700',
                    maxExtent: allBounds,
                    transitionEffect: 'resize'};
var    overlayOptions = OpenLayers.Util.extend({},baseOptions);
    overlayOptions.isBaseLayer = false;
    overlayOptions.style = vector_style;
    overlayOptions.rendererOptions = {yOrdering: true};
var vectorLayerV2 = new OpenLayers.Layer.Vector('vectorLayerV2',overlayOptions);

function addSIOPImages(){
    safeURL = String(document.location).split("#")[0].split("?")[0];
    SIOPURL = safeURL+"/picturesxml?BBOX="+map.getExtent().toBBOX();
    insertVirtualLayer("SIOP",SIOPURL);
}
function removeSIOPImages(){
    removeVLayer("SIOP");
}
function generateNameFromURL(url,type){
    return url.split("/").toString();
    }

function popClose(){
    popLock=false;
    jQuery(".popToggle").hide();
    jQuery("#OBSmapPop").hide().removeClass("OBSMapPopActive");
}

function featureClick(){
    if (popLock){
        popClose();
    } else {
        popLock = true;
        jQuery(".popToggle").show();
        jQuery("#OBSmapPop").addClass("OBSMapPopActive");
    }
}
function photoClick(){
    jQuery("a[rel*='lightbox']").lightBox().click();
}

function onFeatureHover(feature){
    if(!popLock){
        thisFeature = feature;
        jQString = "#"+thisFeature.geometry.id.replace(/\./g,"\\\\\\\.");
        if (thisFeature.data.portal_type==="SiopImage"){
            featureTitleText="<img src='"+thisFeature.data.url+"/image_header' />";
            } else {
            featureTitleText = thisFeature.data.title;
        }
        if (thisFeature.data.description){
            featureDescriptionText = thisFeature.data.description;
            } else {
            featureDescriptionText = "";
        }
        if (thisFeature.data.url){
            popLink = "<p class='popToggle'><a href='"+thisFeature.data.url+"'>Read more...</a></p>";
        }else{
            popLink = "";
        }
        //jQuery("#OBSmapPop")[0].innerHTML="<div id='popClose' class='popToggle' onclick='popClose()'></div><p class='popTitle'><b>"+featureTitleText+"</b></p><p class='popToggle'>"+featureDescriptionText+"</p>"+popLink;
        //jQuery(".popToggle").hide();
        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_header' /></div></div>";
            } else {
            jQuery(jQString).click(featureClick);
            jQuery("#OBSmapPop")[0].innerHTML="<div id='popClose' class='popToggle' onclick='popClose()'></div><p class='popTitle'><b>"+featureTitleText+"</b></p><p class='popToggle'>"+featureDescriptionText+"</p>"+popLink;
            jQuery(".popToggle").hide();
        }
        jQuery("#OBSmapPop").show();
    }
}

function onFeatureUnhover(feature){
    if(!popLock){
    jQuery("#OBSmapPop").hide();
    }
}

function addPopupData(VLayerName){
    nFeatures = vectorLayerV2.features.length;
    for (var i =0;i<nFeatures;i++){
        currentFeature = vectorLayerV2.features[i];
        if (currentFeature.data.cfgd !== true){
            currentFeature.data.cfgd = true;
            if (vectorLayerV2.features[i].attributes.description){
                descHTML = "<p>"+vectorLayerV2.features[i].attributes.description+"</p>" ;
            } else {
                descHTML = "";
            }
            currentFeature.data.popupContentHTML =  "<div><h2>"+
                                                    vectorLayerV2.features[i].attributes.title+
                                                    "</h2>"+
                                                    descHTML+
                                                    "<a href='"+
                                                    vectorLayerV2.features[i].attributes.url+
                                                    "'>Read more...</a></div>";
            if (!currentFeature.data.VLayer){
                currentFeature.data.VLayer = VLayerName;
                }
                var fClass = currentFeature.geometry.CLASS_NAME.split(".");
                if (fClass.length > 2 && fClass[2] === "Polygon") {
                    currentFeature.style.fillOpacity = 0.4;
                    currentFeature.style.graphicZIndex = 0;
                    geomString = currentFeature.geometry.components[0];
                    nPoints = geomString.components.length;
                    var xSum = 0;
                    var ySum = 0;
                    for(var j = 0;j<nPoints-1;j++){
                        point = geomString.components[j];
                        xSum += point.x;
                        ySum += point.y;
                        }
                    xPos = xSum/(nPoints-1);
                    yPos = ySum/(nPoints-1);
                    var pFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(xPos,yPos));
                    pFeature.data.popupContentHTML = currentFeature.data.popupContentHTML;
                    pFeature.data.title = currentFeature.data.title;
                    pFeature.data.description = currentFeature.data.description;
                    pFeature.data.url = currentFeature.data.url;
                    pFeature.data.cfgd = true;
                    pFeature.style = OpenLayers.Util.extend(vector_style, {externalGraphic: currentFeature.data.icon});
                    pFeature.style.graphicZIndex = 1;
                    pFeature.data.VLayer = VLayerName;
                    vectorLayerV2.addFeatures([pFeature]);
                }  else if (fClass.length > 2  && fClass[2] === "LineString"){
                    currentFeature.style.fillOpacity = 0.4;
                    currentFeature.style.graphicZIndex = 0;
                    geomPoint = currentFeature.geometry.components[0];

                    xPos = geomPoint.x;
                    yPos = geomPoint.y;
                    var pFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(xPos,yPos));
                    pFeature.data.popupContentHTML = currentFeature.data.popupContentHTML;
                    pFeature.data.title = "Section of walk"; //currentFeature.data.title;
                    pFeature.data.description = currentFeature.data.description;
                    pFeature.data.url = currentFeature.data.url;
                    pFeature.data.cfgd = true;
                    pFeature.style = OpenLayers.Util.extend(vector_style, {externalGraphic: currentFeature.data.icon});
                    pFeature.style.graphicZIndex = 1;
                    pFeature.data.VLayer = VLayerName;
                    vectorLayerV2.addFeatures([pFeature]);
                } else {
                        currentFeature.style.graphicZIndex = 1;
                        if (currentFeature.data.portal_type){
                            currentFeature.style.externalGraphic = "marker-" + currentFeature.data.portal_type+".png";
            }
            }
                }
            }
    vectorLayerV2.redraw();
}

function insertVirtualLayerFromWKT(virtualLayerName,layerSource){
    monitor.queue();
    wktParser = new OpenLayers.Format.WKT();
    wkt_req = new OpenLayers.Ajax.Request(layerSource,{
        method:"get",
        parameters:null,
        onComplete:function(response){
            featureText = response.responseText;
            wktFeature = wktParser.read(featureText);
            lsParts = layerSource.split("/");
            lsName = lsParts[lsParts.length-2];
            wktFeature.data.title = lsName;
            vectorLayerV2.addFeatures(wktFeature,{});
            addPopupData(virtualLayerName);
            vectorLayerV2.redraw();
            monitor.dequeue();
            }
         });
}

function insertVirtualLayer(virtualLayerName,layerSource){
    monitor.queue();
    GMLParser = new OpenLayers.Format.GML();
    req = new OpenLayers.Ajax.Request(layerSource,{
        method:"get",
        parameters:null,
        onComplete:function(response){
            featureText = response.responseText;
            GMLFeature = GMLParser.read(featureText);
            nf = GMLFeature.length;
            vectorLayerV2.addFeatures(GMLFeature,{});
            addPopupData(virtualLayerName);
            vectorLayerV2.redraw();
            monitor.dequeue();
            }
        });
}

function getURLArgs(){
    if (document.location.search){
        BoundsString = document.location.search.split("=")[1];
        rootURL = document.location.toString().split("interactive-map")[0];
        WKTSources = [rootURL+"getGeometry"];
        GMLSources = [rootURL+"loilayer?bounding_box="+BoundsString,rootURL+"featuresxml"];
        mb = new OpenLayers.Bounds.fromString(BoundsString);
        map.zoomToExtent(mb);
        for (var i = 0; i<WKTSources.length;i++){
            insertVirtualLayerFromWKT(generateNameFromURL(WKTSources[i],0),WKTSources[i]);
        }
        for (var j = 0; j<GMLSources.length;j++){
            insertVirtualLayer(generateNameFromURL(GMLSources[j],0),GMLSources[j]);
        }
    } else {
        map.zoomToMaxExtent();
    }
    mapPosition = map.getCenter();
}

function addVLayer(layerName,layerURL,method){
    virtualLayerName = layerName;
    layerSource = layerURL+"/"+method;
    insertVirtualLayer(virtualLayerName,layerSource);
}

function onPopupClose(evt) {
        selectControl.unselect(selectedFeature);
}

function removeVLayer(VLayerName){
 removeList = [];
    for (var i = 0; i<vectorLayerV2.features.length; i++){
        if (vectorLayerV2.features[i].data.VLayer === VLayerName){
            removeList.push(i);
            }
        }
    removeList.reverse();
    for (var j = 0;j<removeList.length;j++){
        vectorLayerV2.features[removeList[j]].destroy();
    }
}

function addbackpackLayer(layerSource){
    backpackLayerName = generateNameFromURL(layerSource);
    addVLayer(backpackLayerName,layerSource,"singleinterpxml");
}

function removebackpackLayer(layerSource){
    var layerName = generateNameFromURL(layerSource);
    removeVLayer(layerName);
}

function initButton(divID,buttonFunction,buttonToolTip){
    jQuery(divID).click(buttonFunction);
    jQuery(divID).mouseover(function(){
        jQuery("#OBSmapPop")[0].innerHTML="<p class='popTitle'><b>"+buttonToolTip+"</b></p>";
        jQuery("#OBSmapPop").show();
        });
    jQuery(divID).mouseout(function(){
        jQuery("#OBSmapPop").hide();
        });
}



function init() {
    OpenLayers.ImgPath ="http://www.experiencepembrokeshire.com/";
    os_planed = new OpenLayers.Layer.WMS("os_planed","http://eryr.net/tilecache", {layers: 'planed-os'}, baseOptions);
    map = new OpenLayers.Map('map', {controls: [new OpenLayers.Control.MouseDefaults()], units: 'km', restrictedExtent: allBounds, eventListeners:{"move": popClose}});
    //map.controls[0].defaultWheelUp = function(){};
    //map.controls[0].defaultWheelDown = function(){};
    map.addLayers([os_planed,vectorLayerV2]);
    hoverControl = new OpenLayers.Control.SelectFeature(vectorLayerV2,{hover: true, onSelect: onFeatureHover, onUnselect: onFeatureUnhover, geometryTypes: ["OpenLayers.Geometry.Point"], selectStyle: sel_style});
    map.addControl(hoverControl);
    hoverControl.activate();
    mousePos = new OpenLayers.Control.MousePosition();
    map.addControl(mousePos);
     map.addControl(new OpenLayers.Control.PanZoomBar());
    jQuery("#"+mousePos.div.id.replace(/\./g,"\\\\\\\.")).hide();
    getURLArgs();

    monitor.indicId = "monitor";
    monitor.init();

    //initButton("#mBzoomIn",function(){map.zoomIn()},"Zoom in");
    //initButton("#mBzoomOut",function(){map.zoomOut()},"Zoom out");
    initButton("#mBlegend",function(){jQuery("a[rel*='legend']").lightBox().click();},"Show map key");

    map.events.register("mousemove", map, function(e) {
        if (!popLock){
            var cssObj = {left: mousePos.lastXy.x+16,top:mousePos.lastXy.y};
            jQuery("#OBSmapPop").css(cssObj);
        }
    });
    jQuery("#OBSmapPop").hide();
    jQuery("#SIOPImagesCheck").click(function(){
                    if (this.checked){
                        addSIOPImages();

                    } else {
                        removeSIOPImages();

                    }
                });
}

var monitor = {

    indicId: null,
    indic: null,

    queueLength: 0,

    init: function () {
        this.indic = jQuery("#" + this.indicId);
        this.refresh();
    },

    queue: function () {
        this.queueLength++;
        this.refresh();
    },

    dequeue: function () {
        this.queueLength--;
        this.refresh();
    },

    refresh: function () {
        if (this.queueLength > 0) {
            if (this.indic.is(":hidden")) {
                this.indic.show();
            }
        } else {
            if (!this.indic.is(":hidden")) {
                this.indic.hide();
            }
        }
    },

    reset: function () {
        this.queueLength = 0;
        this.refresh();
    }

};



jq(document).ready(function(){
    jq('#mapHelp .close').click(function(){
        jq('#mapHelp').fadeOut("fast");

    });
});
