googleKey  = "ABQIAAAA-BzylX7kr0ByM9Ti9tlRxxQoBkKyDX7W7yyKde_zS38DMSgtdxReQsgBgEN0GjsoJzHIFGYpixM09w";
// set up weather namespace
$.namespace('globe.weather');

// declaring global variables
globe.weather.regions = new Array();
globe.weather.position = -1;
globe.weather.regions["all"] = {};
globe.weather.counter = 3;
globe.weather.cache = new globe.common.Cache();

// document ready events
$(document).ready(function() {
    // get the 3 weather files and create one global file
    globe.weather.getRegions("can");
    globe.weather.getRegions("usa");
    globe.weather.getRegions("intl");

    // smart search plugin on the weather input box
    $('.weather-input').smartSearch();

    // disable suggest list on click
    $("body").click(function(){
        if ($("#suggest-list").css("display") == "block"){
            $("#suggest-list").hide();
            return false;
        }
    });

    
    $(".weather-input").keyup(function(ev){
        country = $('#country-select').val();
        /*console.log(1);*/
        globe.weather.suggestList(this,ev,country);
    });

    $("#suggets-list-regions ul li a").click(function(){
        $("#suggets-list-regions ul li").each(function(){
            $(this).removeClass("selected");
        });
        $($(this).parents("li")).addClass("selected");
        return false;
    });


    $(".country-click").click(function(){
        $(".country-click").each(function(t){
            $(this).removeClass("selected");
        });
        $(this).addClass("selected");

        $("#city").html("");
        globe.weather.getRegionList(this.href.split("#")[1]);
        return false;
    });

    currentCity = document.location.toString().split("#");

    if (currentCity.length>1){
        if(currentCity[1].length == 8){
            globe.weather.displayCity(currentCity[1],"all");
        }
    }else{
        if ($.cookie("gam.weather.default")){
            globe.weather.displayCity($.cookie("gam.weather.default"),"all");    
        }
    }

    /*if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 1);

        map.openInfoWindow(map.getCenter(),
                   document.createTextNode("Hello, world"));
        //var point = new GLatLng(37.4419,-122.1419);
        //map.addOverlay(new GMarker(point));
        
        //map.setUIToDefault();

    }*/


});

// load province/state list
globe.weather.getRegions = function(country){
    url = globe.conf.publicationUrl + "/static/weather/json/"+country+"_list.json";
    $.getJSON(url, function(json){
        globe.weather.regions[country] = json;
        $.extend(globe.weather.regions["all"],json);
        globe.weather.callback();
    });
};

// function to determine when the 3 main json files finished loading
globe.weather.callback = function() {
    globe.weather.counter--;
    if (globe.weather.counter == 0) {
        $(".country-click").each(function(){
            if ($(this).hasClass("selected")){
                globe.weather.getRegionList(this.href.split("#")[1]);
            }
        });
    }
};






globe.weather.displayCity = function(city,country){
    $("#suggest-list").hide();
    displayDiv = "#city-view";
    errorDiv = "#city-error";
    loadingDiv = "#city-load";
    if (city == 0){
        $(displayDiv).hide();
        $(errorDiv).html("city not found");
        $(errorDiv).show();
    }else{
        $(errorDiv).hide();
        $(loadingDiv).html("loading.......").show();
        var json = globe.weather.cache.get(city);

        if (json == undefined) {
            url = globe.conf.publicationUrl + "/static/weather/json/"+city+".json";
            $.getJSON(url, function(json) {
                globe.weather.loadCity(json);
                globe.weather.cache.set(city, json);
            });
        } else {
            globe.weather.loadCity(json);
        }
    }
};



