﻿﻿var forecasttype = { Overview: 'oversiktsver', Weekend: 'helg', Hourly: 'timefortime', OverviewPage: 'oversikt', Season: 'sesong'};
var diagramtype = { Precipitation: 'nedborkart', Radar: 'radar', Satellitt: 'satellitt', Climate: 'klima', GoogleMap: 'kart' };
var hourlymode = { Table: 'table', Chart: 'chart' };
var seasonmode = { Pollen: 'pollen', BathTemperature: 'bathtemperature', UVRays: 'uv' };
var lists = { jsonData: {}, skySymbolsText: {}, windSymbolSpeedText: {}, windSymbolDirectionText: {} };
var variables = { selectedForecastDayIndex: 0, hoveredDayIndex: 0, currentDayGroupID: 0, currentHourlyForecastMode: hourlymode.Table, currentSeasonForecastMode: '', currentSelectedDayID: 0, currentForecastMode: forecasttype.OverviewPage, userInteraction: false, chartInteraction: false };

//function call on page load
function pageLoad() {
    $.getdata.initial();
    $.initialize.weatherpage();
    //setContextMenuLinks();
}

//public functions
$.initialize =
{
    seasonmenu: function() {
        $('div.season-panel').hide().eq(0).show();
        $('div.season-forecast ul').find('li.highlight').removeClass('highlight').end().find('li:first').addClass('highlight');

        $('a.season-menu').click
        (
            function() {
                $index = $('a.season-menu').index(this);
                $('div.season-panel').hide().eq($index).show();
                $('li.highlight').removeClass('highlight');
                $(this).parent().addClass('highlight');
            }
        );
    },

    weatherpage: function() {
        switch (variables.controlName) {
            case forecasttype.OverviewPage:
                $.initialize.overviewPage();
                break;
            case forecasttype.Overview:
                $.initialize.overview();
                break;
            case forecasttype.Weekend:
                $.initialize.weekend();
                break;
            case forecasttype.Hourly:
            case forecasttype.Chart:
            case forecasttype.Table:
                $.initialize.hourbyhour();
                break;
            case forecasttype.Season:
            case forecasttype.Pollen:
            case forecasttype.BathTemperature:
            case forecasttype.UVRays:
                $.initialize.season();
                break;
        }
    },

    overview: function() {
        $('div.forecastDayDetail').click
        (
           function() {
        //selected forecastday index
        var options = { selectedForecastDayIndex: $('div.forecastDayDetail').index(this), userInteraction: true };
               //function to make highlight selected day
               $(this).highlightforecastdayOverview(options);
           }
        );
        $.initialize.dayevent();
        $.firstday.overview();
    },

    overviewPage: function() {
        $.initialize.overview();
        $.initialize.seasonmenu();
    },

    weekend: function() {
        $('div.forecastDayDetail').click
        (
           function() {
               //selected forecastday index
               var options = { selectedForecastDayIndex: $('div.forecastDayDetail').index(this) };
               //function to make highlight selected day
               $(this).highlightforecastdayWeekend(options);
           }
        );

        $.extend(variables, { weekendForecastDayIndex: 0 });
        $.initialize.dayevent();
        $.firstday.weekend();
    },

    hourbyhour: function() {
        $('div.hourlyForecastDayDetail').click
        (
           function() {
               //selected forecastday index
        var options = { selectedForecastDayIndex: $('div.hourlyForecastDayDetail').index(this), userInteraction: true };

               switch (variables.currentHourlyForecastMode) {
                   case hourlymode.Table:
                       //function to make highlight selected day
                       $(this).highlightforecastdayHourlytable(options);
                       break;
                   case hourlymode.Chart:
                       $.extend(variables, { chartInteraction: true});
                       //function to make highlight selected group day
                       $(this).highlightforecastdayHourlychart(options);
                       break;
               }
           }
        );

        $('div.notSelectedHourlyForecastDay').hover
        (
          function() {
              if ($('div.notSelectedHourlyForecastDay').index(this) == -1) return;

              $.extend(variables, { currentDayGroupID: parseInt($('div.hourlyForecastDay').index($(this).parent()) / 3) });
              $.extend(variables, { hoveredDayIndex: variables.currentDayGroupID * 3 });

              switch (variables.currentHourlyForecastMode) {
                  case hourlymode.Table:
                      $(this).find('div.forecastDayDate').css({ "color": '#000' });
                      break;
                  case hourlymode.Chart:
                      $(this).hoverChartDaybox("#000");
                      break;
              }
          },

          function() {
              switch (variables.currentHourlyForecastMode) {
                  case hourlymode.Table:
                      $(this).find('div.forecastDayDate').css({ "color": '#B3B3B3' });
                      break;
                  case hourlymode.Chart:
                      $(this).hoverChartDaybox("#b3b3b3");
                      break;
              }
          }
        );

        $('div.hourlytable').click
        (
           function() {
               $.initialize.hourlytable();
           }
        );

        $('div.hourlychart').click
        (
            function() {
                $.initialize.hourlychart();
            }
        );

        variables.currentHourlyForecastMode == hourlymode.Chart ? $.initialize.hourlychart() : $.initialize.hourlytable();
    },

    hourlytable: function() {
        $.show.hourlycontrol('icons/hourly_selected_tablebutton.png', 'icons/hourly_chartbutton.png', true);
    },

    hourlychart: function() {
        $.show.hourlycontrol('icons/hourly_tablebutton.png', 'icons/hourly_selected_chartbutton.png', false);
    },

    season: function() {
        switch (variables.currentSeasonForecastMode) {
            case seasonmode.BathTemperature:
                $("div.seasonforecast-bathtemperature").show();
                break;
            case seasonmode.Pollen:
                $("div.seasonforecast-pollen").show();
                break;
            case seasonmode.UVRays:
                $("div.seasonforecast-uv").show();
                break;
            default:
                $("div[class ^= 'seasonforecast']").show();
                break;
        }
    },

    dayevent: function() {
        $('div.notSelectedForecastDayDetail').hover
        (
           function() {
               $(this).hoverForecastDaybox("#FFFFFF 1px solid", "#DAE9FF");
           },
           function() {
               $(this).hoverForecastDaybox("#E3E3E3 1px solid", "#FFFFFF");
           }
        );

        $('div.notSelectedForecastDayDetail').click
        (
           function() {
               $(this).clickForecastDaybox("#E3E3E3 1px solid", "#FFFFFF");
           }
        );
    }
};

