/**
	Proof of concept script for the Global Local functionality
*/
var shell;

if (typeof shell == 'undefined') {
    shell = {};
} 

shell.GL = function (settings) {
    this.settings = settings;
    this.cookie = null;
    this.METRICS_CATEGORY = "GlobalLocal";
    
    SHELL_cookie_create('_test', 'pass', 7);
    this.COOKIE_ENABLED = SHELL_cookie_read('_test') === 'pass';
    if (this.COOKIE_ENABLED) {
        SHELL_cookie_create('_test', '', -1);
    } 
    
    this.global_local_enabled_sites = settings.sites;
    this.labels = settings.labels;
    
    this.user_preference = this.getUserPreference();
    this.country = SHELL_cookie_read('loc');
    if (this.country  === 'null') {
        this.country  = null;
    }
    //Semaphore for providers calls
    this.waitingForProviders = 3;
    
    this.location_callback = null;
    this.ui_callback = function () {
            if (shell.gl) {
                shell.gl.showUI();
            }
    };
    window.addEvent('load', function(){
        //Launch Global Local code
        if (shell.gl) {
            shell.gl.doc_loaded = 1;
        }
    });
};

shell.GL.prototype.setupGlobalLocal = function() {
    if (this.user_preference) {
        //Do what user wants
        //unless he just decided to come to this page
        if (document.referrer) {
                this.showUI();
        } else {
            if (this.getCurrentSideId() != this.user_preference) {
                this.redirect();
            }
        }
    } else { 
        var that = this;
        this.getLocation(function (country) {
            if (that.ui_callback) {
                that.ui_callback(country);
            } 
        }); 
    }
};
 
shell.GL.prototype.redirect = function() {
    window.location = this.global_local_enabled_sites[this.user_preference].url;
};

shell.GL.prototype.isSecure = function() {
    return window.location.protocol == 'https:';
};  

/**
 * UI control method to show & generate the homepage chooser 
 */
shell.GL.prototype.showHomePageChooser = function() {
    var homepage_chooser = $('#homepage_chooser');
    var that = this;
    var usa_link;
    var global_link;
    var save_link;
    
    if (homepage_chooser.length === 0) {
        homepage_chooser = $('<div id="homepage_chooser" class="shell clearfix"></div>');
        
        homepage_chooser.append($('<span>' + this.labels.select + '</span>'));
        
        //add USA link
        usa_link = $('<a id="site_preference_usa" href="#"></a>').bind('click', function(){
                    that.trackEvent("Chosen homepage","Go to US site", (that.COOKIE_ENABLED && $('#save_site_preference_option:checked').length > 0)? 1 : 0);
                    that.setUserPreference(that.country);
                    that.redirect();
                });
        
        usa_link.append($('<span>' + this.labels.goto + '</span>'));
        
        homepage_chooser.append(usa_link);
        
        //end USA link

        //add global link
        global_link = $('<a id="site_preference_global" href="#">').bind('click', function(){
                    that.trackEvent("Chosen homepage","Stay on Corporate Site",(that.COOKIE_ENABLED && $('#save_site_preference_option:checked').length > 0)? 1 : 0);
                    that.setUserPreference('com');
                    that.hideHomePageChooser();
                });


        global_link.append($('<span>' + this.labels.stay + '</span>'));

        homepage_chooser.append(global_link);

        //end global_link

        if(this.COOKIE_ENABLED){
            save_link = $('<a id="save_site_preference" href="#"></a>');
            
            var optionEl = $('<input type="checkbox"></input>').bind('click', function(){
                    that.trackEvent("Remember my setting", $('#save_site_preference_option:checked').length > 0); 
                });
                
            save_link.append(optionEl);
            
            save_link.append($('<label for="save_site_preference">' + this.labels.remember + '</label>'))

            homepage_chooser.append(save_link)
            
        } else {
            that.trackEvent("No Cookies");
        }

        homepage_chooser.append($('<a href="#" class="close">' + this.labels.close + '</a>').bind('click', function(){
                    that.hideHomePageChooser();
                    that.trackEvent("Close");
                }));
        
        $('body').append(homepage_chooser);
    }
};

/**
 * Metrics: Event dispatcher 
 */
shell.GL.prototype.trackEvent = function(action, label, value) {
    if (typeof shell.metrics  !== undefined &&
            typeof shell.metrics.trackGAEvent !== undefined) {
        shell.metrics.trackGAEvent(this.METRICS_CATEGORY,action, String(label), value);
    } else {
        if (typeof console !== undefined) {
            console.warn("Metrics object is not set up!");
        } 
    }
};

