var TodayPageWeather = {
    cookieDelimiter: ';',
    cookieItems: 2,
    currentCityCode: null,
    currentCityLabel: null,
    currentWeatherCode: null,
    searchTimer: false,
    searchDelay: 230,
    defaultLocation: 'London',
    DWHArticle: 'todaypage09weather',
    debug: false,

    init: function() {

        if((document.location.toString().indexOf('?debug=1') != -1) || 
           (document.location.toString().indexOf('&debug=1') != -1)) {
            TodayPageWeather.debug = true;
            console.log('Weather console logging enabled!');
        }

        if(TodayPageWeather.debug) {
            console.log('TodayPageWeather.init()');
        }

        dojo.require('dojo.cookie');
        TodayPageWeather.clearErrors();
        TodayPageWeather.weatherCookie = dojo.cookie('weather_location');

        
        if(TodayPageWeather.debug) {
            console.log('weather_location cookie: ', TodayPageWeather.weatherCookie);
        }

        // No cookie found. Use defaultLocation (or legacy cookie if it exists).
        if(typeof TodayPageWeather.weatherCookie === 'undefined') {
            //Does the user have a legacy cookie?
            TodayPageWeather.getLegacyWeatherDetails();
        }
        else {        
            if(TodayPageWeather.debug) {
                console.log('Working with the cookie data');
            }
            var cookieParts = TodayPageWeather.weatherCookie.split(TodayPageWeather.cookieDelimiter);
            if(cookieParts.length === TodayPageWeather.cookieItems) {
                /*
                TodayPageWeather.setCurrentCityCode(TodayPageWeather.weatherCookie);
                TodayPageWeather.setCurrentCityLabel(cookieParts[3]);
                TodayPageWeather.setCurrentWeatherCode(TodayPageWeather.weatherCookie);
                */
                TodayPageWeather.setCurrentCityCode(cookieParts[0]);
                TodayPageWeather.setCurrentCityLabel(cookieParts[1]);
                //TodayPageWeather.setCurrentWeatherCode(TodayPageWeather.weatherCookie);
                TodayPageWeather.updateForecast();
            }
            else {
                if(TodayPageWeather.debug) {
                    console.log('Found cookie is not valid. Falling back onto defaultLocation: ' + TodayPageWeather.defaultLocation);
                }
                TodayPageWeather.setLocation(TodayPageWeather.defaultLocation);
                TodayPageWeather.getCityCodeFromLocation();
            }
        }
    },

    // Does the user have a legacy weather cookie. 
    // If so get the city name from it and use that as the location.
    getLegacyWeatherDetails: function() {
        var legacyCookie = dojo.cookie('OforecastAJAX');
        if(legacyCookie == null || (typeof legacyCookie == 'undefined')) {
            if(TodayPageWeather.debug) {
                console.log('No legacy cookie found.');
            }
            TodayPageWeather.setLocation(TodayPageWeather.defaultLocation);
            TodayPageWeather.getCityCodeFromLocation();
        }
        else {

        if(TodayPageWeather.debug) {
            console.log('legacy cookie: ', legacyCookie);
            console.log(typeof legacyCookie);
        }
        
        var xhrArgs = {
            url: 'http://www.orange.co.uk/jsincludes/feeds/'+legacyCookie+'.js',
            handleAs: 'text',
            load: dojo.hitch(
                this,
                function(data) {
                    // Try and pull the city from the legacy javascript file.
                    var re = new RegExp(/var\ city \=\ \"([a-zA-Z\ ]+)\"/);
                    var city = re.exec(data);
                    console.log(city);
                    if(city.length == 2) {
                        if(TodayPageWeather.debug) {
                            console.log('matched legacy location of: ' + city[1]);
                        }
                        TodayPageWeather.setLocation(city[1]);
                        TodayPageWeather.getCityCodeFromLocation();
                        console.log('returning TRUE from getLegacyWeatherDetails.');
                        //return true;
                    }
                    else {
                        if(TodayPageWeather.debug) {
                            console.log('no legacy city match.');
                        }
                        console.log('returning FALSE from getLegacyWeatherDetails.');
                        TodayPageWeather.setLocation(TodayPageWeather.defaultLocation);
                        TodayPageWeather.getCityCodeFromLocation();
                        //return false;
                    }
                }
            ),
            error: function(error){
                console.log('returning FALSE from getLegacyWeatherDetails.');
                TodayPageWeather.setLocation(TodayPageWeather.defaultLocation);
                TodayPageWeather.getCityCodeFromLocation();
                return false;
            }
        };

        dojo.xhrGet(xhrArgs);

        }

    },

    getURL: function() {
        return TodayPageWeather._url;
    },

    saveWeather: function() {
        if(TodayPageWeather.debug) {
            console.log('saveWeather()');
        }
        TodayPageWeather.getCityCodeFromLocation();
    },

    cancelWeather: function() {
        if(TodayPageWeather.debug) {
            console.log('cancelWeather()');
        }
        TodayPageWeather.closeLightbox();
        TodayPageWeather.clearErrors();
    },

    changeWeather: function() {
        if(TodayPageWeather.debug) {
            console.log('changeWeather()');
        }
        TodayPageWeather.openLighBox();
        TodayPageWeather.reportToDWH(TodayPageWeather.DWHArticle, 'change');
    },

    displayError: function(err) {
        //
        if(typeof err === 'undefined') {
            dojo.byId('home_weatherlightboxerror').innerHTML = 'Oops, we can\'t find a region for that search. Try a city name or UK postcode, like Leeds or LS27 5JX.';
        }
        else {
            dojo.byId('home_weatherlightboxerror').innerHTML = err;
        }
    },
    
    clearErrors: function() {
        dojo.byId('home_weatherlightboxerror').innerHTML = '';
    },

    getCurrentCityCode: function() {
        return TodayPageWeather.currentCityCode;
    },

    setCurrentCityCode: function(cityCode) {
        TodayPageWeather.currentCityCode = cityCode;
    },

    getCurrentCityLabel: function() {
        return TodayPageWeather.currentCityLabel;
    },

    setCurrentCityLabel: function(cityLabel) {
        TodayPageWeather.currentCityLabel = cityLabel;
    },

    setCurrentWeatherCode: function(code) {
        TodayPageWeather.currentWeatherCode = code;
    },

    getCurrentWeatherCode: function() {
        return TodayPageWeather.currentWeatherCode;
    },

    getDomain: function() {
        return 'orange.co.uk';
    },

    getFullDomain: function() {
        return 'http://www.orange.co.uk';
    },

    getLocation: function() {
        return dojo.byId('weatherlocation').value
    },

    setLocation: function(location) {
        dojo.byId('weatherlocation').value = location;
    },
    
    openLighBox: function() {
        var dialog = dijit.byId('home_weatherlightbox');
        dialog.duration = 1;
        dialog.show();
    },

    closeLightbox: function() {
        var dialog = dijit.byId('home_weatherlightbox');
        if (dialog) {
            dialog.hide();
        }
    },

    getCityCodeFromLocation: function() {
        if(TodayPageWeather.debug) {
            console.log('TodayPageWeather.getCurrentCityCodeFromLocation() - ' + TodayPageWeather.getLocation());
        }
        if (TodayPageWeather.getLocation().toString().length >= 2) {

            // START dojo.io.script.get
            dojo.require("dojo.io.script");
            dojo.io.script.get({
                url: 'http://web.orange.co.uk/weather/ajax.php',
                timeout: 5000,
                content: {
                    location: TodayPageWeather.getLocation()
                   ,townmatch: 'on'
                   ,callback: 'callback'
                },
                callbackParamName: 'callback',
                load : function(response, ioArgs) {
                    if(TodayPageWeather.debug) {
                        console.log('good', response);
                    }
                    // Store the city code.

                    if (response.gotStations && response.stations[0]) {
                        // Got station
                        if(TodayPageWeather.debug) {
                            console.log('Got station', response.stations[0]);
                        }

                        //TodayPageWeather.setCurrentWeatherCode(response.stations[0].station_id);

                        TodayPageWeather.setCurrentCityCode(response.stations[0].station_id);
                        TodayPageWeather.setCurrentCityLabel(TodayPageWeather.getLocation());
                        //var values = response.stations[0].station_id.split('|');
                        //var label = values[values.length-1];
                        //TodayPageWeather.setCurrentCityLabel(label);
                        //TodayPageWeather.setLocation(label);
                        TodayPageWeather.updateForecast();
                    }
                    else {
                        //TodayPageWeather.displayError();
                        if(TodayPageWeather.debug) {
                            console.log('No station match using \''+TodayPageWeather.getLocation()+'\', reverting to defaultLocation.');
                        }
                        TodayPageWeather.setLocation(TodayPageWeather.defaultLocation);
                        TodayPageWeather.getCityCodeFromLocation();
                    }
                },
                error : function(response, ioArgs) {
                    if(TodayPageWeather.debug) {
                        console.log('error resolving location: ', response);
                    }

                    //if(response.dojoType === 'timeout') {
                    //    TodayPageWeather.displayError('Timeout');
                    //}
                    //else {
                        TodayPageWeather.displayError('Sorry, we are unable to retrieve you weather forecast.');
                    //}
                    return response;
                }
            });
        }
    },
    
    updateForecast: function() {
        if(TodayPageWeather.debug) {
            console.log('TodayPageWeather.updateForecast()');
        }
        //if (!TodayPageWeather.getCurrentWeatherCode()) {
            if(TodayPageWeather.debug) {
                console.log('getCurrentCityCode - ' + TodayPageWeather.getCurrentWeatherCode());
            }
            //return false;
        //}

        // Set current city code cookie
        var cookieDomain = TodayPageWeather.getDomain();

        //dojo.cookie('weather_location', TodayPageWeather.getCurrentCityCode() + '|' + TodayPageWeather.getCurrentCityLabel(), {domain: '.' + cookieDomain, expires: 830, path: '/'});
        dojo.cookie('weather_location', TodayPageWeather.getCurrentCityCode() + TodayPageWeather.cookieDelimiter + TodayPageWeather.getCurrentCityLabel(), {domain: '.' + cookieDomain, expires: 830, path: '/'});
        //dojo.cookie('weather_location', TodayPageWeather.getCurrentWeatherCode(), {domain: '.' + cookieDomain, expires: 830, path: '/'});
        //console.log('set cookie!');

            dojo.io.script.get({
                url: 'http://web.orange.co.uk/weather/content.php',
                timeout: 5000,
                content: {
                    rm: 'forecast'
                   ,json: 'true'
                   ,location: TodayPageWeather.getCurrentCityCode()
                },
                callbackParamName: 'callback',
                load : function(response, ioArgs) {
                    if(TodayPageWeather.debug) {
                        console.log('good', response);
                    }

                    // Update the displayed weather information.
                    dojo.byId('home_weather_location').innerHTML = TodayPageWeather.getCurrentCityLabel();
                    dojo.byId('home_weatherlightboxcity').innerHTML = TodayPageWeather.getCurrentCityLabel();
                    dojo.byId('home_weather_high').innerHTML = response[0].high + '&deg;';
                    dojo.byId('home_weather_low').innerHTML = response[0].low + '&deg;';
                    var icon = dojo.byId('home_weather_icon_image');
                        icon.src = '/img/homerefresh09/weather/icons/' + response[0].icon + '.gif';
                        icon.alt = response[0].summary;
                    
                    // Show the change and 5-day links.
                    dojo.byId('home_weather_change').style.visibility   = 'visible';
                    dojo.byId('home_weather_forecast').style.visibility = 'visible';

                    return response;
                },
                error : function(response, ioArgs) {
                    if(TodayPageWeather.debug) {
                        console.log('error getting forecast: ', response);
                    }
                    TodayPageWeather.displayError('Sorry, we are unable to retrieve you weather forecast.');
                    return response;
                }
            }); 

        console.log('finished in updateForecast()');
        TodayPageWeather.cancelWeather();

    },

    reportToDWH: function(article,link) {
        dojo.xhrGet({
            url: "/pagebuilder/admin/tools/tool_track.htm?linkfrom=hp"+hp+"&article="+article+"&link="+link+"&linkto="
        });
    },

    fiveDayForecast: function() {
        TodayPageWeather.reportToDWH(TodayPageWeather.DWHArticle, '5dayforecast');
        if(TodayPageWeather.debug) {
            console.log('getting five day forecast.');
        }
        //document.location = 'http://orangeuk.accuweather.com/orange/forecast.asp?location=' +  TodayPageWeather.getCurrentCityCode();
        document.location = 'http://orangeuk.accuweather.com/orange/index.asp?location=' +  TodayPageWeather.getCurrentCityCode();
    },


    setLocationDefault: function() {
        var location = dojo.byId('search_');

        if (!location) {
            return false;
        }

        var cookie = dojo.cookie('weather_location');

        if (cookie) {
            var cookieParts = cookie.split('|');
            location.value = cookieParts[cookieParts.length - 1];
        } else {
            location.value = 'enter postcode or town';
        }
    },

    clearLocationDefault: function() {
        var location = dojo.byId('weatherLocation');

        if (!location) {
            return false;
        }

        if (location.value == 'enter postcode or town') {
            location.value = '';
        }
    },

    consoleLog: function() {
        if(TodayPageWeather.debug) {
            console.log(arguments);
        }
    }
};
