var BaseSection = new Class({
	
	opposites  : {left:'right' , right:'left' , top:'bottom' , bottom:'top'},
	tabOffset  :  {top:'top' , left:'left' , bottom:'top' , right:'left'},
	backgroundTransitionTime : 1200,
	
	jQuery: 'BaseSection',

	initialize: function(param_definition){
		this.definition = param_definition;
		var uniqueId = this.generateUniqueID();
		this.contentId = '#' + uniqueId
		var html = $(this.definition.html_content);
		jQuery('#content').append(html);
		var div = $(html)[0];
		$(div).attr('id' ,uniqueId);
		jQuery($(html)[1]).css({opacity:0 , bottom:'-10px'});
		jQuery(this.contentId).css({
			height:'auto' ,
			width : 'auto',
			top : 0,
			left : 0,
			marginLeft : 0,
			marginTop : 0,
			opacity:0,
			color : this.definition.themetype == 'dark' ? "#ffffff" : "#000000"
		});
		
		MainUI.getInstance().resetSectionContent(this.definition);
	},
	
	
	appear:function(param_delay){
		this.resize();
		 MainUI.getInstance().busy = true;
		if(MainUI.getInstance().direction != undefined){
			this.showBackground(MainUI.getInstance().direction , param_delay + 0);
		}
		else{
			MainUI.getInstance().changeTheme(this.definition.themetype);
			this.showContent(MainUI.getInstance().direction);
		}
	},
	
	
	cleanup:function(){
		$('.bg').remove();
		$('.previoussection').remove();
		$(this.contentId).css('zIndex' , 'auto');
		MainUI.getInstance().changeTheme(this.definition.themetype);	
	},
	
		
	showBackground: function(param_direction , param_delay){
		$('body').append('<div class="bg"></div>');
		$(this.contentId).css('zIndex' , $('.bg').css('zIndex') + 1);
		toHeight = $(window).height();
		toWidth = $(window).width();
		switch(param_direction){
			case 'left':
				initProperties = {height:toHeight , width:0};
				animationProperties = {width:toWidth };
			break;
			case 'right':
				initProperties = {height:toHeight , width:0 , left:toWidth};
				animationProperties = {width:toWidth , left:0 };
			break;
			case 'top':
				 initProperties ={height:0 , width:toWidth , top:0};
				animationProperties = {height:toHeight };
			break;
			case 'bottom':
				initProperties = {top : toHeight};
				animationProperties = {top:0 , height:toHeight };
			break;
		}
		
		initProperties['backgroundColor'] = this.definition.themetype == 'clear' ? '#ffffff' : '#000000';
		$('.bg').css(initProperties);
		$('.bg').show();
		$('.bg').animate(animationProperties , this.backgroundTransitionTime , 'easeOutExpo' , $.proxy(function(){this.cleanup(); }  , this));
		 
		 this.showContent(param_direction , Math.round(this.backgroundTransitionTime * .45)  )
	},
	
	
	showContent:function(param_direction , param_delay , param_duration , param_options){
		if(param_direction == undefined){
			$(this.contentId).delay(param_delay).animate({opacity:1} , this.backgroundTransitionTime, $.proxy(function(){
				this.togglePagination(true)
				MainUI.getInstance().busy = false} , this));
			return false;
		}
		
		var direction = this.opposites[param_direction];		
		var tabContentOffset =  {top:$(window).height() , left:$(window).width() , bottom:-$(this.contentId).height() , right:-$(this.contentId).width()  };
		if(param_options != undefined){
			if(param_options.hasOwnProperty('initialPos'))
				tabContentOffset = param_options.initialPos;
		}
		
		var coord = this.tabOffset[direction];
		var cssProperties;

		var contentPosition = $(this.contentId).css(coord);
		cssProperties = {opacity:1};
		cssProperties[coord] = tabContentOffset[direction];
		$(this.contentId).css(cssProperties);
		
		var animationProperties = {};
		animationProperties[coord] = contentPosition;
		var duration  =  param_duration != undefined ?param_duration : Math.round(this.backgroundTransitionTime * .60)
		$(this.contentId).delay(param_delay).animate(animationProperties , duration ,  'easeOutExpo' , $.proxy(function(){
			this.togglePagination(true);
			MainUI.getInstance().busy = false
		} , this)); 

	},
	
	
	togglePagination:function(param_to){
		if(param_to)
			jQuery('#pagination').animate({opacity:1, bottom:'10px'} , 200);
		else{
			var pagination = jQuery('#pagination');
			jQuery(pagination).animate({opacity:0, bottom:'-10px'} , 200 , function(){jQuery(pagination).remove(); });
		}
			
	},
	
	disappear:function(){
		jQuery('.tooltip').remove();
		this.togglePagination(false);
		$(this.contentId).addClass('previoussection');
		$(document).trigger('SECTION_TRANSITION_OUT_COMPLETE' );
	},
	
	
	calculateFontSize : function(param_type , param_force_iswide , param_is_wide_text){
		var isWide = $(window).height() / $(window).width();
		var titleSize;
		var textSize;
	    isWide = param_force_iswide == undefined ? isWide < .75 ? true : false : param_force_iswide;
	    var wideText = param_is_wide_text == undefined ?isWide : param_is_wide_text
		var cufonErrorPercentage = 1.365;
		var heightRatios = {large:.2 , medium :.16, small:.13 , tiny:.10};
		var type = param_type == undefined ? 'medium' : param_type;
		if(isWide)
			titleSize= Math.round($(window).width() * heightRatios[type] * .73 * cufonErrorPercentage );
		else
			titleSize= Math.round($(window).height() * heightRatios[type] * cufonErrorPercentage );
		if(wideText)
			textSize= Math.round($(window).width() * .02 * .73 * cufonErrorPercentage );
		else
			textSize= Math.round($(window).height()  *  .02 * cufonErrorPercentage );
	
		return {title:titleSize  , text:textSize }; //:Math.round($(window).height() * .02 * cufonErrorPercentage
	},
	
	generateUniqueID:function(){
		var chars = 'abcdefghijklmnopqrstuvwxyz';
		var key ='';
		for(var i = 0; i < 10 ; ++i){
			rand = Math.floor(Math.random() * chars.length -1 );
			key += chars.charAt(rand);
		}
		return key;
	}


});



