//Global JS variables
var map,editmode,options,sitelayer,geocoder;
var mapx,mapy=0;
var g_changecountry=0;
/*****************************************
    Core JQuery funcs for load/unload
******************************************/
$ = jQuery.noConflict();

$(window).load(function() {
    initialize();
});

function initialize() {
    //super fish menu code
    $("#superfish ul.sf-menu").superfish({
        dropShadows: false,
        speed: 'fast'
    });
    
    $("#topmenu ul.sf-top-menu").superfish({
        dropShadows: false,
        speed: 'fast'
    });
    
    $("#region").change(function() {
        changeRegion(g_activity, $(this).val());
    });
    
    $("#country").change(function() {
        changeCountry();
    });
    
    var sumbox = $("#summarybox");
    if (sumbox.length>0) sumbox.val('0'+g_timeperiod);
    $("#summary-load").hide();
    sumbox.change(function() {
        $("#summary-load").show();
        sitelayer.getSites($(this).val());
    });
    $("#find").focus(function(){  
        if($(this).attr("value") == "Enter your location") $(this).attr("value", "");  
    });  
    $("#find").blur(function(){  
        if($(this).attr("value") == "") $(this).attr("value", "Enter your location");  
    });  
    
    $("#findb").click(function() {
        if ($("#find").attr("value")!="") search();
    });
    $("#map").mousemove(function(e){
        mapx = e.pageX;
        mapy = e.pageY;
    });
    $("#find").keypress(function (e) {
        if (e.which == 13) { if ($(this).attr("value")!="") search(); }
    });
    $("#country").val(g_country);
    $("#region").val(g_region);
    if (g_map && !charts)  pageload();
    //autocomplete for search fields
    /*$('#find').autocomplete("/ajr.php", {
        highlight: false,
        width: 200,
        extraParams: {
            r: "location",
            t: "auto",
            a: g_activity
        }
    });*/
    
    if ($("#find").length > 0) {
        $("#find").autocomplete({
            source: function(req, add) {
                $.ajax({
                    data : ({'r': "location", 't': 'auto', 'a': g_activity, 'country': g_country, 'q': req.term}),
                    success: function(data) {
                        var suggestions = data.split("\n");
                        suggestions.pop();
                        //pass array to callback  
                        add(suggestions);  
                    }
                });
            },
            select: function(e, ui) {
                var location=ui.item.value;
                var urlpath="/"+rewriteOutput(g_aname)+"/"+rewriteOutput(g_country)+"/"+rewriteOutput(location);
                window.location.href=urlpath;
            }
        });
    }
    $(".hot-el").click(function() {
        var str=$(this).attr('rel');
        var el=$('.my-weather');
        el.append(makeHotLink(str));
        setCookie_MyWeather("myweather-"+str, str);
        $(".myweather-help").remove();
    });
    $(".el-rm").live("click", function() {
        var cookie=$(this).attr('rel');
        var el=$(this).parent().parent();
        el.remove();
        deleteCookie_MyWeather("myweather-"+cookie);
        return false;
    });
    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
    getCookies_MyWeather();
    if (g_aname) setCookie('defaultactivity', g_aname, 365);
}

$.extend({
    scope: function(fn, scope) {
        return function() {
            return fn.apply(scope, arguments);
        }
    }
});


$.fn.setJCookie = function(value) {
    setCookie($(this[0]).attr("id"), value, 365)
}

$.ajaxSetup({
    url: "/ajr.php",
    type: "POST",
    dataType : 'text json',
    data : ({'country': g_country, 'swellmap': g_swellmap }),
    error : function (xhr, desc, exception) { }
});

//dataType : 'text json',

$(window).unload(function() {
    if (g_activity) pageunload();
});
/*****************************************
    Error msgs
******************************************/
var errmsg = {
    unfound: "Sorry a weather forecast for this location could not be found",
    search: "<p class='alert'>Your location has not been found. Please check the spelling or try a nearby place.</p>",
    fcast: "<br>Sorry, there is temporarily no forecast."
}