$.fn.extend(
{
    //function to highlight Overview forecastday
    highlightforecastdayOverview: function(options) {
        $.extend(variables, options);

        //remove css from last selected forecastday and its date
        $('div.selectedForecastDay').addClass('notSelectedForecastDay').removeClass('selectedForecastDay').find('div.selectedForecastDayDetail').addClass('notSelectedForecastDayDetail').removeClass('selectedForecastDayDetail').find('div.forecastDaySelectedDate').addClass('forecastDayDate').removeClass('forecastDaySelectedDate').css('border-bottom', "#E3E3E3 1px solid").end().end().parent().find('div.forecastDayArrow').empty();

        //highlight slected forecastday & date
        this.parent().addClass('selectedForecastDay').removeClass('notSelectedForecastDay').find('div.notSelectedForecastDayDetail').addClass('selectedForecastDayDetail').removeClass('notSelectedForecastDayDetail').find('div.forecastDayDate').addClass('forecastDaySelectedDate').removeClass('forecastDayDate').end().end().parent().find('div.forecastDayArrow').html(variables.arrowHTML);

        //function to show timesteps for selected forecastday
        $.show.timesteps(variables);
        variables.userInteraction ? document.location.hash = "dag=" + variables.selectedForecastDayIndex : null;
        setContextMenuLinks();
    },

    //function to highlight Weekend forecastday
    highlightforecastdayWeekend: function(options) {
        var settings = $.extend({}, variables, options);

        //find weekend forecastday indexes
        $availableWeekendForecasts = $('div.forecastDayDetail').length;
        $dayIndex = (6 - $availableWeekendForecasts) + settings.selectedForecastDayIndex;
        $index = parseInt($dayIndex / 3);

        //remove css from last selecte forecastday and its date
        $('div.selectedForecastDay').addClass('notSelectedForecastDay').removeClass('selectedForecastDay').find('div.selectedForecastDayDetail').addClass('notSelectedForecastDayDetail').removeClass('selectedForecastDayDetail').find('div.forecastDaySelectedDate').addClass('forecastDayDate').removeClass('forecastDaySelectedDate').css('border-bottom', "#E3E3E3 1px solid").end().end().parent().find('div.forecastDayArrow').empty();

        //highlight slected forecastday & date
        this.parent().addClass('selectedForecastDay').removeClass('notSelectedForecastDay').find('div.notSelectedForecastDayDetail').addClass('selectedForecastDayDetail').removeClass('notSelectedForecastDayDetail').find('div.forecastDayDate').addClass('forecastDaySelectedDate').removeClass('forecastDayDate').end().end().parent().find('div.forecastDayArrow').html(variables.arrowHTML);

        //highlight selected weekend label
        $('div.weekendSelectedText').addClass('weekendText').removeClass('weekendSelectedText').parent().find('div.weekendTextSelectedArrow').addClass('weekendTextArrow').removeClass('weekendTextSelectedArrow');
        $('div.weekendText').eq($index).addClass('weekendSelectedText').removeClass('weekendText').parent().find('div.weekendTextArrow').addClass('weekendTextSelectedArrow').removeClass('weekendTextArrow');

        //function to show timesteps for selected forecastday
        $.show.timesteps(settings);
    },

    //function to highlight Hourlytable forecastday
    highlightforecastdayHourlytable: function(options) {
        $.extend(variables, options);

        //remove css from last selecte forecastday and its date
        $('div.selectedHourlyForecastDay').css({ 'border-left': '#FFF 2px solid', 'border-right': '#FFF 2px solid' }).addClass('notSelectedHourlyForecastDay').removeClass('selectedHourlyForecastDay').find('div.forecastDaySelectedDate').css({ "color": "#b3b3b3" }).addClass('forecastDayDate').removeClass('forecastDaySelectedDate').end().parent().find('div.hourlyForecastDayArrow').empty().css("background", "url(null)");

        //highlight slected day and date
        this.parent().addClass('selectedHourlyForecastDay').removeClass('notSelectedHourlyForecastDay').css({ 'border-left': '#FF9B46 2px solid', 'border-right': '#FF9B46 2px solid' }).find('div.forecastDayDate').addClass('forecastDaySelectedDate').removeClass('forecastDayDate').css({ "background": "#FFFFFF", "color": "#000" }).end().parent().find('div.hourlyForecastDayArrow').css("background", "url(" + variables.themePath + 'icons/hourlydate_selectedbottom.png' + ") top repeat-x").html(variables.hourlyArrowHTML);

        //function to show timesteps for selected forecastday
        $.show.timesteps(variables);
        variables.userInteraction ? document.location.hash = "dag=" + variables.selectedForecastDayIndex : null;
        setContextMenuLinks();
    },

    //function to highlight Hourlychart forecastday
    highlightforecastdayHourlychart: function(options) {
    $.extend(variables, options, { currentDayGroupID: parseInt(options.selectedForecastDayIndex / 3)});
        $.extend(variables, { selectedForecastDayIndex: variables.currentDayGroupID * 3 });
        $('div.selectedHourlyForecastDay').eq(0).css('border-left', '#FFF 2px');
        $('div.selectedHourlyForecastDay').eq(2).css('border-right', '#FFF 2px');
        //$('div.notSelectedHourlyForecastDay').css('border','#FFF 2px solid');

        //remove css from last selecte forecastday
        $('div.selectedHourlyForecastDay').addClass('notSelectedHourlyForecastDay').removeClass('selectedHourlyForecastDay').find('div.forecastDaySelectedDate').css({ "color": "#b3b3b3" }).addClass('forecastDayDate').removeClass('forecastDaySelectedDate').end().parent().find('div.hourlyForecastDayArrow').empty().css("background", "url(null)");

        //highlight slected forecastday   
        for (var i = 0; i < 3; i++) {
            $('div.notSelectedHourlyForecastDay').eq(variables.selectedForecastDayIndex + i).addClass('selectedHourlyForecastDay').find('div.forecastDayDate').addClass('forecastDaySelectedDate').removeClass('forecastDayDate').css({ "background": "#FFFFFF", "color": "#000000" }).end().parent().find('div.hourlyForecastDayArrow').css("background", "url(" + variables.themePath + 'icons/hourlydate_selectedbottom.png' + ") top repeat-x");
            (i == 1) ? $('div.hourlyForecastDayArrow').eq(variables.selectedForecastDayIndex + i).html(variables.hourlyArrowHTML) : null;
        }

        $('div.selectedHourlyForecastDay').removeClass('notSelectedHourlyForecastDay');
        $('div.selectedHourlyForecastDay').eq(0).css({ 'border-right': '0px', 'border-left': '#FF9B46 2px solid' });
        $('div.selectedHourlyForecastDay').eq(1).css({ 'border-left': '0px', 'border-right': '0px' });
        $('div.selectedHourlyForecastDay').eq(2).css({ 'border-right': '#FF9B46 2px solid', 'border-left': '0px' });

        //function to show the meteogram
        $.show.chart();
        
        
        var url = document.location.href;
        var dayindex = url.indexOf("dag=") != -1 ? parseInt(url.substr(url.indexOf("dag=") + 4)) : 0;
        $.extend(variables, { currentSelectedDayID: dayindex });
        variables.userInteraction ? document.location.hash = "dag=" + (variables.chartInteraction ? variables.selectedForecastDayIndex : variables.currentSelectedDayID) : null;
    },

    hoverForecastDaybox: function(dayboxlinecolor, background) {
        if (this.hasClass('selectedForecastDayDetail')) return;
        this.css('background', background).find("div:not(.forecastDayWindSymbolDetail, .forecastTimestep)").css("border-bottom", dayboxlinecolor);
    },

    clickForecastDaybox: function(dayboxlinecolor, background) {
        this.css('background', background).find("div:not(.forecastDayWindSymbolDetail, .forecastTimestep)").css("border-bottom", dayboxlinecolor).end().find('.forecastDayDate').css("border-bottom", "#F4801F 1px solid");
    },

    hoverChartDaybox: function(color) {
        for (var i = 0; i < 3; i++) {
            $('div.hourlyForecastDayDetail').eq(variables.hoveredDayIndex + i).find('div.forecastDayDate').css({ "color": color });
        }
    }
});


