﻿Ext.onReady(function() 
{  
    new TwentyFour.Scripts.Weather.ForecastSelector();
    $(_ddlRegionId).on('change',populateCities);    
    $('btnGo').on('click',validateGo);
    updateCityInfo(_cityName);
    updateDateInfo(new Date());
    startClock();
});

function updatePage()
{
    var ddlCity = $(_ddlCityId).dom;
    updateTopInfo(ddlCity.value, ddlCity.options[ddlCity.selectedIndex].text);
}

function updateTopInfo(selectedCityId, selectedCityName)
{
    updateCityInfo(selectedCityName);
    updateDateInfo(new Date());
    
    _cityId = selectedCityId;   
    $('verticalMenu').update('');
    new TwentyFour.Scripts.Weather.ForecastSelector();
}

function updateCityInfo(cityName)
{       
    $('cityInfo').update('<span class="font12">' + cityName + '</span>');
}

function updateDateInfo(date)
{
    $('dateInfo').update(Ext.util.Format.date(date, 'l, F j Y'));
}

function populateCities(e,ddl)
{
    var ddlRegion = $(_ddlRegionId).dom;
    var regionValue = ddlRegion.options[ddlRegion.selectedIndex].value;
    $(_ddlCityId).dom.options.length = 0;
    $(_ddlCityId).dom.options.add(new Option('loading...','-1'));
    TwentyFour.Weather.Web.Ajax.GetCities(_country,ddl.options[ddl.selectedIndex].value, populateCitiesCallback);
}

function populateCitiesCallback(response)
{
    var ddl = $(_ddlCityId).dom;
    if (!response.error)
    {
        var data = response.value;
        if (data != null && data.length > 0)
        {
            ddl.options.length = 0; 
            for (var i=0; i<data.length; i++)
            {
                var opt = new Option(data[i].Text, data[i].Value);
                opt.setAttribute("reg",data[i].Attributes["reg"]);
                ddl.options.add(opt);
            }
        }
    }
}

function startClock()
{
    setInterval(tick.createDelegate(this), 1000);
}

function tick()
{
    t = new Date();
    updateClock(t);
}

function updateClock(date)
{
    $('timeInfo').update('Current Time : ' + Ext.util.Format.date(date, 'h:i:s A') + ' SAST');
}

function validateGo(e,button)
{
    var ddl = $(_ddlCityId).dom;
    if (ddl.options[ddl.selectedIndex].value == '-1')
    {
        e.stopEvent();
        alert('Please select a city/town');
    }
    else
        updatePage();
}