/// <reference path="jquery-1.3.2-vsdoc.js" />




// NOTE NOTE NOTE !

// GolfWeather2009.js is not meant to be used directly by the client - it's needs to be delivered by the RenderScript
// action on the Golf Weather Controller, to subsitute the ASP.NET.HOST variable properly.

// NOTE NOTE NOTE !                    
                      
                      
                                                         
// HELPERS
String.format = function( text )
{                               
    //check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )                            
    {                                                       
        //if there are not 2 or more arguments there?s nothing to replace
        //just return the original text                                  
        return text;                                                     
    }                                                                    
    //decrement to move to the second argument in the array              
    var tokenCount = arguments.length - 2;                               
    for( var token = 0; token <= tokenCount; token++ )                   
    {                                                                    
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ] );
    }
    return text;
};

function parseASPNETMVCDateFormat(dateString) {
    // Since there is no Dates in the JSON spec, MS made the call to return dates in this
    // format: "\/Date(1253556000000)\/"
    // I won't elaborate on why - but this method parses it.
    var cleanedString = dateString.replace("/Date(", "").replace(")/", "");
    var secondsSinceEpoch = parseInt(cleanedString, 10);
    return new Date(secondsSinceEpoch);
}

// HELPERS END

// Customization variables, assigned in <script> tag after include
var weather_golf_club_id;
var custom_weather_image_url;
var custom_wind_direction_image_url;
var custom_temperature_image_url;
var custom_loading_image_url;


// GLOBALS

var IS_IE6 = /MSIE 6/i.test(navigator.userAgent);

var TODAY = new Date();
var TOMORROW = new Date();
var TODAY_PLUS_2 = new Date();
var TODAY_PLUS_3 = new Date();

TOMORROW.setDate(TODAY.getDate() + 1);
TODAY_PLUS_2.setDate(TODAY.getDate() + 2);
TODAY_PLUS_3.setDate(TODAY.getDate() + 3);

// Date.getDay to Swedish string.
var WEEKDAY = new Array();
WEEKDAY[0] = "Sön";
WEEKDAY[1] = "Mån";
WEEKDAY[2] = "Tis";
WEEKDAY[3] = "Ons";
WEEKDAY[4] = "Tor";
WEEKDAY[5] = "Fre";
WEEKDAY[6] = "Lör";

var WEEKDAY_LONG = new Array();
WEEKDAY_LONG[0] = "Söndag";
WEEKDAY_LONG[1] = "Måndag";
WEEKDAY_LONG[2] = "Tisdag";
WEEKDAY_LONG[3] = "Onsdag";
WEEKDAY_LONG[4] = "Torsdag";
WEEKDAY_LONG[5] = "Fredag";
WEEKDAY_LONG[6] = "Lördag";

// YR.NO symbol to Swedish string
var WEATHERTYPE = new Array();
WEATHERTYPE[1] = "Sol";             // Sun
WEATHERTYPE[2] = "Lätt molnigt";      // LightCloud
WEATHERTYPE[3] = "Lätt molnigt";      // PartlyCloud
WEATHERTYPE[4] = "Molnigt";           // Cloud
WEATHERTYPE[5] = "Lätt regn.";      // LightRainSun
WEATHERTYPE[6] = "Lätt regn.";      // LightRainThunderSun
WEATHERTYPE[7] = "Snöblandat regn.";    // SleetSun
WEATHERTYPE[8] = "Snö / Sol";         // SnowSun
WEATHERTYPE[9] = "Lätt regn";       // LightRain
WEATHERTYPE[10] = "Regn";           // Rain
WEATHERTYPE[11] = "Regn / Åska";      // RainThunder
WEATHERTYPE[12] = "Snöblandat regn.";   // Sleet
WEATHERTYPE[13] = "Snö";            // Snow
WEATHERTYPE[14] = "Snö/Åska";       // SnowThunder
WEATHERTYPE[15] = "Dimma";          // Fog

// The JSON response will return a number representing the direction
// This hashtable translates it to a Direction string. 
var DIRECTION = new Array();
DIRECTION[1] = "N";
DIRECTION[2] = "NE";
DIRECTION[3] = "E";
DIRECTION[4] = "SE";
DIRECTION[5] = "S";
DIRECTION[6] = "SW";
DIRECTION[7] = "W";
DIRECTION[8] = "NW";