$.show =
{
    timesteps: function(options) {
        $.timestep.showDetail(options);
    },

    chart: function() {
        switch (variables.currentDayGroupID) {
            case 0:
                writePlot0();
                break;
            case 1:
                writePlot1();
                break;
            case 2:
                writePlot2();
                break;
        }
    },

    hourlycontrol: function(tableicon, charticon, istable) {
        $('div.hourlytable').css({ 'background': 'url(' + variables.themePath + tableicon + ')', 'cursor': istable ? 'default' : 'pointer' });
        $('div.hourlychart').css({ 'background': 'url(' + variables.themePath + charticon + ')', 'cursor': istable ? 'pointer' : 'default' });

        $('#timesteps').css("display", istable ? "block" : "none");
        $('#timechart').css("display", istable ? "none" : "block");
        variables.currentHourlyForecastMode = istable ? hourlymode.Table : hourlymode.Chart;
        istable ? $.firstday.hourlytable() : $.firstday.hourlychart();
    },

    hilightmenu: function() {
        $('div.context-menu ul li.active').removeClass('active');
        $('div.context-menu ul li').find('a[name=' + variables.controlName + ']').parent().addClass('active');
    },

    onchangemenu: function() {
        $.show.hilightmenu(); 
    }
};

$.firstday =
{
    overview: function() {
    $.extend(variables, { selectedForecastDayIndex: variables.currentSelectedDayID, currentForecastMode: forecasttype.OverviewPage });
        $('div.forecastDayDetail').eq(variables.selectedForecastDayIndex).highlightforecastdayOverview(variables);
    },

    weekend: function() {
    $.extend(variables, { selectedForecastDayIndex: 0, currentForecastMode: forecasttype.Weekend });
        $('div.forecastDayDetail').eq(variables.weekendForecastDayIndex).highlightforecastdayWeekend(variables);
    },

    hourlytable: function() {
    $.extend(variables, { selectedForecastDayIndex: (variables.chartInteraction ? variables.selectedForecastDayIndex : variables.currentSelectedDayID), currentForecastMode: forecasttype.Hourly });
        $('div.hourlyForecastDayDetail').eq(variables.selectedForecastDayIndex).highlightforecastdayHourlytable(variables);
    },

    hourlychart: function() {
    $.extend(variables, { currentForecastMode: forecasttype.Hourly });
        $('div.hourlyForecastDayDetail').eq(variables.selectedForecastDayIndex).highlightforecastdayHourlychart(variables);
    }
};