globe.weather.loadCity = function(json){
    displayDiv = "#city-view";
    loadingDiv = "#city-load";
    
    $(displayDiv+" .current-title").html("Current Conditions");
    $(displayDiv+" .updated").html("Updated: "+json.OBS.DATE);
    $(displayDiv+" .name").html(json.NAME_EN);

    //$(displayDiv+" .remember").html("<a href='#"+json.LOCATIONID+"' class='remember-city'>Remember City</a>");
    $(displayDiv+" .default").html("<a href='#"+json.LOCATIONID+"' class='make-default'>Make Default</a>");

    $(displayDiv+" .curr-image").html("<img src='"+globe.conf.publicationUrl + "/static/weather/images/i"+json.OBS.ICON+".gif' />");
    $(displayDiv+" .temp-curr").html(json.OBS.TEMPERATURE+"&deg;C");
    $(displayDiv+" .cond-curr").html(json.OBS.FORECAST_TEXT_EN);

    $(displayDiv+" #feels-like").html("Feels Like: ");
    if (!json.OBS.WIND_CHILL){
        wc = json.OBS.TEMPERATURE;
    }else {
        wc = json.OBS.WIND_CHILL;
    }
    $(displayDiv+" #feels-like-detail").html(wc+"&deg;C");
    $(displayDiv+" #wind").html("Wind: ");
    $(displayDiv+" #wind-detail").html(json.OBS.WIND_DIR_EN+", "+json.OBS.WIND_SPEED+" km/h");
    $(displayDiv+" #humidity").html("Rel. Humidity: ");
    $(displayDiv+" #humidity-detail").html(json.OBS.REL_HUMIDITY+"%");
    $(displayDiv+" #dewpoint").html("Dewpoint: ");
    $(displayDiv+" #dewpoint-detail").html(json.OBS.DEWPOINT+"&deg;C");
    $(displayDiv+" #pressure").html("Pressure: ");
    $(displayDiv+" #pressure-detail").html(json.OBS.PRESSURE+"kPa");

    if (json.PERIOD){
        forecastHTML = "<h3 class='current-title'>Forecast</h3>";
        for (i=0;i<json.PERIOD.length;i++){
            per = json.PERIOD[i];
            forecastHTML+= "<div class='col'>";
            forecastHTML+= "<p>"+per.NAME_EN+"</p>";
            forecastHTML+= "<p class='for-image'><img src='"+globe.conf.publicationUrl + "/static/weather/images/i"+per.ICON+".gif' /></p>";
            forecastHTML+= "<p class='for-cond'>"+per.FORECAST_TEXT_EN+"</p>";
            forecastHTML+= "<p class='for-detail'>Temp:"+per.TEMPERATURE+"&deg;C</p>";
            forecastHTML+= "<p class='for-detail'>P.O.P:"+per.POP+"</p>";
            forecastHTML+= "<p class='for-detail'>"+per.WIND_DIR_EN+", "+per.WIND_SPEED+" km/h</p>";
            forecastHTML+= "</div>";
        }
        $(displayDiv+" .forecast").html(forecastHTML);
    }else{
        $(displayDiv+" .forecast").html("");
    }

    //var total = json.WEEKDAY.length > 4 ? 4 : json.WEEKDAY.length;
    weekdayCount = 0;
    if (json.WEEKDAY){
        extendedHTML = "<h3 class='current-title'>Extended</h3>";
        for (i=0;i<json.WEEKDAY.length;i++){
            wkd = json.WEEKDAY[i];
            weekdayCount++;
            if (weekdayCount < 5){
                extendedHTML+= "<div class='col'>";
                extendedHTML+= "<p>"+wkd.NAME_EN+"</p>";
                extendedHTML+= "<p class='for-image'><img src='"+globe.conf.publicationUrl + "/static/weather/images/i"+wkd.ICON+".gif' /></p>";
                extendedHTML+= "<p class='for-cond'>"+wkd.FORECAST_TEXT_EN+"</p>";
                extendedHTML+= "<p class='for-detail'>High:"+wkd.HIGH_TEMP+"&deg;C</p>";
                extendedHTML+= "<p class='for-detail'>Low:"+wkd.LOW_TEMP+"&deg;C</p>";
                extendedHTML+= "<p class='for-detail'>P.O.P:"+wkd.POP+"%</p>";
                //extendedHTML+= "<p class='for-detail'>"+wkd.WIND_DIR_EN+", "+wkd.WIND_SPEED_KM+" km/h</p>";
                extendedHTML+= "</div>";
            }
        }
        $(displayDiv+" .extended").html(extendedHTML);
    }else{
        $(displayDiv+" .extended").html("");
    }

    if (json.ALM){
        almanacHTML = "<h3 class='current-title'>Almanac</h3>";
        almanacHTML += "<div  class='col'>";
        almanacHTML += "<p>Normal Low: "+json.ALM.NORMAL_LOW+"&deg;C</p>";
        almanacHTML += "<p>Normal High: "+json.ALM.NORMAL_HIGH+"&deg;C</p>";
        almanacHTML += "</div>";
        almanacHTML += "<div  class='col'>";
        almanacHTML += "<p>Record Low: "+json.ALM.RECORD_LOW+"&deg;C in "+json.ALM.RECORD_LOW_YEAR+"</p>";
        almanacHTML += "<p>Record High: "+json.ALM.RECORD_HIGH+"&deg;C in "+json.ALM.RECORD_HIGH_YEAR+"</p>";
        almanacHTML += "</div>";
        almanacHTML += "<div  class='col'>";
        almanacHTML += "<p>Sunrise at: "+json.ALM.SUNRISE_EN+"</p>";
        almanacHTML += "<p>Sunset at: "+json.ALM.SUNSET_EN+"</p>";
        almanacHTML += "</div>";
        $(displayDiv+" .almanac").html(almanacHTML);
    }else{
        $(displayDiv+" .almanac").html("");
    }
    $(loadingDiv).hide();
    $(displayDiv).show();

    /*$(".remember-city").click(function(){
        globe.weather.rememberCity(this.href.split("#")[1]);
    });*/
    $(".make-default").click(function(){
        globe.weather.makeDefault(this.href.split("#")[1]);
    });
};