/******************************************
    Tool tips
*******************************************/
var tooltips = {
    myweathermain: "<h3>This is for saving your favourite weather locations</h3><h3>Click on a location's <span class='hot-el'></span> icon to add a location to this menu.</h3>"
}

/******************************************
    Map functions
*******************************************/
// Javascript on page load function
function pageload() {
    var centerPos=null;
    var zoom=null;
    var latlng=null;
    var countryChange=parseInt(getCookie('countrychange'));
    
    if ((countryChange==1) || !(getCookie('map-pos-lon'))) {
        zoom = g_zoom;
        latlng = g_latlng;
    }
    else if (getCookie('map-pos-lon')) {
        zoom = parseFloat(getCookie('map-zoom'));
        if (zoom < 5) {
            latlng = g_latlng;
        }
        else {
            var cookieLon = parseFloat(getCookie('map-pos-lon'));
            var cookieLat = parseFloat(getCookie('map-pos-lat'));
            latlng = new google.maps.LatLng(cookieLat, cookieLon);
        }
    }
    var mapOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        mapTypeControl: true,
        navigationControl: true,
        streetViewControl: false,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.ZOOM_PAN
        }
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    var latlngpt=document.createElement('DIV');
    latlngpt.id='latlngpt';
    latlngpt.style.top='8px';
    map.controls[google.maps.ControlPosition.RIGHT_TOP].push(latlngpt);
    google.maps.event.addListener(map, "mousemove", function(pt) { document.getElementById("latlngpt").innerHTML = Math.round(pt.latLng.lng()*1000)/1000+", "+Math.round(pt.latLng.lat()*1000)/1000; });
    if (g_activity > 1) regionlayer = new RegionLayer(map, g_activity);
    sitelayer = new SiteLayer(map, g_activity, g_aicon);
}

function pageunload() {
    if (g_map &&  !charts) {
        var center = map.getCenter();
        setCookie('map-pos-lon', center.lng(), 365);
        setCookie('map-pos-lat', center.lat(), 365);
        setCookie('map-zoom', map.getZoom(), 365);
    }
    setCookie('countrychange', g_changecountry, 365);
}

function setCookie(c_name, value, expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+"; path=/";
}

function setCookie_MyWeather(id, str) {
    // seperated string -> aid|aname|sid|sname
    setCookie(id, str, 365);
}


function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        } 
    }
    return "";
}

function getCookies_MyWeather() {
    var check_name="myweather";
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    var el=$('.my-weather');
    for ( i = 0; i < a_all_cookies.length; i++ ) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        // if the extracted name matches passed check_name
        if ( cookie_name.indexOf(check_name)!=-1 ) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 ) {
                    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            el.append(makeHotLink(cookie_value));
        }
        a_temp_cookie = null;
        cookie_name = '';
        cookie_value = '';
    }
    if ( !b_cookie_found ) {
        el.append("<li class='myweather-help'>"+tooltips.myweathermain+"</li>");
    }
}

function deleteCookie_MyWeather(id) {
    setCookie(id, "", -1);
}

function makeHotLink(value) {
    var ar = new Array();
    ar=value.split("/", 3);
    var textlink=rewriteInput(ar[0])+" > "+rewriteInput(ar[1])+" > "+rewriteInput(ar[2]);
    return "<li><a href='/"+value+"' title='"+textlink+"' rel='"+value+"'><span class='el-rm ' rel='"+value+"' title='Delete bookmark'></span>"+textlink+"</a></li>";
}



function rewriteOutput(output) {
    var rewrite='/';
    if (output) rewrite=output.replace(/ /g, '-');
    return rewrite.toLowerCase();
}

function rewriteInput(input) {
    var rewrite='/';
    if (input) rewrite=input.replace(/-/g, ' ');
    return rewrite;
}

/****************************************************
    Search site functions
****************************************************/
function search() {
    $("#searchlist").html("<img src='/style/img/ajax-loader.gif'>");
    var site = $('#find').val();
    if (site.length > 0) {
        $.ajax({
            data : ({'r': "location", 't': 'search', 'a': g_activity, 's': site}),
            success : function(json) {
                displaySiteResults(json, true);
            }
        });
    }
}

