var ratingsprite=new Array(0, 22, 84, 146, 208, 270, 332, 394, 456, 518, 580);
var weathersprite=new Array(0, 196, 134, 72, 10, 382, 320, 320, 258, 0, 444, 258, 506, 568, 10, 630, 692, 692, 382, 754, 0, 72, 0, 754, 382, 0, 816, 878, 940, 1002, 1064, 1002, 1126, 1188, 1188, 1064);
var navail=new Array(10, 1072);

SiteLayer = Class({
    map_: null, activity_: null, imgpath_: null, spritepath_: null, spritear_: null, spritex_: null, spritew_: null, spriteh_: null, iconsize_: null, offset_: null, sfac_: null, sites_: null, offset_:null, json_:null,
    initialize: function(map, activity, iconimg) {
        var that=this;
        this.map_ = map;
        this.activity_ = activity;
        this.imgpath_='/style/img/weathericons/'+iconimg;
        this.spritepath_=(this.activity_==1) ? '/style/img/sprites/weather_sprite.png' : '/style/img/sprites/rating_sprite.png';
        this.spritear_=(this.activity_==1) ? weathersprite : ratingsprite;
        this.spritex_=(this.activity_==1) ? 0 : 20;
        this.spritew_=(this.activity_==1) ? 62 : 82;
        this.spriteh_=(this.activity_==1) ? 1240 : 1168;
        this.iconsize_=(this.activity_==1) ? 42 : 34;
        this.offset_=(this.activity_==1) ? 30 : 17;
        this.sfac_ = 34/42;
        this.sites_ = new Array();
        this.json_ = null;
        this.getSites("0"+g_timeperiod);
        google.maps.event.addListener(map, 'zoom_changed', $.scope(that.displaySites, that));
    },
    getSites: function(day) {
        var that=this;
        var json = $.ajax({
            async: false,
            data : ({'r': "weather", 'a': this.activity_, 'day': day, 'regions': 0 })
        }).responseText;
        this.json_=json;
        that.displaySites();
    },
    displaySites: function() {
        this.deleteSites();
        var count=0;
        var sites = eval("("+this.json_+")");
        for (var item in sites) {
            var bits=sites[item].split(',');
            if (bits[4] <= this.map_.getZoom()) {
                var lon = parseFloat(bits[2]);
                var lat = parseFloat(bits[3]);
                var location = new google.maps.LatLng(lat, lon);
                var icon = this.getIcon(parseInt(bits[5]));
                this.addSite(location, icon, bits[0], bits[1], this.activity_);
            }
            else {
                break;
            }
            count++;
        }
        $("#summary-load").hide();
    },
    addSite: function(location, icon, id, name, activity) {
        var marker = new google.maps.Marker({
            position: location,
            map: this.map_,
            icon: icon,
            zIndex: 1000
            //draggable: true
        });
        this.sites_.push(marker);
        google.maps.event.addListener(marker, 'click', function(e) {
            openSite(name, g_aname);
            //deleteSite(g_aname, id);    
        });
        google.maps.event.addListener(marker, 'mouseover', function(e) { infoDiv(e, name);});
        google.maps.event.addListener(marker, 'mouseout', closeinfo);
        /*google.maps.event.addListener(marker, 'dragend', function() {
            updateSitePosition(g_aname, id, marker.getPosition());
        });*/
    },
    getIcon: function(index) {
        var px, py=0;
        if (index>=0) {
            if (index==0) {
                px=navail[0]*this.sfac_;
                py=navail[1]*this.sfac_;
            }
            else {
                px=this.spritex_*this.sfac_;
                py=this.spritear_[index]*this.sfac_;
            }
            var icon = new google.maps.MarkerImage(
                this.spritepath_,
                new google.maps.Size(this.iconsize_, this.iconsize_),
                new google.maps.Point(px, py),
                new google.maps.Point(this.offset_, this.offset_),
                new google.maps.Size(this.spritew_*this.sfac_, this.spriteh_*this.sfac_)
            );
        }
        else {
            var icon = new google.maps.MarkerImage(
                this.imgpath_,
                null,
                null,
                null, 
                new google.maps.Size(34, 34)
            );
        }
        return icon;
    }, 
    deleteSites: function() {
      if (this.sites_) {
        for (var i in this.sites_) {
            this.sites_[i].setMap(null);
        }
        this.sites_.length = 0;
      }
    }
});

function updateSitePosition(activity, siteid, pos) {
    //ajax and update marker pos
    var that=this;
    var json = $.ajax({
        async: false,
        data : ({'r': "location", 't': "sitepos", 'a': activity, 'siteid': siteid, 'lon': pos.lng(), 'lat': pos.lat() })
    }).responseText;
}

function deleteSite(activity, siteid) {
    //ajax and update marker pos
    var that=this;
    var json = $.ajax({
        async: false,
        data : ({'r': "location", 't': "sitedelete", 'a': activity, 'siteid': siteid })
    }).responseText;
}