$.getdata =
{
    menuname: function() {
        try {
            return $('div.context-menu ul li.active a')[0].innerHTML;
        }
        catch (e) { return ''; }
    },

    initial: function() {
        var url = document.location.href;
        var dayId = parseInt(url.substr(url.indexOf("dag=") + 4));
        variables.currentSelectedDayID = url.indexOf("dag=") != -1 ? (dayId > 8 ? 8 : (isNaN(dayId) ? 0 : dayId)) : 0;
        url = (url.indexOf("#") != -1) ? (url.substr(0, url.indexOf("#")) != "" ? url.substr(0, url.indexOf("#")) : url) : (url.substr(0, url.indexOf("?")) != "" ? url.substr(0, url.indexOf("?")) : url);
        //url = (url.indexOf('modules') != "-1") ? url.substr(0, url.indexOf("?")) : url;
        url = url.substr(url.lastIndexOf('/') + 1).toLowerCase();

        $.extend(forecasttype, diagramtype, hourlymode, seasonmode);
        $.extend(variables, { isRequestForecastType: false });

        switch (url) {
            case forecasttype.Season:
            case forecasttype.Precipitation:
            case forecasttype.Radar:
            case forecasttype.Satellitt:
            case forecasttype.Climate:
            case forecasttype.GoogleMap:
                $.extend(variables, { controlName: url });
                break;
            case forecasttype.OverviewPage:
            case forecasttype.Overview:
            case forecasttype.Weekend:
            case forecasttype.Hourly:
                $.extend(variables, { controlName: url, isRequestForecastType: true});
                break;
            case forecasttype.Table:
            case forecasttype.Chart:
                $.extend(variables, { controlName: forecasttype.Hourly, currentHourlyForecastMode: url, isRequestForecastType: true});
                break;
            case forecasttype.Pollen:
            case forecasttype.BathTemperature:
            case forecasttype.UVRays:
                $.extend(variables, { controlName: forecasttype.Season, currentSeasonForecastMode: url, isRequestForecastType: false});
                break;
            default:
                $.extend(variables, { controlName: forecasttype.OverviewPage, isRequestForecastType: true});
                break;
        }

        if (variables.isRequestForecastType) {
        try{
            var jsonObject = Sys.Serialization.JavaScriptSerializer.deserialize($(".dayForecastsDataField").find(":nth-child(1)").get(0).value);

            $.extend(lists, { skySymbolsText: jsonObject[0], windSymbolDirectionText: jsonObject[1], windSymbolSpeedText: jsonObject[2], jsonData: jsonObject[3] });
            $.extend(variables, { themePath: jsonObject[4], timeLabel: jsonObject[5], precLabel: jsonObject[6], currentCulture: jsonObject[7] });
            $.extend(variables, { arrowHTML: "<img class='forecastDaySelectedBottom' src = '" + variables.themePath + 'icons/daybox_selectedbottom.png' + "'/>", hourlyArrowHTML: "<img class='hourlyForecastDaySelectedBottom' src = '" + variables.themePath + 'icons/hourlydate_selectedbottom_arrow.png' + "'/>" });
            }
            catch(e)
            {
            }
        }        
        $.show.onchangemenu();
    }
};