// The JSON response will return a number representing the timeperiod
// This hashtable translates it to a TimePeriod string. 
var TIMEPERIOD = new Array();
TIMEPERIOD[1] = "Night";
TIMEPERIOD[2] = "Morning";
TIMEPERIOD[3] = "Afternoon";
TIMEPERIOD[4] = "Evening";      

// CONSTANTS END


// GLOBALS
var currentForecast = null;
var isFetching = false;
// GLOBALS END


// Callback when information is downloaded
function onForecastRetrieved(forecast) {

    if (forecast.toString().substring(0, 5) == "ERROR") {
        alert(forecast);
        return;
    }        

    $("#weather-loading").remove();
    
    forecast.Date = parseASPNETMVCDateFormat(forecast.Date);  // Fix the date
    currentForecast = forecast;
    dataBind();    

    // Make the stuff visible again
    $("#weatherContainer").children().css("visibility", "visible");
    $("#weatherContainer").show();
    
    isFetching = false;
    
}

function getForecast(timePeriod, date) {

    if (weather_golf_club_id == undefined) {
        alert("Javascript variable 'golf_club_id' must be defined for GolfWeather2009 to work.");
        return;
    }

    if (isFetching)
        return;
    isFetching = true;
   
    if (date == undefined) {
        if (currentForecast == undefined) {
            alert("Cannot call currentForecast without date parameter unless it has been called once before");
            return false;
        }
        date = currentForecast.Date;
    }

    // Hide the current weather data and show loading icon
    $("#weatherContainer").children().css("visibility", "hidden");
    $("#weatherContainer").css("position", "relative");
    var loadingUrl = "http://golfweather.systeamhalmstad.se:80/Content/Images/ajax-loader.gif";
    if (custom_loading_image_url != undefined)
        loadingUrl = custom_loading_image_url;
    if (IS_IE6)
        loadingUrl = loadingUrl.replace(".png", ".gif");    
    $("#weatherContainer").append(String.format('<img id="weather-loading" src="{0}" style="position:absolute;left:45%;top:50%;display:none" />', loadingUrl));
    $("#weather-loading").fadeIn("slow");

    // Internet Explorer writes out "UTC" instead of GMT in date strings,
    // which ASP.NET MVC ironically does not recognize as a proper date. Fix:
    var consistentUTCDateString = date.toUTCString().replace("UTC", "GMT");

    // must use .getJSON and provide a JSONP callback
    $.getJSON("http://golfweather.systeamhalmstad.se:80/GolfWeather.mvc/GetForecast?jsonpcallback=?",
    {
        gitId: weather_golf_club_id,
        date: consistentUTCDateString,
        timePeriod: timePeriod
    },
    onForecastRetrieved);


    
   
}