var People_item = new Class({
	Extends: BaseSection,
	
	initialize:function(param_definition){
		this.parent(param_definition);
		var bgId = this.generateUniqueID(); 
		$(this.contentId  + ' #background').attr('id' , bgId);
		this.bgId = '#' + bgId
		$(this.bgId).css({position:'absolute'}).hide();
		$(this.contentId ).css({opacity:0})
		$(this.contentId + ' h1').text(String($(this.contentId + ' h1').text()).replace('-' , ' '));
		$(this.contentId + ' h1').html(MainUI.getInstance().addSpan(this.contentId + ' h1'));
		$(this.contentId).append($(this.contentId + ' #info').html());
		$(this.contentId + ' #info').remove();
	},
	
	
	appear:function(param_delay){
		MainUI.getInstance().toggleWait(true);
		$(this.bgId).bind("load", $.proxy(function(){
			MainUI.getInstance().toggleWait(false);
			$(this.bgId).unbind('load');
			this.showBackground(MainUI.getInstance().direction);
		} , this));
	},
	
	showBackground: function(param_direction , param_delay){
		$('#content').append($(this.bgId));
		$('#content').append($(this.contentId));
		this.resize();
		var direction = this.opposites[param_direction];		
		var coord = this.tabOffset[direction];
		var tabContentOffset =  {top:$(window).height() , left:$(window).width() , bottom:-$(this.bgId).height()  , right:-$(this.bgId).width() };
		

		var animationProperties = {};
		animationProperties[coord] =  $(this.bgId).css(coord);
		cssProperties = {}
		cssProperties[coord] = tabContentOffset[direction];
		$(this.bgId).css(cssProperties).show().animate(animationProperties , this.backgroundTransitionTime , 'easeOutExpo' ,   $.proxy(function(){this.cleanup(); }  , this));
		
		
		var duration = undefined;
		delayPercent  = direction == 'left' ?  .70 : direction == 'right' ? .50 : .45;
		durationPercent  = direction == 'left' ? .45: direction == 'right' ? .70: undefined;
		var delay = Math.round(this.backgroundTransitionTime * delayPercent);
		if(durationPercent != undefined)
			duration = Math.round(this.backgroundTransitionTime * durationPercent);
		
		this.showContent(param_direction , delay , duration )
	},
	
	disappear:function(){
		$(this.bgId).addClass('previoussection');
		this.parent();
	},
	
	
	resize : function(){
		var fontSizes = this.calculateFontSize('small' , undefined , false);
		$(this.contentId).css('fontSize' , fontSizes.text);
		$(this.contentId + ' h1').css('fontSize' , fontSizes.title);
		Cufon.replace(this.contentId);
		var negativeMargin =  - Math.round($(this.contentId + ' h1 span:eq(0)').height() * .2);
		$(this.contentId + '  h1 span').css('marginBottom' , negativeMargin );
		$(this.contentId + '  h1 span:last').css('marginBottom' , negativeMargin / 1.2 );
		var titleWidth = MainUI.getCufonWidth(this.contentId + ' h1 cufon')
		$(this.contentId + '  p').width(titleWidth);
		$(this.contentId).width(titleWidth);
		$(this.bgId).fitToScreen();
		var halfWidth = Math.round($(window).width() / 2);
		var maxX = $(window).width() - $(this.contentId).width() - 30;
		var toX = Math.round( halfWidth + halfWidth*.10 ) ;
		$(this.contentId).css('left' , toX >=  maxX ? maxX : toX);
		$(this.contentId).centerY();
	}
	
	
});