String.prototype.toProperCase = function() {
    return this.toLowerCase().replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); });
}

String.prototype.findPlaceName = function() {
    var placename = this.indexOf('modules') != "-1" ? this.substr(this.indexOf('#') + 1) : this.substr(this.lastIndexOf('vaer/') + 5);
    placename = placename.indexOf('location') != "-1" ? placename.substring(placename.indexOf('=') + 1) : placename;
    return placename.replace("%20", " ").toProperCase();
}

function setContextMenuLinks()
{
    if(variables.currentForecastMode == forecasttype.OverviewPage || variables.currentForecastMode == forecasttype.Hourly)
    {
        $(".link-context-menu").each(function(i){
            setContextMenuItem(this);
        });
    }
}

function setContextMenuItem(menuLink) {
    var routeName = menuLink.name;
    var routePath = menuLink.href;
    var hashIndex = routePath.indexOf('#');
    
    if(hashIndex > 0)
        routePath = routePath.substring(0,hashIndex);
    
    variables.currentSelectedDayID = 0;
    
    if (routeName == forecasttype.OverviewPage || routeName == forecasttype.Hourly) {
        variables.currentSelectedDayID = variables.selectedForecastDayIndex;
    }

    menuLink.href = (routeName == forecasttype.OverviewPage || routeName == forecasttype.Hourly) ? (variables.currentSelectedDayID != 0 ? routePath + "#dag=" + variables.currentSelectedDayID : routePath) : routePath;
}