var SwapCountry = Class.create();
SwapCountry.prototype = {
	
	url: '',
	timeout: 0,
	
	initialize: function() {

		this.countries = new Hash();
		this.countries.set('gl', '0');
		this.countries.set('ar', '1');
		this.countries.set('cl', '2');
		this.countries.set('co', '3');
		this.countries.set('ec', '4');
		this.countries.set('sv', '5');
		this.countries.set('gt', '6');
		this.countries.set('hn', '7');
		this.countries.set('vi', '8');
		this.countries.set('jm', '9');
		this.countries.set('ni', '10');
		this.countries.set('pa', '11');
		this.countries.set('py', '12');
		this.countries.set('pe', '13');
		this.countries.set('pr', '14');
		this.countries.set('pre', '15');
		this.countries.set('do', '16');
		this.countries.set('uy', '17');
		this.countries.set('ve', '18');
		
		
		this.setMouseover();
	},
	
	setMouseover: function() {
		this.checkUrl();
		
	},
	
	checkUrl: function() {
		if (this.url != document.location.hash) {
			window.scrollTo(0, 0);
			this.url = document.location.hash;
			if(this.url.match(/#(.*)/)) {
				selected = this.url.match(/#(.*)/)[1];
			} else {
				return;
				//selected = 'ar';
				//document.location.href = '#' + selected;
			}
			
			// check for correct anchor
			/*
			if(!this.countries.get(selected)) {
				selected = 'ar';
				document.location.href = '#' + selected;
			}
			*/
			
			// if english speaking, go to lae/. CHANGE this flow when more than one country in lae/!
			if(selected == 'jm' || selected == 'pre' || selected == 'vi') {
				document.location.href = '/lae/iphone/buy/#' + selectedCountry;
				//document.location.href = '/lae/iphone/buy/#jm';
			}

			// change select index
			var countryIndex = this.countries.get(selected);
			$('selectCountry').selectedIndex = countryIndex;
			this.turnOnCountryDiv(selected);
		} else if(!document.location.hash) {
			//document.location.href = '#ar';
		}

		this.timeout = window.setTimeout(this.checkUrl.bind(this, document.location.hash), 200);
	},
	
	turnOnCountryDiv: function(selectedCountry) {
		
		if(!this.countries.get(selectedCountry)) {
			selectedCountry = 'gl';
		}
		
		// if english speaking, go to lae/. CHANGE this flow when more than one country in lae/!
		if(selectedCountry == 'jm' || selectedCountry == 'pre' || selectedCountry == 'vi') {
			document.location.href = '/lae/iphone/buy/#' + selectedCountry;
			return;
		}
		
		window.scrollTo(0, 0);
		var contentdivs = $$('.contentblock');
		contentdivs.each(function(div) {
			div.hide();
		});

		var divToTurnOn = 'content_' + selectedCountry;
		$(divToTurnOn).appear({ duration: 1.0 });
		var flagspan = $$('.flagimg');
		flagspan.each(function(s) {
			s.src = "/la/iphone/countries/images/tinyflag_" + selectedCountry + "20080609." + "png";
		});
	},
	
	handleSelect: function(event, obj) {
		selectedCountry = obj[obj.selectedIndex].value;
		document.location.href = '#' + selectedCountry;
	}
}