// Update the interface with data from currentForecast 
function dataBind() {
    
    // Date / day element
    $("#weather-day").html(
        String.format('{0}&nbsp;<span id="weather-date">{1}/{2}</span></p>',
                        WEEKDAY_LONG[currentForecast.Date.getDay()], // Example: Onsdag
                        currentForecast.Date.getDate(), // Example: 19/9
                        currentForecast.Date.getMonth() + 1) // Example: 9 for sept 
                        // (adding 1 to getMonth() here because it returns 0-11) 
    );

    // Overall weather symbol + precipitation span
    var weatherSymbolUrl = "http://api.met.no/weatherapi/weathericon/1.0/?symbol={0};content_type=image/png";
    if (custom_weather_image_url != undefined)
        weatherSymbolUrl = custom_weather_image_url;
    if (IS_IE6)
        weatherSymbolUrl = weatherSymbolUrl.replace(".png", ".gif");
    weatherSymbolUrl = String.format(weatherSymbolUrl, currentForecast.OverallWeather); // Put the symbol int in
            
    var precipitation = "";
    if (currentForecast.Precipitation != 0)
        precipitation = currentForecast.Precipitation + "mm";
    weatherSymbolImg = String.format('<img title="{0}" src="{1}" /><span id="weather-precipitation">{2}</span>',
            WEATHERTYPE[currentForecast.OverallWeather],
            weatherSymbolUrl,
            precipitation);
    $("#weather-symbol").html(weatherSymbolImg);

    // Temperature symbol and data
    var thermometerUrl = 'http://golfweather.systeamhalmstad.se:80/Content/Images/thermometer.png';
    if (custom_temperature_image_url != undefined)
        thermometerUrl = custom_temperature_image_url;
    if (IS_IE6)
        thermometerUrl = thermometerUrl.replace(".png", ".gif");   

    var temperatureImg = String.format('<img src="{0}" /><span>{1}°C</span>', thermometerUrl, currentForecast.Temperature);
    $("#temperature-symbol").html(temperatureImg);

    // Wind symbol
    var windDirectionUrl = "http://golfweather.systeamhalmstad.se:80/Content/Images/wind_{0}.png";
    if (custom_wind_direction_image_url != undefined)
        windDirectionUrl = custom_wind_direction_image_url;
    windDirectionUrl = String.format(windDirectionUrl, DIRECTION[currentForecast.Wind.Direction]); // Put the direction in (Example: "W")
    if (IS_IE6)
        windDirectionUrl = windDirectionUrl.replace(".png", ".gif");

    var windImg = String.format('<img src="{0}" title="{1}" />{2}m/s',
                                    windDirectionUrl,
                                    DIRECTION[currentForecast.Wind.Direction], 
                                    currentForecast.Wind.Speed);
    $("#wind-symbol").html(windImg); 

    // Activate the correct date selector:
    deactivate("ul.days li"); // deactivate all
    if (currentForecast.Date.getDate() == TODAY.getDate()) 
        activate("#days-today");        
    if (currentForecast.Date.getDate() == TOMORROW.getDate()) 
        activate("#days-tomorrow");
    if (currentForecast.Date.getDate() == TODAY_PLUS_2.getDate()) 
        activate("#days-today-plus-2");
    if (currentForecast.Date.getDate() == TODAY_PLUS_3.getDate()) 
        activate("#days-today-plus-3");
    

    // Activate the correct time period selector:
    deactivate("#time-period-menu li"); // deactivate all
    if (TIMEPERIOD[currentForecast.TimePeriod] == "Morning")
        activate("#time-period-menu-item-morning");
    if (TIMEPERIOD[currentForecast.TimePeriod] == "Afternoon")
        activate("#time-period-menu-item-afternoon");
    if (TIMEPERIOD[currentForecast.TimePeriod] == "Evening")
        activate("#time-period-menu-item-evening");
    
    // Hide passed periods, as the weather data is no longer avaliable.
    $("#time-period-menu li").show(); // Show all first

    if (currentForecast.Date.getDate() == TODAY.getDate()) { 
        if (getNextTimePeriodToday() == "Afternoon")
            $("#time-period-menu-item-morning").hide();

        if (getNextTimePeriodToday() == "Evening") {
            $("#time-period-menu-item-morning").hide();
            $("#time-period-menu-item-afternoon").hide();
        } 
    }
    
    
    
    
        
      
}


