SiteLayer = OpenLayers.Class(OpenLayers.Layer.Markers, {
    id: null,
    activity: null,
    iconpath: null,
    sites: null,
    json: null,
    offset: null,
    initialize: function(id, activity, iconpath) {
        OpenLayers.Layer.Markers.prototype.initialize.apply(this, [id]);
        this.sites = new Array();
        this.id=id;
        this.activity = activity;
        this.iconpath = iconpath;        
        this.getSites(0);
        this.setOpacity(1);
        this.offset=(this.activity==1) ? 0.04 : 0;
    },
    
    getSites: function(day) {
        this.ajaxStart();
        OpenLayers.loadURL(bhref+'ajr.php', '?r=weather&a='+this.activity+'&day='+day, this, this.getJSON);
    },
    
    ajaxStart: function() {
        $j("#ajaxBusy").show();  
    },
    
    ajaxStop: function() {
        $j("#ajaxBusy").hide();
    },
    
    getJSON: function(json) {
        if (!json.responseText) return;
        this.json = json;
        map.events.register("zoomend", this, this.displayMarkers);
        this.displayMarkers();
    },
    
    parseJSON: function(){
        try {
            var sites = eval("("+this.json.responseText+")");
            for (var item in sites) {
                var bits=sites[item].split(',');
                if (bits[4] <= map.zoom) {
                    var lon = parseFloat(bits[2]);
                    var lat = parseFloat(bits[3]);
                    if (map.zoom <= 9) lat+=this.offset;
                    var location = new OpenLayers.LonLat(lon, lat);
                    location = location.transform(proj, map.getProjectionObject());
                    if (bits[6] == 1) {
                        var data={icon:this.getRegionIcon(bits[5]),id:bits[0],name:bits[1],activity:this.activity};
                        this.addRegion(location, data);
                    }
                    else {
                        var data={icon:this.getIcon(bits[5]),id:bits[0],name:bits[1],activity:this.activity};
                        this.addSite(location, data);   
                    }
                }
                else { break; }
            }
        }
        catch(e) {}
        this.ajaxStop();
    },
    
    addSite: function(location, data) {
        var activity = this.activity;
        var site = new OpenLayers.Feature(this, location, data);
        this.sites.push(site);
        var marker = site.createMarker();
        marker.events.register('mouseover', site, function(evt){infoDiv(evt, data.name);});
        marker.events.register('mouseout', site, closeinfo);
        marker.events.register('click', site, function(evt) {siteSelect(data.id, data.name, activity);});
        this.addMarker(marker);
    },
    
    addRegion: function(location, data) {
        var activity = this.activity;
        var map=this.map;
        var site = new OpenLayers.Feature(this, location, data);
        this.sites.push(site);
        var marker = site.createMarker();
        marker.events.register('mouseover', site, function(evt){infoDiv(evt, data.name);});
        marker.events.register('mouseout', site, closeinfo);
        marker.events.register('click', site, function(evt) {
            if(map.zoom <= 5) {
                map.setCenter(location, 9);
                map.zoomTo(9);
            }
            else {
                map.setCenter(location, 5);
                map.zoomTo(5);
            }
        });
        this.addMarker(marker);
    },
    
    displayMarkers: function() {
        if (this.map.zoom<5) map.zoomTo(5);
        this.clearMarkers();
        this.sites.length=0;
        this.parseJSON();
    },
    
    getIcon: function(type) {
        var iconpath=(this.activity==1) ? 'style/img/weathericons/' : 'style/img/';
        iconpath+=(type=="") ? this.iconpath : type;
        var size = new OpenLayers.Size(30,30);
        var icon = new OpenLayers.Icon(iconpath, size);
        $j(icon.imageDiv).css('cursor', 'pointer');
        return icon;
    },
    
    getRegionIcon: function(type) {
        var cat="";
        var iconpath="";
        var zoom=(this.map.zoom<=5) ? "in" : "out";
        if (type) {
            var rating=parseInt(type.substring(0,1));
            if (rating > 6) { cat="g"; }
            else if (rating > 3) { cat="o"; }
            else { cat="b"; }
            iconpath='style/img/'+cat+zoom+'r.png';
        }
        else {
            iconpath='style/img/'+zoom+'.png';    
        }
        var size = new OpenLayers.Size(30,30);
        var icon = new OpenLayers.Icon(iconpath, size);
        $j(icon.imageDiv).css('cursor', 'pointer');
        return icon;
    }
}); 