var Home = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        this.currentNews = 0;
		this.timeOut;
		this.delay = 5000;
		this.newsRoll = true;
		jQuery(this.contentId + ' ul').css('opacity' , 0);
		this.nbNewsItems = jQuery(this.contentId + ' ul li').size();
    },
    
	resize : function(){		
		var fontSizes = this.calculateFontSize('large');
		$(this.contentId + ' h1').css('font-size' , fontSizes.title);
		$(this.contentId + ' h1 span').css('position' , 'relative');
		Cufon.replace(this.contentId + ' h1');
		
		var negativeMargin =  - Math.round($(this.contentId + ' h1 span:eq(0)').height() * .2);
		$(this.contentId +' h1 span:eq(1)').css('marginTop' , negativeMargin);
		
		// NEWS LIST
		
		$(this.contentId +'  ul').css('fontSize' , fontSizes.text + 'px' );
		Cufon.replace(this.contentId + ' ul' , {hover:true});
		var newsWidth = $(this.contentId).width() - $(this.contentId +' h1 span:eq(1) cufon').width() - fontSizes.text;
		$(this.contentId + ' ul').width(newsWidth);
		$(this.contentId + ' ul li span').width(newsWidth);
		
		var newsX = $(this.contentId +' h1 span:eq(1) cufon').width();
		var newsHeight =  $(this.contentId + ' ul li:eq(' + this.currentNews + ')').height() + 125;
		var newsY = $(this.contentId +' h1').height() + negativeMargin - newsHeight; 
		$(this.contentId +'  ul').css({'left':newsX , 'marginLeft':fontSizes.text , 'top':newsY });
		
		MainUI.alignContent(this.contentId  ,  $(this.contentId).height() + negativeMargin);
	},
		
	
	showContent:function(param_direction , param_delay ){
		this.parent(param_direction , param_delay);
		setTimeout($.proxy(this.hideNews , this), param_delay + this.backgroundTransitionTime);
	},
	
	disappear:function(){
		this.newsRoll = false;
		this.hideNews();
		this.parent();
	},
	
	
	showNews : function(){	
		var currentOpacity = jQuery(this.contentId + ' ul').css('opacity');
		if(currentOpacity == 0)
			jQuery(this.contentId + ' ul').animate({opacity: 1} , 300);

		$(this.contentId + ' ul li:eq(' + this.currentNews + ')').show();
		$(this.contentId + ' ul li:eq(' + this.currentNews + ') span').each(function(i){
			$(this).css({marginLeft : '-20px' , opacity:0});
			$(this).delay(i*100).animate({marginLeft:0 , opacity:1});
		});
		
		if(jQuery(this.contentId + ' ul li').size() > 1)
			this.timeOut = setTimeout($.proxy(this.hideNews , this), this.delay);
	},

	
	hideNews : function(){
		var current = this;
		clearTimeout(this.timeOut );
		var item = $(this.contentId + ' ul li:eq(' + this.currentNews + ')');
		var count = $(this.contentId + ' ul li:eq(' + this.currentNews + ') span').size();
		$(this.contentId + ' ul li:eq(' + this.currentNews + ') span').each(function(i){
			
			$(this).delay(i*100).animate({marginLeft:50 , opacity:0} , null , $.proxy(function(){
				if(i < count - 1)
					return;
						
				item.hide();
				if(this.newsRoll){
					this.currentNews++; 	
					this.currentNews  = this.currentNews >= this.nbNewsItems ? 0 : this.currentNews;
					this.showNews();
				}	
			} , current ));
		});
	}
    
});



