CurrencySelector = new JS.Class('CurrencySelector', {
    include: Ojay.Observable,
    
    initialize: function(container, currencies, redirect, options) {
        options          = options || {};
        
        this._currencies = currencies;
        this._container  = Ojay(container);
        this._redirect   = redirect;
        
        var geolocatedInUS   = this.klass.readCookie('geocountry') === 'US',
            cookieCurrency   = this.klass.getCurrencyFromCookie(),
            selectedCurrency = cookieCurrency;
        
        if (currencies.indexOf(cookieCurrency) < 0) {
            cookieCurrency   = null;
            selectedCurrency = currencies[0];
        }
        
        // Migrate old geolocation implementation cookies
        if (this.klass.readCookie('currency') === 'USD^') {
            geolocatedInUS = true;
            this.klass.storeCookie('geocountry', 'US');
        }
        
        if (!(cookieCurrency === 'USD' && geolocatedInUS)) {
            this._makeControls(options.titles || []);
        }
        
        this.setCurrency(selectedCurrency);
        
        if (!cookieCurrency) {
            this.doGeolocation(options.endpoint);
        }
    },
    
    setCurrency: function(currency) {
        if (this._currencies.indexOf(currency) < 0) return;
        
        var body = Ojay(document.body);
        
        if (this._selected) {
            this._controls[this._selected].deselect();
            body.removeClass(this._selected.toLowerCase());
        }
        
        if (this._controls) {
            this._controls[currency].select();
        }
        
        body.addClass(currency.toLowerCase());
        
        BasketCounter.setCurrency(currency);
        
        this.klass.storeCookie('currency', currency);
        this._selected = currency;
        
        this.notifyObservers('change', currency);
    },
    
    changeCurrency: function(currency) {
        if (this._selected == currency) return;
        
        if (!(this._mask && this._overlay)) this._makeDialogue();
        
        this._setOverlayContent();
        
        this._confirm.on('click', function(el, evnt) {
            evnt.stopDefault();
            
            this.setCurrency(currency);
            
            if (BasketCounter.numItems() > 0) {
                var uri = this._redirect.parseURI();
                uri.setParam('currency', currency);
                document.location = uri.toString();
            } else {
                this.closeDialogue();
            }
        }, this);
        
        this._cancel.on('click', this.closeDialogue, this);
        
        this.openDialogue();
    },
    
    doGeolocation: function(endpoint) {
        if (typeof endpoint != 'string') return;
        
        this.klass.getCurrencyFromLocation(endpoint, function(location) {
            if (typeof location.geo != 'object') return;
            
            var geoCountry  = location.geo.countrycode,
                geoCurrency = location.geo.currencycode;
            
            this.setCurrency(geoCurrency);
            
            if (geoCountry.length > 0) {
                this.klass.storeCookie('geocountry', geoCountry);
            }
            
            if (this._selected == 'USD' && geoCountry === 'US') {
                this._container.hide();
            }
        }, this);
    },
    
    extend: {
        getCurrencyFromCookie: function() {
            var currency = this.readCookie('currency');
            
            return currency.length >= 3 ? currency.substring(0, 3) : null;
        },
        
        getCurrencyFromLocation: function(endpoint, callback, scope) {
            if (document.location.protocol == 'https:'){
                endpoint = endpoint.replace('http:', 'https:');
            }
            
            Ojay.HTTP.GET(endpoint, {jsonp: 'callback'},{
                onSuccess: function(response) {
                    callback.call(scope, response);
                }
            });
        },
        
        readCookie: function(key) {
            var keyRegExp   = new RegExp('^' + key + '=.+?'),
                cookieValue = (document.cookie.split(/\s*;\s*/).filter(function(kvp) {
                    return kvp.match(keyRegExp);
                })[0] || '').substr(key.length + 1);
            
            return cookieValue;
        },
        
        storeCookie: function(key, value, expiry) {
            if (typeof key != 'string' || typeof value != 'string') return;
            
            if (!expiry) {
                expiry = new Date();
                expiry.setUTCFullYear(expiry.getUTCFullYear() + 1);
            }
            
            document.cookie = key + '=' + value + ';expires=' + expiry.toUTCString() + ';path=/';
        },
        
        Control: new JS.Class('CurrencySelector.Control', {
            initialize: function(selector, abbr, options) {
                options = options || {};
                this._selector = selector;
                this._abbr     = abbr;
                this._title    = options.title || null;
            },
            
            getHTML: function() {
                if (this._html) return this._html;
                
                this._html = Ojay(Ojay.HTML.li({
                    id:    'currency-' + this._abbr.toLowerCase(),
                    title: this._title
                }, this._abbr));
                
                this._html.on('click')._(this._selector).changeCurrency(this._abbr);
                
                return this._html;
            },
            
            select: function() {
                this._html.addClass('selected');
            },
            
            deselect: function() {
                this._html.removeClass('selected');
            }
        })
    },
    
    openDialogue: function() {
        this._mask.positionBehind(this._overlay).show('fade')
        ._(this._overlay).fitToContent().center().show('zoom');
    },
    
    closeDialogue: function(el, evnt) {
        this._overlay.hide('zoom')._(this._mask).hide('fade');
    },
    
    _makeControls: function(titles) {
        this._html = Ojay(Ojay.HTML.ul({className: 'currencies'}));
        
        this._controls = this._currencies.reduce(function(currs, abbr, i) {
            var control = new this.klass.Control(this, abbr, {title: titles[abbr] || null});
            
            this._html.insert(control.getHTML());
            currs[abbr] = control;
            
            return currs;
        }.bind(this), {});
        
        this._container.insert(this._html);
    },
    
    _makeDialogue: function() {
        this._mask = new Ojay.PageMask({
            color: '#000',
            opacity: 0.75
        });
        
        this._overlay = new Ojay.ContentOverlay({
            width: 400
        });
    },
    
    _setOverlayContent: function() {
        var self = this;
        
        this._overlayContent = Ojay.HTML.div(function(H) {
            H.h2('Are you sure you want to change your currency?');
            H.p('Please note: by selecting a new currency you are being charged by the price list ' +
                 'associated with that currency and NOT by any conversion rate. The value of any ' +
                 'items already placed in your basket will be recalculated.');
            
            H.div({className: 'clear'}, function(C) {
                self._confirm = Ojay(C.a({className: 'button primary'}, 'Continue'));
                self._cancel  = Ojay(C.a({className: 'button submit-grey secondary'}, 'Cancel'));
            });
        });
        
        this._overlay.setContent(this._overlayContent);
    }
});

