/*jslint bitwise: true, eqeqeq: true, immed: true, strict: false, newcap: true, nomen: true, onevar: true, plusplus: true, regexp: false, undef: true, white: true, indent: 4*/
/*global YUI, console, alert, window, document, navigator */

/**
 * Standard xhr callback naming convention: methodnameOnSuccess
 */

YUI().use(
    'node',
    'event',
    'json',
    'io-base',
    'io-form',
    
function (Y) {
    YUI.namespace('zigerflitz');

    Y.zigerflitz = (function () {

        // var declarations
        var appInit, latitude, longitude, foundLocation, noLocation, manualLocation, currentCoordinates = "";

        // private Methods
        appInit = function () {
            // Event handler
            Y.on("change", manualLocation, "#startort");
            try {
                navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
            } catch (e) {
                noLocation();
            }
        };

        foundLocation = function (position) {
            var request;
            latitude = position.latitude;
            longitude = position.longitude;
            if (!latitude) {
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
            }
            Y.one("#location").set("innerHTML", "Koordinaten: " + latitude + '/' + longitude);
            Y.one("#progress").set("innerHTML", "<img src='loader.gif' class='spinner'>     Ermiittle Fahrplan");
            // request place and timetable
            request = Y.zigerflitz.doXhr.get('/timetable/coordinates/' + latitude + '/' + longitude, Y.zigerflitz.timetable.show);
            
        };
        
        noLocation = function () {
            Y.one('#progress').addClass('hidden');
            Y.one('#location').removeClass('hidden');
            Y.one("#location").set("innerHTML", "Koordinaten nicht ermittelbar.");
            //Y.one('#manuell').removeClass('hidden');
        };
        
        manualLocation = function () {
            var startort, myindex, SelValue;
            startort = Y.one("#startort");
            
            SelValue = encodeURIComponent(startort.get("value"));
            request = Y.zigerflitz.doXhr.get('/timetable/assume/' + SelValue , Y.zigerflitz.timetable.show);
        };
        
        // Public methods
        return {
            init: function () {
                Y.on('contentready', appInit, "#content");
            }
        };
    }());
    
    Y.zigerflitz.timetable = {
        show: function (id, response) {
            //Y.log(response);
            Y.one("#fahrplan").set("innerHTML", response.markup);
            Y.one('#progress').addClass('hidden');
            Y.one('#location').addClass('hidden');
            Y.one('#fahrplan').removeClass('hidden');
            //Y.one('#manuell').addClass('hidden');
        }
    };

    Y.zigerflitz.doXhr = (function () {
        var config, xdrConfig, response;
        return {
            get: function (uri, successHandler, errorHandler) {
                if (errorHandler === undefined) {
                    errorHandler = Y.zigerflitz.doXhr.connectionError;
                }
                config = {
                    on: { success: this.globalSuccessHandler, failure: errorHandler },
                    arguments: successHandler
                };
                return Y.io(uri, config);
            },
            connectionError: function () {
                Y.log('Could not send request, pleace check if you\'re connected to the internet');
            },
            globalSuccessHandler: function (id, o, successHandler) {
                response = Y.zigerflitz.json.parse(o.responseText);
                if (response.status === 'nologin') {
                    alert(response.message);
                    // TODO display login form overlay maybe?
                } else if (response.status === 'noaccess') {
                    alert(response.message);
                    // TODO display nicer alert, the user can't do anything about that (except renew his subscription maybe)
                    // however this should really seldomly happen so maybe just leave the alert
                } else {
                    successHandler(id, response);
                }
            }
        };
    }());

    Y.zigerflitz.json = (function () {
        var response;
        return {
            parse: function (string) {
                try {
                    response = Y.JSON.parse(string);
                } catch (e) {
                    Y.log('Could not parse JSON string');
                    response = { status : 'error' };
                }
                return response;
            },
            serialize: function (string) {

            }
        };
    }());

    Y.zigerflitz.init();


});