var About = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        this.fontSize = Main.getInstance().localization.getLocale() == 'en' ? 'medium' : 'tiny';
    },
    
    resize : function(){	
		var fontSizes = this.calculateFontSize(this.fontSize);
		$(this.contentId + ' h1').css('font-size' , fontSizes.title);
		$(this.contentId + ' p').css({'font-size':fontSizes.text });
		var negativeMargin =  - Math.round($(this.contentId + ' h1').height() * (this.fontSize == 'medium' ? .2 : .1));
		$(this.contentId + ' h1').css('marginBottom' , negativeMargin );
		Cufon.replace(this.contentId);
		$(this.contentId + ' p').width($(this.contentI + ' h1').width());
		MainUI.alignContent(this.contentId);
	}
    
});


var Philosophy = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
    },
    
   resize : function(){	
		var fontSizes = this.calculateFontSize('medium');
		$(this.contentId).css('font-size' , fontSizes.text);
		$(this.contentId + ' h1').css('font-size' , fontSizes.title);
			
		Cufon.replace(this.contentId);
		var negativeMargin =  - Math.round($(this.contentId + ' h1 span:eq(0)').height() * .2);
		$(this.contentId + ' h1').css('marginBottom' , negativeMargin * .75 );
		$(this.contentId + '  h1 span:eq(0)').css('marginBottom' , Math.round(negativeMargin) );

		MainUI.alignContent(this.contentId);
	}
    
});