// Set up basic HTML Structure inside the weatherContainer div 
function createBasicElements() {

    // <div class="header">
    $("#weatherContainer").append('<div class="header" />');

    // Create date menu

    /* Output XHTML:
    <ul class="days">
      <li id="days-today" class=""></li>
      <li id="days-tomorrow" class="active">
        <a href="#">
          Lör
        </a>
      </li>
      <li id="days-today-plus-2" class="">
        <a href="#">
          Sön
        </a>
      </li>
      <li id="days-today-plus-3" class="">
        <a href="#">
          Mån
        </a>
      </li>
    </ul>
    */
    $("#weatherContainer").hide();
    $("#weatherContainer div.header").append('<ul id="date-menu" class="days" />');   
    
    $("ul.days").append('<li id="days-today" class="active" />');
    $("ul.days").append('<li id="days-tomorrow" class="" />');
    $("ul.days").append('<li id="days-today-plus-2" class="" />');
    $("ul.days").append('<li id="days-today-plus-3" class="" />');
    
    // TODO: Should use IMG tags instead, with weather icons, and proper weekday
    // names on the text
    $("#days-today").append(String.format('<a href="#">{0}</a>&nbsp;', WEEKDAY[TODAY.getDay()] ));
    $("#days-tomorrow").append(String.format('<a href="#">{0}</a>&nbsp;', WEEKDAY[TOMORROW.getDay()]));
    $("#days-today-plus-2").append(String.format('<a href="#">{0}</a>&nbsp;', WEEKDAY[TODAY_PLUS_2.getDay()]));
    $("#days-today-plus-3").append(String.format('<a href="#">{0}</a>', WEEKDAY[TODAY_PLUS_3.getDay()] ));

    // Click events for days menu
    $("#days-today a").click(function() {
        getForecast(getNextTimePeriodToday(), TODAY);
        return false;
    });              


    $("#days-tomorrow a").click(function() {
        getForecast("Afternoon", TOMORROW);
        return false;
    });

    $("#days-today-plus-2 a").click(function() {
        getForecast("Afternoon", TODAY_PLUS_2);
        return false;
    });

    $("#days-today-plus-3 a").click(function() {
        getForecast("Afternoon", TODAY_PLUS_3);
        return false;
    });

    // Create the weather-day element
    /* Output XHTML:         
    <p id="weather-day">
    Lördag
    <span>19/9</span>
    </p>   
    */
    $("#weatherContainer div.header").append('<p id="weather-day">');

    // Create time period menu
    /* Output XHTML  
    <ul id="time-period-menu" class="today">        
      <li id="time-period-menu-item-morning" class="active">
        <a href="#">Förm.</a>
      </li>
      <li id="time-period-menu-item-afternoon">
        <a href="#">Efterm.</a>
      </li>
      <li id="time-period-menu-item-evening">
        <a href="#">Kväll</a>
      </li>
    </ul>
    */

    $("#weatherContainer div.header").append('<ul id="time-period-menu" class="today">');
    $("#time-period-menu").append('<li id="time-period-menu-item-morning"><a href="#">Förm</a></li>');
    $("#time-period-menu").append('<li id="time-period-menu-item-afternoon"><a href="#">Efterm</a></li>');
    $("#time-period-menu").append('<li id="time-period-menu-item-evening"><a href="#">Kväll</a></li>');
    
    // Click events for time period menu
    $("#time-period-menu-item-morning a").click(function() {
        getForecast("Morning");
        return false;
    });
    
    $("#time-period-menu-item-afternoon a").click(function() {
        getForecast("Afternoon");
        return false;
    });

    $("#time-period-menu-item-evening a").click(function() {
        getForecast("Evening");
        return false;
    });


    // Weather data
    /*
    <p id="weather-symbol" class="weather">
        <img title="Sunny" src="http://clubs.golf.se/light/weather/images/icon_3200.gif"/>
        <span>Sunny</span>
    </p>
    */
    $("#weatherContainer").append('<p id="weather-symbol" class="weather">');

    /*
    <p id="temperature-symbol" class="temp">
        <img src="http://clubs.golf.se/light/weather/images/tmp_icon.gif"/>
        10.0°C
    </p>
    */
    $("#weatherContainer").append('<p id="temperature-symbol" class="temp">');

    /*
    <p id="wind-symbol" class="wind">
        <img src="http://clubs.golf.se/light/weather/images/wind_W.gif"/>
        2m/s
    </p>
    */
    $("#weatherContainer").append('<p id="wind-symbol" class="wind">');

}

// Adds class active, removes class inactive.
function activate(selector) {
    $(selector).addClass("active");
    $(selector).removeClass("inactive");
}

// As activate() but reversed.
function deactivate(selector) {
    $(selector).removeClass("active");
    $(selector).addClass("inactive");
}



// Retrieves the time period following the current time period.
function getNextTimePeriodToday() {
    var now = new Date();
    if (now.getHours() < 6)
        return "Morning";
    if (now.getHours() < 12)
        return "Afternoon";
    return "Evening";    
}

function initializeWeather() {


    createBasicElements();
    getForecast(getNextTimePeriodToday(), TODAY);    
    
}