RegionLayer = Class({
    map_: null, activity_: null, json_:null,
    initialize: function(map, activity) {
        var that=this;
        this.map_ = map;
        this.activity_ = activity;
        this.regions_ = new Array();
        this.json_ = null;
        this.getRegions(0);
    },
    getRegions: function(day) {
        var that=this;
        var json = $.ajax({
            async: false,
            data : ({'r': "weather", 'a': this.activity_, 'day': day, 'regions': 1 })
        }).responseText;
        this.json_=json;
        that.displayRegions();
    },
    displayRegions: function() {
        var regions = eval("("+this.json_+")");
        for (var item in regions) {
            var bits=regions[item].split(',');
            this.addRegion(bits[0], bits[1], bits[2], bits[3], bits[4], bits[5], bits[6], bits[7], bits[8], this.activity_, item);
        }
    },
    addRegion: function(name, cx, cy, x1, y1, x2, y2, zoom, rating, activity, id) {
        var that=this;
        var sw = new google.maps.LatLng(parseFloat(y1), parseFloat(x1));
        var ne = new google.maps.LatLng(parseFloat(y2), parseFloat(x2));
        var bounds=new google.maps.LatLngBounds(sw, ne);
        var region=new google.maps.Rectangle({
            map: this.map_,
            fillColor: "#666666",
            fillOpacity: 0.1,
            strokeWeight: 1,
            strokeColor: "#ffffff",
            bounds: bounds,
            zIndex: 10
        });
        google.maps.event.addListener(region, 'click', function(e) {
            that.map_.fitBounds(bounds);
            that.map_.setZoom(parseInt(zoom));
            $("#region").val(id);
            getRegionSites(activity, id);
        });
        google.maps.event.addListener(region, 'mouseover', function(e) { if (that.map_.getZoom() < parseInt(zoom)) infoRegion(e, name); });
        google.maps.event.addListener(region, 'mouseout', function (e) { if (that.map_.getZoom() < parseInt(zoom)) closeinfo(); });
    }
});

function openSite(sitename, activity) {
    urlnew='/'+rewriteOutput(activity)+'/'+rewriteOutput(g_cname)+'/'+rewriteOutput(sitename);
    window.location.href=urlnew;
}

function getSunRiseSet(activity, site) {
    $(".sun-loader").show();
    $(".sun").hide();
    $.ajax({
        data : ({'r': "extras", 'a': activity, 't': "sun", 's': site}),
        success : function (resp) {
            if (resp) {
                $(".sun").html(resp);
                $(".sun-loader").hide();
                $(".sun").show();
            }
        }
    });
}

function getSeaTemp(activity, site, sitename) {
    $("#sst-loader").show();
    $("#sst").hide();
    $.ajax({
        data : ({'r': "extras", 'a': activity, 't': "sst", 's': site}),
        success : function (resp) {
            $("#sea-location").html(sitename);
            if (resp) {
                var temp=parseInt(resp);
                if (temp<0) {
                    $("#sea-temp").html("No data available");
                    $("#sea-rec-value").html("");
                }
                else {
                    $("#sst-value").html(temp);
                    $("#sea-rec-value").html(getSeaRec(temp));
                }
            }
            else {
                $("#sea-temp").html("No data available");
            }
            $("#sst-loader").hide();
            $("#sst").show();
        },
        error: function() {
            $("#sea-temp").html("No data available");
            $("#sea-rec-value").html("");
            $("#sst-loader").hide();
            $("#sst").show();
        }
    });
}

function getSeaRec(temp) {
    var tempar=[12,15,18,20,22,100];
    var recar=["5/4 Wetsuit", "4/3 Wetsuit", "3/2 Wetsuit", "Spring Suit", "Shorty", "Boardies and bikinis"];
    var rec="Not available";
    for (var i=0; i<itemp.length; i++) {
        if (temp<=tempar[i]) rec=recar[i];
    }
    return rec;   
}

//Popup info for layer features
function infoDiv(e, str){
    var info = $('#infobox');
    var html="";
    info.html("");
    if (g_swellmap==true) {
        info.swellmap({
            'site': str,
            'activity': g_aname,
            'smaplink': "Click icon for 7 day forecast"
        });
    }
    else {
        var html="";
        html+="<div id='infobox-region'>";
        html+=str;
        html+="<br>";
        html+="<span style='font-size:80%'>Click icon for 7 day forecast</span>";
        html+="</div>";
        info.html(html);
    }
    info.css({'top': mapy+'px', 'left': mapx+'px'});
    info.css('visibility', (str==''? 'hidden':'visible'));
}

function infoRegion(e, str, type) {
    var info = $('#infobox');
    var html="";
    html+="<div id='infobox-region'>";
    html+=str;
    html+="<br>";
    html+="<span style='font-size:80%'>Click to zoom in and view all forecasts</span>";
    html+="</div>";
    info.html(html);
    info.css({'top': mapy+'px', 'left': mapx+'px'});
    info.css('visibility', (str==''? 'hidden':'visible'));
}

//Close info box
function closeinfo(){
    $('#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;
}