var Client_list = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        MainUI.getInstance().toggleWait(true);
        MainUI.getInstance().busy = true;
        $(this.contentId).css({visibility:'hidden' , opacity:0});
		this.loadedItems = 0;
		this.nbItems = $(this.contentId + ' ul li img').size();
		$(this.contentId + ' ul li a').click(function(e){
			e.preventDefault();
			var url = '/' + Main.getInstance().localization.getLocale() + '/' + $(this).attr('href')
			Main.getInstance().navigator.gotoURL(url);
		});
		
		var current = this;	
		$(this.contentId + ' ul li img').each(function(i){
			var imgParent = $(this).parent();
			$(this).load(function(){
				$(this).unbind('load');
				current.loadedItems++;
				
				if(current.loadedItems >= current.nbItems){
					setTimeout(function(){
						$.proxy(current.loadComplete(), current);
					} , 1000);
				}
			});
		});

    },
    
    
    appear : function(){},
	
	loadComplete : function(){
		 $(this.contentId).css({visibility:'visible' , opacity:1});
		
		$(this.contentId + ' ul li img.off').mouseover(function(){
			var imgParent = $(this).parent();
			$(this).hide();
			$(imgParent).find('.on').show();
		});
		
		$(this.contentId + ' ul li img.on').mouseout(function(){
			var imgParent = $(this).parent();
			$(this).hide();
			$(imgParent).find('.off').show();
		});
		
		MainUI.getInstance().toggleWait(false);
		this.resize();
		if(MainUI.getInstance().direction != undefined)
			this.showBackground(MainUI.getInstance().direction);
		else
			this.showContent(undefined);
	},
	
	resize : function(){
		var contentRatio = .58;
		var toPercent;
		var dimensions = MainUI.getInstance().calulateContentSize(contentRatio);		
		toPercent = dimensions.width / $(window).width() * 100;
		$(this.contentId).css('width' , toPercent + '%');
		MainUI.getInstance().centerX(this.contentId);
		$(this.contentId).centerY();
	}
    

});



var Client_item = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        $(this.contentId + ' a').lightBox();
		$(this.contentId).css({opacity : 0 , visibility:'hidden' ,  position:'absolute' , height:$(this.contentId + ' ul').height() , width:$(this.contentId + ' ul').width()});
		MainUI.getInstance().toggleWait(true);
		this.loadedItems = 0;
		$(this.contentId + ' ul').css({ margin:0 , left:0 , top:0})
		this.nbElements = $(this.contentId + ' ul li').size();
		var current = this;
		$(this.contentId + ' ul li').each(function(i){
			var imgLoader = new Image();
			$(imgLoader).load(function(){
				current.loadedItems++;
				if(current.loadedItems >= current.nbElements)
					current.appear();
			});
			imgLoader.src = $(this).backgroundImageUrl();
		});
    },
    
   appear:function(param_delay){
   		if(this.loadedItems  != this.nbElements)
   			return false;
   			
   		MainUI.getInstance().toggleWait(false);	
   		$(this.contentId).css({ visibility:'visible'});
   		this.parent();
   },
    
   resize : function(){
   		$(this.contentId).css("top", ( jQuery(window).height() - $(this.contentId).height() ) / 2  + jQuery(window).scrollTop() + "px");
   		$(this.contentId).centerX();
   }
    
});




var Contact = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        $(this.contentId).width('70%');
		$(this.contentId + ' address').html(MainUI.getInstance().addSpan(this.contentId + ' address' , true ,  '<br>'));	
		$(this.contentId + ' .linkbutton').click(MainUI.getInstance().pressNavigationLink);
    },
    
   resize : function(){
		var fontSizes = this.calculateFontSize('small' , false);
		$(this.contentId).css('font-size' , fontSizes.text);
		$(this.contentId + ' address').css('font-size' , fontSizes.title);
		Cufon.replace(this.contentId + ' a' , {hover:true}); 
		Cufon.replace(this.contentId); 
		var negativeMargin =  - Math.round($(this.contentId + ' address span:eq(0)').height() * .15);
		$(this.contentId + ' address span').css('marginBottom' , negativeMargin );
		MainUI.alignContent(this.contentId);
	}

});


