/*** Region Cookie Set ***/

var cookie = {
	set: function(name, value, days) {
		var expires,
			date = new Date();
		
		if(days) {
			date.setTime(date.getTime() + (days*24*60*60*1000));
			expires = '; expires=' + date.toGMTString();
		} else {
			expires = '';	
		}

		document.cookie = name + '=' + value+expires + '; path=/';
	},

	get: function(name) {
		var nameEQ = name + '=',
			ca = document.cookie.split(';'),
			c, i = 0, ii = 0;

		for(i = 0, ii = ca.length; i < ii; i++) {
			c = ca[i];

			while(c.charAt(0) === ' ') {
				c = c.substring(1, c.length);
			}

			if(c.indexOf(nameEQ) === 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	},

	destroy: function(name) {
		this.set(name, '', -1);
	}
};

/*** RegionSelect Object ***/

var regionSelect = function(target, options) {
	var base = this;

	base.options = {
	    redirectUrl: 'http://pokemon.com',
		regionSelectUrl: 'http://pokemon.com',
		visitedCookie: 'cookie-name',
		regionCookie: 'cookie-name'
	};

	if(options) {
		for(key in base.options) {
			if(typeof options[key] !== 'undefined') {
				base.options[key] = options[key];
			}
		}
	}

	base.container = target;

	base.init();
};

regionSelect.prototype = {
	init: function() {
		var base = this,
			regionCookie = cookie.get(base.options.regionCookie),
			visitedCookie = cookie.get(base.options.visitedCookie);
        
        // if there is no visited cookie, go through the process
		if(!visitedCookie) {
			if(regionCookie) {
			     // what if you want to go back to the region select page but you already have a cookie?
				cookie.set(base.options.visitedCookie, 'visited', 365);
			} else {
			 // redirect to region select page
    		  if(document.location.href !== base.options.regionSelectUrl)
    			 document.location = base.options.regionSelectUrl;
    			
                base.events();
			}
		} else {
		// we have cookies already, so go to the homepage
		  //if(document.location.href !== base.options.redirectUrl)
			//document.location = base.options.redirectUrl;
		}
	},

	events: function() {
		var base = this,
			anchor = base.container.find('a'),
			countryCode;
        
		anchor.click(function(e) {
			e.preventDefault();
            
            var href = e.target.getAttribute('href');
            
			countryCode = e.target.getAttribute('href').slice(href.length-2, href.length);
            
			base.setRegion(countryCode);
            cookie.set(base.options.visitedCookie, 'visited', 365);
            
            if(countryCode !== 'en'){
                // redirect to localized pages
                document.location = base.options.redirectUrl+'regions/'+countryCode;
            } else {
                document.location = base.options.redirectUrl;
            }
		});
	},

	setRegion: function(countryCode) {
		var base = this;

		cookie.set(base.options.regionCookie, countryCode, 365);
	}
};