function displaySiteResults(sites, search) {
    var sitecount=0;
    var list = (search) ? $('#searchlist') : $('#sitelist');
    list.show();
    list.html("");
    var str="";
    if (sites) {
        for (var item in sites) {
            var fontsize = cloudFontSize(sites[item].views);
            if (g_map) {
                if (g_activity==2) {
                
                }
                else {
                    str = " <a style='font-size: "+fontsize+"px; margin-left: 6px;' title='See detailed 7 day forecast' href='/"+rewriteOutput(g_aname)+"/"+rewriteOutput(g_cname)+"/"+rewriteOutput(sites[item].name)+"'>  "+sites[item].name+"  </a> ";   
                }
                list.append(str);
            }
            else {
                var urlpath=rewriteOutput(g_aname)+"/"+rewriteOutput(g_cname)+"/"+rewriteOutput(sites[item].name);
                list.append(" <a style='font-size: "+fontsize+"px; margin-left: 6px;' title='See detailed 7 day forecast' href='/"+urlpath+"'>  "+sites[item].name+"  </a> ");   
            }
            sitecount++;
        }
        if (g_map && sitecount==1) {   
            map.setCenter(new google.maps.LatLng(sites[item].lat, sites[item].lon));
            map.setZoom(10);
        }
        else if (sitecount==1) {
            urlnew='/'+rewriteOutput(g_aname)+'/'+rewriteOutput(g_cname)+'/'+rewriteOutput(sites[item].name);
            window.location.href=urlnew;   
        }
    }
    else {
        list.html("Your location could not be found. Check your spelling or try a nearby location.");
    }
}

function cloudFontSize(views) {
    var i = parseInt(views);
    fontSize = Math.ceil(10+(Math.min(1, (i/100))*6));
    return fontSize;
}

function changeCountry() {
    g_changecountry=1;
    setCookie('country', $("#country").val(), 365);
    var urlnew=rewriteOutput("/"+g_aname);
    window.location.href=urlnew;
}

function updateRegions(activity, country) {
    var html="";
    if (country) {
        $.ajax({
            data : ({'r': "location", 't': 'country_regions', 'a': activity, 'country': country}),
            success : function (json) {
                $('#region')[0].options.length = 0;
                html="<option value=''>Select an area</option>";           
                for (var item in json) { html+="<option value='"+item+"'>"+json[item].name+"</option>";}
                $('#region').html(html);
            }
        });
    }
}

function changeRegion(activity, region) {
    if (region) {
        if (g_map) {
            var zoom=9;
            $.ajax({
                data : ({'r': "location", 't': 'region', 'a': activity, 'siteid': region}),
                success : function (json) {
                    zoom=(charts) ? 8 : parseInt(json.zoom);
                    if (json.y1) {
                        var sw = new google.maps.LatLng(json.y1, json.x1);
                        var ne = new google.maps.LatLng(json.y2, json.x2);
                        var bounds=new google.maps.LatLngBounds(sw, ne);
                        map.fitBounds(bounds);
                        map.setZoom(zoom);
                    }
                    else {
                        map.setCenter(new google.maps.LatLng(json.lat, json.lon));
                        map.setZoom(parseInt(zoom));
                    }
                }
            });
        }
        getRegionSites(activity, region);
    }
    else {
        if (g_map) {
            $('#sitelist').html("");
            map.setCenter(g_latlng);
            map.setZoom(g_zoom);
        }
    }
}

function getRegionSites(activity, region) {
    var list=$("#sitelist");
    if (g_chart_activity > 0) activity=g_chart_activity;
    list.html("<img src='/style/img/ajax-loader.gif'>");
    $.ajax({
        data : ({'r': "location", 't': 'sites', 'a': activity, 'siteid': region}),
        success : function (resp) {
            displaySiteResults(resp);
        }
    });
}