globe.weather.rememberCity = function(city){
    if ($.cookie("gam.weather")){
        if ($.cookie("gam.weather").indexOf(city)>-1){
            return;
        }else{
            newValue = $.cookie("gam.weather")+"|"+city;
            $.cookie("gam.weather", newValue, {expires: 365,path: '/'});
        }
    }else{
        $.cookie("gam.weather", city, {expires: 365,path: '/'});
    }
};
globe.weather.makeDefault = function(city){
    if ($.cookie("gam.weather.default")){
        if ($.cookie("gam.weather.default").indexOf(city)>-1){
            return;
        }else{
            $.cookie("gam.weather", city, {expires: 365,path: '/'});
        }
    }else{
        $.cookie("gam.weather.default", city, {expires: 365,path: '/'});
    }
};

/*globe.weather.toggleSelect = function(obj){
    console.log($(obj));
    $($(obj)[0]).addClass("selected");
};*/

globe.weather.getRegionList = function(region){
    regionHTML = "<ul>";
    for (var reg in globe.weather.regions[region]){
        regionHTML += "<li><a href='#"+reg+"' class='region-select'>"+reg+"</a></li>";
    }
    regionHTML += "</ul>";
    $("#subregion").html(regionHTML);
    $(".region-select").click(function(){
        $(".region-select").each(function(){
            $(this).removeClass("selected");
        });
        $(this).addClass("selected");
        globe.weather.getCityList(region,this.href.split("#")[1]);
        return false;
    });
};

globe.weather.getCityList = function(region,subregion){
    subregion = subregion.replace(/%20/g," ");

    cityHTML = "<ul>";
    /*console.log(globe.weather.regions[region][subregion]);*/
    for (var city in globe.weather.regions[region][subregion]){
        cityHTML += "<li><a href='#"+globe.weather.regions[region][subregion][city]+"' class='city-select'>"+city+"</a></li>";
    }
    cityHTML += "</ul>";
    $("#city").html(cityHTML);
    $(".city-select").click(function(){
        $(".city-select").each(function(t){
            $(this).removeClass("selected");
        });
        $(this).addClass("selected")
        globe.weather.displayCity(this.href.split("#")[1],region);
        //return false;
    });
};