//image layer class
ImageLayer = OpenLayers.Class(OpenLayers.Layer.Image, {
    initialize: function(id, url, size, options) {
        var imgoptions={isBaseLayer:false,maxResolution:options.maxResolution,minResolution:options.minResolution};
        var maxExtent =  new OpenLayers.Bounds(18067715.978333, -6024072.1185352, 20337508.34, -4028802.0255736);
        OpenLayers.Layer.Image.prototype.initialize.apply(this, [id, url, maxExtent, size, imgoptions]);
    },
    
    CLASS_NAME: "ImageLayer"
});

function openSite(siteid, activity) {
    urlnew='?a='+activity+'&s='+siteid;
    window.location.href=urlnew;
}

function siteSelect(siteid, sitename, activity) {
        var aname=cooksitename="";
        var l_aname=rewriteOutput(g_aname);
        var l_sname=rewriteOutput(sitename);
        $j('#sitefeed').html("<a href='feed/"+l_aname+"/"+l_sname+"'><img src='style/img/feed14.png' /></a>");
        $j('#sitename').html("<a href='"+l_aname+"/"+l_sname+"'>"+sitename+"</a> outlook");
        $j('#detailed').html("<a href='"+l_aname+"/"+l_sname+"'><img src='style/img/detailed.png' /></a>");
        $j('#siteurl').html("<a href='"+l_aname+"/"+l_sname+"'><img src='style/img/detailed.png' /></a>");
        alen=g_aname.length;
        slen=sitename.length;
        if (alen+slen > 22) {
            if (alen > 7) aname=g_aname.substr(0, 6)+"..";
            else aname=g_aname;
            if (slen > 12) cooksitename=sitename.substr(0, 11)+"..";
            else cooksitename=sitename;
        }
        else {
            aname=g_aname;
            cooksitename=sitename;
        }
        $j('.drag-el').attr('rel', l_aname+'|'+aname+'|'+l_sname+'|'+cooksitename);
        getSiteForecast(activity, siteid);
        getSunRiseSet(activity, siteid);
        g_siteid = siteid;
        g_sitename = sitename;
}

function getSiteForecast(activity, site) {
    var summary = $j('#sitesummary')
    summary.hide();
    $j.ajax({
        data : ({'r': "weather", 'a': activity, 's': site}),
        success : function (resp) {
            if (resp) {
                $j('#tablesummary').html(resp);
                var row = $j("#tablesummary tr");
                row.addClass(".row");
                row.bind("click", function(){
                    var link = $j(this).attr("link");
                    window.location.href = link;
                });
                addDayEvs();
            }
            else {
                summary.html(errmsg.fcast);   
            }
            summary.show();
        },
        error : function() {
            summary.html(errmsg.fcast);
            summary.show();
        }
    });
}

function getSunRiseSet(activity, site) {
    $j.ajax({
        data : ({'r': "extras", 'a': activity, 't': "sun", 's': site}),
        success : function (resp) {
            if (resp) {
                $j("#sunrise").html("Sunrise at "+resp.sunrise);
                $j("#sunset").html("Sunset at "+resp.sunset);
            }
        }
    });
}

//Popup info for layer features
function infoDiv(e, str){
    var info = $j('#infobox');
    var html="";
    html+=str;
    html+="<br>";
    html+="<span style='font-size:80%'>Click weather icon to view forecast</span>";
    info.html(html);
    info.css('top', mapy+'px');
    info.css('left', mapx+'px');
    info.css('visibility', (str==''? 'hidden':'visible'));
}

//Close info box
function closeinfo(){  
    $j('#infobox').css('visibility', 'hidden');
}

function haverSine(lon1, lat1, lon2, lat2) {
    var R = 6371; // earths radius in km
    var dLat = (lat2-lat1).toRad();
    var dLon = (lon2-lon1).toRad(); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var distance = R * c;
    return distance;
}

Number.prototype.toRad = function() {
    return this * Math.PI / 180;
}