var Map = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        this.latlng = new google.maps.LatLng(46.1963213, 6.1391419);
		var stylez = [ {  featureType: "all", elementType: "all", stylers: [{ saturation:-100 }]}];
		
		var mapOptions = {
			draggable:false,
			scrollwheel:false,
			disableDefaultUI: true,
			zoom: 16,
			center: this.latlng,
			mapTypeControlOptions: {mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'hiphop']}
		};
		  
		$(this.contentId).append('<span id="map_title">M&CSaatchi</span><img src="/static/img/mappuce.png" id="map_puce">');
		$('#map_title').css({'fontSize': 80 , color:'#000000'});
		Cufon.replace('#map_title');
		var pos = $('#map_puce').position();
		$('#map_title').css({'top':pos.top -  $('#map_title').height() + 15 , 'left':pos.left - Math.round($('#map_title').width() * .2) })

		this.map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
		var styledMapOptions = {name: "Hip-Hop"}
		var jayzMapType = new google.maps.StyledMapType( stylez, styledMapOptions);
		this.map.mapTypes.set('hiphop', jayzMapType);
		this.map.setMapTypeId('hiphop');		
    },
    
    showBackground: function(param_direction , param_delay){
		$('#content').append($('#gmap'));
		$('#content').append($(this.contentId));
		this.resize();
		var direction = this.opposites[param_direction];		
		var coord = this.tabOffset[direction];
		var tabContentOffset =  {top:$(window).height() , left:$(window).width() , bottom:-$('#gmap').height()  , right:-$('#gmap').width() };

		var animationProperties = {};
		animationProperties[coord] =  $('#gmap').css(coord);
		cssProperties = {}
		cssProperties[coord] = tabContentOffset[direction];
		$('#gmap').css(cssProperties).show().animate(animationProperties , this.backgroundTransitionTime , 'easeOutExpo' ,   $.proxy(function(){
			this.cleanup();
		}  , this));
		
		var startPos =  {top:$(window).height() +100 , left:$(window).width() + 100 , bottom:-$(this.contentId).height() - 100 , right:-$(this.contentId).width() - 300  };
		this.showContent(param_direction , this.backgroundTransitionTime * .6 , undefined ,  {initialPos:startPos})
	},
    
   disappear:function(){
		$('#gmap').addClass('previoussection');
		this.parent();
	},
    
	resize : function(){	
		$('#gmap').width($(window).width());
		$('#gmap').height($(window).height());
		$('#gmap').centerX();
		$('#gmap').centerY();
		google.maps.event.trigger(this.map,'resize');
		this.map.setCenter(this.latlng);
		$(this.contentId).centerX();
		$(this.contentId).centerY();
	}
    
});


var Jobs = new Class({
    Extends: BaseSection,
    
    initialize: function(param_definition){
        this.parent(param_definition);
        $(this.contentId).width('70%');
    },
    
   resize :function(){
		var fontSizes = this.calculateFontSize('medium');
		$(this.contentId).css('fontSize' , fontSizes.text);
		$(this.contentId + ' h1').css('fontSize' , fontSizes.title);
		Cufon.replace(this.contentId + ' a' , {hover:true}); 
		Cufon.replace(this.contentId); 
		var negativeMargin =  - Math.round($(this.contentId + ' h1').height() * .16);
		$(this.contentId + ' h1').css('marginBottom' , negativeMargin);
		MainUI.alignContent(this.contentId);
	}

});


var Network = new Class({
    Extends: BaseSection,
    initialize: function(param_definition){
        this.parent(param_definition);
    },
    
    resize : function(){
		var fontSizes = this.calculateFontSize('medium');
		$(this.contentId + ' h1').css('font-size' , fontSizes.title);
		$(this.contentId + ' p').css('font-size' , fontSizes.text);
		$(this.contentId + ' a').css('font-size' , fontSizes.text);
		$(this.contentId + ' h1 span').css('position' , 'relative');
		$(this.contentId + ' h1 span:eq(1)').css('top' , '-20px');
		Cufon.replace(this.contentId + ' h1');
		Cufon.replace(this.contentId + ' p');
		Cufon.replace(this.contentId + ' a' , {hover:true});
		var negativeMargin =  - Math.round($(this.contentId + ' h1').height() * .15);
		$(this.contentId + ' h1').css('marginBottom' , negativeMargin);
		MainUI.alignContent(this.contentId);
	}

});