// suggest list function
globe.weather.suggestList = function(obj,ev,country){
    if (ev.keyCode == 40){
        if ($("#suggest-list").css("display") == "block"){
            globe.weather.position++;
            globe.weather.highlightCity("down");
        }
    }else if (ev.keyCode == 38) {
        if ($("#suggest-list").css("display") == "block"){
            globe.weather.position--;
            globe.weather.highlightCity("up");
        }
    }else if (ev.keyCode == 13) {
        if ($("#suggest-list").css("display") == "block"){
            if ($("#city-list li.highlight a").length>0){
                window.location = $("#city-list li.highlight a")[0].href;
                $(".weather-input").val(($("#city-list li.highlight a").html().replace("<strong>",'').replace("</strong>",'').split(",")[0]));
                globe.weather.displayCity($("#city-list li.highlight a")[0].href.split("#")[1]);
            }else{
                globe.weather.displayCity(0);
            }
        }else{
            if($(".weather-input").val()!= ""){
                cityId = globe.weather.getCityId($(".weather-input").val());
                globe.weather.displayCity(cityId);
            }
        }
    }else{
        globe.weather.searchCity($(obj).val(),country);
    }
};

globe.weather.getCityId = function(val){
    val = $.trim(val);
    selectedCity = 0;
    var isFound = false;

    for(prov in globe.weather.regions["all"]){
        if (!isFound){
            for (_city in globe.weather.regions["all"][prov]){
                currentCity = _city.toLowerCase();
                if (currentCity == val.toLocaleLowerCase()){
                    selectedCity = globe.weather.regions[country][prov][_city]
                    isFound = true;
                    break;
                }
            }
        }else{
            break;
        }
    }
    return selectedCity;
};

globe.weather.searchCity = function(city,country){
    $("#suggest-list").hide();
    $("#suggest-list .container").html("");
    globe.weather.position = -1;
    html = "";
    if (city != "" || city != " " || city != "  "){
        html = "<ul id='city-list'>";
        var provCount=0;
        var cityCount=0;
        var _cityCount=0;
        var done=false;
        for(prov in globe.weather.regions[country]){
            if (done == false){
                provCount++;                
                for (_city in globe.weather.regions[country][prov]){
                    currentCity = _city.toLowerCase().substring(0,city.length);
                    currentInput = city.toLowerCase();
                    if (currentCity.indexOf(currentInput) > -1){
                        cityCount++;
                        lastClass = "";
                        if (cityCount < 20){
                            displayName = "<strong>"+_city.substring(0,city.length)+"</strong>"+_city.substring(city.length,_city.length);
                            html += "<li><a href='#"+globe.weather.regions[country][prov][_city]+"' class='city-view'>"+displayName+", "+prov+"</a></li>";
                        }else{
                            html += "<li class='last'>...</li>";
                            done = true;
                            break;
                        }

                    }
                }
            }

        }

        html += "</ul>";
        $("#suggest-list .container").html(html);

        $(".city-view").click(function(){
            globe.weather.displayCity(this.href.split("#")[1],country);
            //return false;
        });
        if (html != "<ul id='city-list'></ul>"){
            $("#suggest-list").show();
        }
    }
};



globe.weather.highlightCity = function(direction){
    if (globe.weather.position == $("#city-list li").length){
        globe.weather.position = 0;
    }
    if (globe.weather.position< 0){
        globe.weather.position = $("#city-list li").length-1;
    }
    $("#city-list li").removeClass("highlight");
    $("#city-list li:eq("+globe.weather.position+")").addClass("highlight");
};