shell.GL.prototype._showUIcallback = function(country) {
    if (this.country) {
        if (this.global_local_enabled_sites[this.country]) {
            this.showHomePageChooser();
        }
    } 
};

/**
 * This method defers the UI display until all the necessary data are received.
 */
shell.GL.prototype.showUI = function() {
    var that = this;
    var deffered_loading = function () { 
        if (that.user_preference) {
            if (that.user_preference != that.getCurrentSideId()) {
                that.showHomePageChooser();
            }
        } else {
            if (that.country) {
                if (that.global_local_enabled_sites[that.country]) {
                    that.showHomePageChooser();
                }
            } else {
                that.ui_callback = function (country) {that._showUIcallback(country);};
            }
        }
    };
    if (this.doc_loaded) {
        deffered_loading();
    } else {
        window.addEvent('load', deffered_loading);
    }
};

/**
 * Callback for the asyncronous location provider services. 
 * Location is given as a parameter to this callback function
 */
shell.GL.prototype._setLocation = function(countryCode) {
    /* 
     * If the country code was already provider earlier do nothing
     */ 
    if (this.waitingForProviders > 0) {
        this.waitingForProviders--;
        if (countryCode && typeof countryCode == 'string' && !this.country) {
            countryCode = countryCode.toLowerCase();
            //Store location value in a cookie to minimise the networking overhead 
            this.waitingForProviders = 0;
            this.country = countryCode;
            SHELL_cookie_create('loc', this.country, 7);
            if (this.location_callback) {
                this.location_callback(this.country);
            }
        }
    } else if (this.waitingForProviders === 0){
        this.waitingForProviders--;
        if (this.location_callback) {
            this.location_callback(null);
        }
    }
};

/**
 * Location is given as a prameter to callback function
 * 
 */
shell.GL.prototype.getLocation = function(callback) {
    //Try reading cached value
    if (!this.country) {
        this.country = SHELL_cookie_read('loc');
        if (this.country == 'null') {
            this.country = null;
        }
    }
    /**
     * Info for developers:
     * If you want to mock up the location provider to point to US
     * just add this line: this.country = 'us';
     */
    if (this.country) {
        //We have got the location data so release the semaphore 
        this.waitingForProviders = 0;
        callback(this.country);
    } else {
        this.location_callback = callback;
        var that = this;
        google.load("maps", "2");
        google.setOnLoadCallback(function() {
            if (google.loader.ClientLocation) {
                that._setLocation(google.loader.ClientLocation.address.country_code);
            } else {
                if (that.isSecure()) {
                    //IPInfoDB Cannot be used on secure sites! Decreasing the semphore
                    that.waitingForProviders--;
                } else {
                    that.getIPinfoDB();
                }
                that._setLocation(null);
            }
        });
        
        
    }
};

shell.GL.prototype.getCurrentSideId = function() {
    return 'com';
};

/**
 * Gets the user preference from the cookie
 */
shell.GL.prototype.getUserPreference = function() {
    var country = SHELL_cookie_read('cn');
    if (country == 'null') {
        return null;
    }
    return country;
}; 

shell.GL.prototype.setUserPreference = function(country) {
    this.user_preference = country;
    if (this.COOKIE_ENABLED && $('#save_site_preference_option:checked').length > 0) {
        this.cookie = SHELL_cookie_create('cn', this.user_preference, 354);
    }
};

/**
 * Perform the JSONP call to the ipinfodb
 */
shell.GL.prototype.getIPinfoDB = function() {
    var that = this;
    new Request.JSONP({
      url: 'http://api.ipinfodb.com/v2/ip_query_country.php?key=06bf1d9924a193936b2f886938284feb24f63e5e08be7c8106e3a75ada97d774&output=json',
        onComplete: function(data){
            if (data) {
                that._setLocation(data['CountryCode']);
            } else {
                that._setLocation(null);
                that.setLocaleBasedLocation();
            }
        },
        onTimeout : function () {
            that._setLocation(null);
            that.setLocaleBasedLocation();
        }
    }).send();
};

shell.GL.prototype.setLocaleBasedLocation = function() {
    var locale;
    if ( navigator ) {
        if ( navigator.language ) {
            locale = navigator.language;
        }
        else if ( navigator.browserLanguage ) {
            locale = navigator.browserLanguage;
        }
        else if ( navigator.systemLanguage ) {
            locale = navigator.systemLanguage;
        }
        else if ( navigator.userLanguage ) {
            locale = navigator.userLanguage;
        }
    }
    if (locale && typeof locale == 'string') {
        var res = locale.split(new RegExp("[-_]"));
        this._setLocation(res[res.length -1]);
    } else {
        this._setLocation(null);
    }
};
