
var StoreChooser = Class.create({

	totalSCWidth: 0,
	loadedStoreImages: 0,
	//aspectRatio: 1,
	SCdims: new Array(),
	windowSizes: {},
	selectedRes: '',
	selectedResW: 0,
	selectedResH: 0,
	storesChooserData: {},
	timeouts: [],
	
	initialize: function( data ){
		if(data) this.storesChooserData = data;
		jQuery.noConflict();
		jQuery.fx.interval = 30;
		Event.observe(window, 'resize', this.resizeStoreChooserScreen.bind(this) );
		Event.observe(window, 'load', this.handleOnPageLoad.bind(this) );
	},
	
	handleOnPageLoad: function( event ){
		jQuery('#underlay li').click( (function(e){
			if( typeof this.chosenStore == 'undefined' ){
				this.chosenStore = (this.bike?'bike':'board');
				this.afterStoreSelection();
				setTimeout( this.getHomePage.bind(this),10);
			}
			return false;
		}).bind(this));
		
		// Initialize Images
		this.getWindowSizes();
		var largestX = 0;
		for( var resolution in this.storesChooserData.images ){
			var xy = resolution.split('x');
			if( xy[0] > largestX ) this.selectedRes = resolution;
			if( xy[0] >= this.windowSizes.width && xy[1] >= this.windowSizes.height){
				this.selectedRes = resolution;
				this.selectedResW = xy[0];
				this.selectedResH = xy[1];
				break;
			}
		}
		if( this.selectedRes ){
			var handleImageCreation = {};
			for(var mode in this.storesChooserData.images[this.selectedRes]){
				for(var store in this.storesChooserData.images[this.selectedRes][mode])
					handleImageCreation[this.storesChooserData.imagesPath + this.storesChooserData.images[this.selectedRes][mode][store]] = { store : store, mode: mode };
			}
			for( var url in handleImageCreation){
				var o = handleImageCreation[url];
				var img = new Element('img',{src:url,className:o.mode});
				img.observe('load',(function(e){
					this.loadedStoreImages++;
					if($(e.target).stopObserving('load').hasClassName('over')) jQuery(e.target).hide();
				}).bind(this));
				if(o.mode == 'over'){
					$$('#underlay li.' + o.store + ' a img.normal')[0].insert({ after : img});
				} else {
					$$('#underlay li.'+o.store+' a')[0].insert({ top : img });
				}
			}		
		}

		this.storeChooserLoading();
	},
	
	afterStoreSelection: function(){
		if( jQuery('#underlay').queue().length == 0 ) {
			var x = (this.bike ? ( -1 * this.SCdims[0] + this.windowSizes.width - 3 ) : - this.SCdims[0] + 3 );
			jQuery('#underlay li').each(function( i,e ){
				jQuery(e).unbind('mouseenter').unbind('mouseleave');
				jQuery(e).find('img.over').css({opacity:1});
			});
			jQuery('#underlay li.'+this.chosenStore+' span').stop().animate({ width:0 },600,'easeOutElastic', (function(e){
					jQuery('#underlay').animate({ left: x }, 800 );
					var left = (jQuery('body').get(0).offsetWidth - 882)/2 - 62;
					jQuery('#underlay li.'+this.chosenStore+' a').animate((this.bike?{right:left}:{left:left}),800,(function(){
						this.readyForHomepageDisplay = true; // animation ready
					}).bind(this));
				}).bind(this)
			);
			var head = jQuery('head');
			this.storesChooserData.css[this.chosenStore].each(function(css,i){
				if( css.search(/^IE[0-9]+/g) == 0){
					if(jQuery.browser.hasOwnProperty("msie") && jQuery.browser.msie == true){
						css = css.substring(css.indexOf(':')+1);
					} else return;
				}
				if (document.createStyleSheet) {
					document.createStyleSheet(css);
				} else {
					head.append(jQuery('<link/>', {rel:'stylesheet', href: css, type: "text/css" }));
				}
			});
			jQuery('html.store_chooser').addClass('switch_'+(this.bike?'board':'bike')).css('height','100%');
		} else {
			setTimeout( this.afterStoreSelection.bind(this), 100 );
		}
	},
	
	getWindowSizes: function(){
		this.windowSizes.width = jQuery('html').get(0).offsetWidth;
		this.windowSizes.height = jQuery('html').get(0).offsetHeight;
	},

	resizeStoreChooserScreen: function( event ){
		if($('viewport')){
			this.getWindowSizes();
			$('viewport').setStyle({
				width: this.windowSizes.width + 'px',
				height: this.windowSizes.height + 'px'
			});
			
			var wh = this.selectedRes.split('x');
			if( this.windowSizes.width/this.windowSizes.height > wh[0]/wh[1]){
				this.aspectRatio = this.windowSizes.width/wh[0];
				this.selectedResW = wh[0] * this.aspectRatio;
				this.selectedResH = wh[1] * this.aspectRatio;
			} else {
				this.aspectRatio = this.windowSizes.height/wh[1];
				this.selectedResW = wh[0] * this.aspectRatio;
				this.selectedResH = wh[1] * this.aspectRatio;
			}
			
			$$('div#underlay ul li').each( (function(e,i){
				e.setStyle({width:this.windowSizes.width + 'px',height: this.windowSizes.height + 'px'});
				/*if(e.down('img.normal')){
					e.down('img.normal').setStyle({ width: this.selectedResW+'px', height: this.selectedResH+'px' });
					e.down('img.over').setStyle({ width: this.selectedResW+'px', height: this.selectedResH+'px' });
				}*/
			}).bind(this));
			
			var lis = $$('div.viewport div.underlay ul li');
			this.totalSCWidth = 0;
			this.SCdims.clear();
			while(lis.length){
				var li = lis.pop();
				this.SCdims.push($(li).getWidth());
				this.totalSCWidth += $(li).getWidth();
			}

			$('underlay').setStyle({
				width : this.totalSCWidth+'px'
			});
		}
	},

	showStoreChooser: function(){
		this.resizeStoreChooserScreen();

		$('underlay').setStyle({
			left  : (- this.totalSCWidth / 2 + this.windowSizes.width / 2) + 'px'
		});

		jQuery('#underlay li').each((function( i, e){
			e = jQuery(e);
			e.mouseenter( (function(event){
				var bike = e.hasClass('bike') && !e.hasClass('board');
				if( typeof this.bike == 'undefined' || this.bike != bike) { 
					this.bike = bike;
					this.moveStoreChooser();
				}
			}).bind(this));
			e.mousemove((function(){
				e.unbind('mousemove');
				if(typeof this.bike == 'undefined') {
					this.bike = e.hasClass('bike') && !e.hasClass('board');
					this.moveStoreChooser();
				}
			}).bind(this));
		}).bind(this));
	},
	
	moveStoreChooser: function(){
		while(this.timeouts.length){ clearTimeout(this.timeouts.pop()); }
		var el = jQuery('#underlay li.'+(this.bike?'bike':'board'));
		jQuery('#underlay li span').stop().animate({ width:0,queue:true },600,'easeOutElastic');
		this.timeouts.push(setTimeout( (function(){jQuery('#underlay').stop().animate({ left: (- this.windowSizes.width / 2 + 225 * (this.bike?1:-1)), queue:true },1500);}).bind(this),300));
		this.timeouts.push(setTimeout( (function(){jQuery('#underlay li.'+(this.bike?'board':'bike')+' img.over').stop(true,true).fadeOut(1000);}).bind(this),900));
		this.timeouts.push(setTimeout( (function(){el.find('img.over').stop(true).fadeIn(1000);}).bind(this),900));
		this.timeouts.push(setTimeout( (function(){el.find('span').stop().animate({width:52,queue:true},600,'easeOutElastic');}).bind(this),1000));
	},

	storeChooserLoading: function( e ){
		if( this.loadedStoreImages == 4 ){
			this.showStoreChooser();
			$$('div#underlay ul li').each( (function(e,i){
				e.fade({
					duration: 2,
					from: 0,
					to: 1,
					beforeStart : (function( e ){ 
						$(e.element).setStyle({
							height: this.windowSizes.height + 'px',
							visibility:'visible',
							opacity: 0
						});
					}).bind(this)
				});
			}).bind(this));
			$(e.element).remove();
		} else {
			var logo = $$('body.store_chooser .logo')[0];
			if(logo){
				new Effect.Fade(logo,{
					duration: 2,
					from: 1,
					to: 0,
					transition: Effect.Transitions.pulse,
					afterFinish: this.storeChooserLoading.bind(this)
				});
			}
		}
	},
	
	getHomePage: function(){
		new Ajax.Request(jQuery('#underlay li.'+this.chosenStore+' a').attr('href') + '&___ajax=1', {
			method: 'get',
			onSuccess: (function(response) {
				this.response = response;
				setTimeout( this.switchToHomePage.bind(this), 10 );
			}).bind(this)
		});
	},
	
	switchToHomePage: function(){
		if( jQuery('#underlay').queue().length == 0 && this.readyForHomepageDisplay) {
			jQuery('body').removeClass('store_chooser').addClass('cms-home');
			jQuery('#viewport').css({position:'absolute'});
			var wrap = jQuery('<div class="wrapper"></div>');
			wrap.hide();
			jQuery('body').append(wrap);
			wrap.html(this.response.responseText);
			wrap.fadeIn(
				2000,
				function(){
					jQuery('#viewport').remove();
					Event.fire(document, "dom:loaded");
					jQuery('html').css('height','auto').removeClass('store_chooser')
				}
			);
		} else {
			setTimeout( this.switchToHomePage.bind(this), 100 );
		}
	}
});

