var Prodeo = Prodeo || {};

function isEmpty(obj) {
	for(var prop in obj) {
		if(obj.hasOwnProperty(prop))
			return false;
	}
	return true;
};


Prodeo.controller = function(){
	var self = {};
	var page,
		filtre,
		contenu;
	var coefPage = {contenu:.1,rubrique:.25,home:.15};
	var moving = false;
	var $volet = $('#volet');
	var $bg = $('#bg');
	var $img_bg = $('img_bg');
	var bgW,bgH;
	var savedOverlayX;
	var curIdx = 0;
	self.diapoTimeout = 0;
	var montimer = 0;
	self.typePage = 'home';
	self.current = {};
	self.realisations = false;
	self.projet = false;
	self.clients = false;

	var _init = function(){
		
		$('#bt_open_projet').click(self.animOpenVolet);
		

		$('img.center_vertical ').load(function(){
			
				var parentH = $(this).parents().find('.vertical_wrapper').height();
				var posY  = (parentH - $(this).height() )/2;
			
				$(this).css( {top:posY} );
				self.verticalCenter();
		});
		
		$('.menu').click(function(){
			
			

			self.changeHash($(this).attr('id'),'p');
			
			$.bbq.removeState('c','a');
			$('.submenu').removeClass('subactif');
			
			return false;
		});
		$('.vdo_togglePlayPause').click(_playPauseVideo);
		$('.submenu').click(function(){
				
				$('.submenu').removeClass('subactif');
				$(this).addClass('subactif');

				self.changeHash($(this).attr('rel'),'c');
				return false;
			});
		$('.scat_filter').unbind('click');
		$('.scat_filter').live('click',_filterScat);

		self.verticalCenter();

		$(window).resize(self.resizeFullScreen);

		$(window).resize(self.verticalCenter);
		
		$(window).bind('hashchange', self.watchHash);

		self.watchHash();
	};

	self.changeHash = function(menu,attr) {
		var state = $.bbq.getState();
		if(attr=='p' && self.current != eval('self.'+menu)){
			


			
			$('.menu').removeClass('actif');
			$('.menu').siblings('ul.sous_menu').slideUp();
			$('#'+menu).addClass('actif');

		}
		if(state[attr] != menu)
		{
			state[attr] = menu;
			
			$.bbq.pushState(state);
		}
		
	};
	
	self.watchHash = function(e)
	{
		
		var hash = $.bbq.getState();
		var oldPage = page;
		var oldFiltre = filtre;
		var oldContenu = contenu;

		page = hash['p'];
		filtre = hash['c'];
		contenu = hash['a'];
		
		if(hash['a'] )
		{

			$('#'+hash['p']).addClass('actif');
			$('.submenu[rel="'+hash['c']+'"]').addClass('subactif');
			
			self.openContent(true);
			self.getProjet();

		}
		else if(hash['p']  && self.current != eval('self.'+page) )
		{
			
			self.current = eval('self.'+page);
			
			_grabContent();
			
			$('#'+page).addClass('actif');
			
		}
		
		else if(hash['c']  )
		{
			currentC = hash['c'];
			$('#'+hash['p']).addClass('actif');
			$('.submenu[rel="'+hash['c']+'"]').addClass('subactif');
			self.current.displayVignettes(hash['c']);
		}
		
		else
			{
			
			if(self.current && self.current.defaultAction)
				self.current.defaultAction(hash['c']);
			}
		

	};

	self.animCloseVolet = function() {
		
		var logoArrivee = _placeLogo(0.05);
		
		if(self.realisations)
			self.realisations.hideMenuProjets(false);
		
		$('#wrapper_menu_projet').hide();
		$("#content_wrapper").hide("slide", { direction: "left" }, 50);
		$("#volet_foot").hide("slide", { direction: "left" }, 50);
		$volet.animate({width:0},{easing:'swing',duration:100,queue:true,complete: function(){
			$('#volet_gauche').css({backgroundColor:''});
			$('#ombre_gauche').hide();
			$('#bt_open_projet').css({top:logoArrivee+20}).show();
			$('#ombre_droite').hide();
		}}); 
		savedOverlayX = $('#page_overlay').css('left');
		$('#page_overlay').animate({left:0},{ queue: false,duration:100,  easing:'swing' , complete: function(){} });
		
		return false;													
	};
	
	self.animOpenVolet = function() {
		
		
		$('#bt_open_projet').hide();
		$('#volet_gauche').css({backgroundColor:'#fff'});
		$('#ombre_gauche').show();
		$('#ombre_droite').show();
		
			
		$volet.animate({width:220},{easing:'swing',duration:100,queue:true,complete: function(){
				$("#content_wrapper").show("slide", { direction: "left" }, 50);
				$("#volet_foot").show("slide", { direction: "left" }, 50);
				$('#wrapper_menu_projet').show();			
		}}); 
		$('#page_overlay').animate({left:savedOverlayX},{ queue: false,duration:100,  easing:'swing' , complete: function(){} });
		
		
		return false;
																
	};

	self.openContent = function(noAnim) {
		
		var logoArrivee = _placeLogo(coefPage[self.typePage]);
		$('#volet_gauche').css({backgroundColor:'#ffffff'});
		
		$("#logo_text").slideUp();
		$('#content_wrapper').animate( {top:logoArrivee+15},{ queue: false,  easing:'linear' , complete: function(){ self.verticalCenter(true);}});
		if(noAnim){
			$volet.stop();
			$volet.css({width:220}); 
			$volet.css({left:'94px'});
		
		}
		else{
			$volet.animate({width:220},{easing:'linear',queue:true,complete: function(){}}); 
			$volet.animate({left:'94px'},{easing:'linear',queue:false});
		}
																
	};
	self.updateBg = function(obj){
		$img_bg = obj;
		bgW = obj.width();
		bgH = obj.height();
	};

	self.resizeFullScreen = function (){
		
		if($('#home_wapper').length>0)
			 $('#bg').width($('#wrapper').width()*.64);
		else
		{
			$('#bg').css({right:0,width:''});

		}
			$bg = $('#bg');
			$img_bg = $('#img_bg');
			
			var h = $bg.height();
			
			var w = $bg.width() ;
			
			var ratioW = w/h;
			var ratioI = bgW/bgH;
			
			if(ratioW > ratioI)
				$img_bg.removeClass('masterHeight').addClass('masterWidth');
			else
				$img_bg.removeClass('masterWidth').addClass('masterHeight');
			
			var posY  = (h - $img_bg.height()  )/2;
			
			var posX = (w - $img_bg.width()  )/2;
			
			$img_bg.css( {top:posY,left:posX});
			
			var pos = $img_bg.position();
			
			$('.force_full_screen').css({width:$bg.width(),height:$bg.height()});

	};
	
	
	self.verticalCenter = function (anim){
			
			var logoArrivee = _replaceLogo(coefPage[self.typePage]);
			$('#bt_open_projet').css({top:logoArrivee+20});

			$('.center_vertical').each(function(){
				var parentH = $(this).parent().height();
				var posY  = (parentH - $(this).height() )/2;
				$(this).css( {top:posY} );
			});
			$('.parent_rel_centered').each(function(){
				var rel = $('#'+$(this).attr('rel'));
				var posrel = rel.offset();
				var posY  = posrel.top ;
				
				if($(this).height() + posrel.top + $('#volet_foot').height()+40 < $('#wrapper').height())
					if(anim!==true)
						$(this).css( {top:posY} );
					else{
						moving = true;
						$(this).animate( {top:posY},{ queue: false,  easing:'linear' , complete: function(){if(self.current.resizeScroller) self.current.resizeScroller();} }  );
					}
					
				else
				{
					var posY  = Math.max((($('#wrapper').height()-$('#volet_foot').height()-15) - $(this).height() )/2,0);

					if(anim!==true)
						$(this).css( {top:posY} );
					else{
						moving = true;
						$(this).animate( {top:posY},{ queue: false,  easing:'linear' , complete: function(){moving = false;if(self.current.resizeScroller) self.current.resizeScroller();} } );
					}
					
				}
			
				
			});
			if(self.current.resizeScroller && !moving)
				self.current.resizeScroller();

			
			

	};
	
	self.hide_overlay = function(){
		$('#page_overlay').hide();
	};
	
	self.getProjet = function(id){

		if(!id){
			var hash = $.bbq.getState();
			id = hash['a'];
		}
	
		$('#menu_list .actif').siblings('.sous_menu').slideUp();
	
		$.get('/home/projet/'+id+'/ajax',null,function(data){
	
		if(self.current.hideFleches)
			{
			self.current.hideFleches();
			
			}
		if(self.realisations)
			{
			self.realisations.hideMenuProjets();
			}
		
		
		
		
		$('#content').empty().append(data);
		self.current = self.projet;
		self.current.defaultAction();
		
	},'html');
	return false;

	};

	var _anim_closeHome = function( callBack){

		var voletDepart = $volet.offset();
		
		
		$volet.css({left:voletDepart.left});
		$volet.animate({left:"0"},{ complete:callBack } );

	};



	var _replaceLogo = function(coef) {
		
		var logoDepart = $('#logo').position();
		var logoArrivee = $('#wrapper').height()*coef;
		$('#logo').css({top:logoDepart.top}); 
		$("#logo").removeClass('center_vertical'); 
		$("#logo").css({top:logoArrivee});
		
		return logoArrivee;
	}

	var _placeLogo = function(coef) {
		
		var logoDepart = $('#logo').position();
		var logoArrivee = $('#wrapper').height()*coef;
		$('#logo').css({top:logoDepart.top}); 
		$("#logo").removeClass('center_vertical'); 
		$("#logo").animate({top:logoArrivee},{complete: function(){ } } );
		
		return logoArrivee;
	}

	

	

	var _grabContent = function(){
		
		
		self.hide_overlay();
		animDone = false;
		loadingDone = false;

		
		
		var voletDepart = $volet.position();
		
		if(voletDepart.left > 94 ) 
			_anim_closeHome(_loadContent);
		else
			_loadContent();
	
		
	};
	
	var _loadContent = function()
	{
		
		
		$('#horizontal_navigation').hide();
		
		clearTimeout(self.diapoTimeout);
		var filter = (filtre) ? '/'+filtre+'/ajax' : '/0/ajax';
		
		$(window).unbind('resize.clients');
		

		$.get('/home/'+page+filter,function(data){
			
			$('#home_wapper').remove();
			self.resizeFullScreen();
			self.typePage = 'rubrique';
			$('#content').empty().append(data);
			
			if($('#'+page).siblings('ul.sous_menu').children().length>0)
			{
				
				$('#'+page).siblings('ul.sous_menu').slideDown();
			}
			
			
			self.current = eval('self.'+page);
			
			self.current.defaultAction();
			
			
			self.openContent();
					
		});
	};
	
	var _playPauseVideo = function() {
		
		var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["vdo_bg"]:document["vdo_bg"];
		if(flash.togglePlayPause)
			{
			var playing = flash.togglePlayPause();
			console.log(playing);
			$(this).toggleClass('vdo_pause');

			}
		
		return false;
	};

	var _showVideoControls = function(state){

		switch(state){
			case 'paused' :
			case 'stopped' :
			
				$('.vdo_togglePlayPause').addClass('vdo_play');			
				$('.vdo_togglePlayPause').removeClass('vdo_pause');
				break;
		}

		$('#video_controls').fadeIn();
		clearTimeout(montimer);
		if(state.clientX+''!='undefined')
		{
			montimer = window.setTimeout('controller.hideVideoControls()',2000);
		}
	};
	
	self.hideVideoControls = function(state){
		
		switch(state){
			case 'playing' :
				$('.vdo_togglePlayPause').removeClass('vdo_play');			
				$('.vdo_togglePlayPause').addClass('vdo_pause');

				break;
		}
		$('#video_controls').fadeOut();
	};

	self.loadBackgroundImage = function(obj) {
		
		$('.pagenav').removeClass('on');
		$('.thumbnav ').removeClass('on');
		$('.thumbnav img[imgid="'+obj.attr('imgid')+'"]').parent().addClass('on');
		$('.pagenav[imgid="'+obj.attr('imgid')+'"]').addClass('on');

		curIdx = parseInt(obj.attr('idx'));
		switch (obj.attr('type'))
		{
		case 'image':
			self.hideVideoControls();
			$('#page_overlay').unbind('mousemove',_showVideoControls);
			
			clearTimeout(self.diapoTimeout);
			if($('#img_bg').length > 1){
				$('#img_bg').each(function(){
					$(this).remove();
				});
			}
			var old_img = $('#img_bg');
			
			$('#vdo_bg').remove();
			var img_bg = $('<img />').hide();
			img_bg.load(function(){
				
				
				self.updateBg($(this));
				
				self.resizeFullScreen();
				
				if(obj.hasClass('diaporama'))
				{
					self.diaporama();
				}
				
				var new_img = $(this);
				
				if(old_img.length > 0){
					old_img.hide(obj.attr('effect'),{direction:'left',duration:500},function(){$(this).remove();});
					new_img.show(obj.attr('effect'),{direction:'right',duration:480})
					}
				else
					$(this).show('fade',{duration:500});
				
			});
			img_bg.prependTo($bg);
			
			img_bg.attr('src',obj.attr('rel')).addClass('full_screen').attr('id','img_bg');

		break;
		case 'video':
			$('#vdo_bg').remove();

			$('#img_bg').remove();
			var img_bg = $('<div  >').hide();
			img_bg.prependTo('#bg');
			img_bg.addClass('force_full_screen').attr('id','vdo_bg');
			self.resizeFullScreen();
			var flashvars = {};

			flashvars.fichier = obj.attr('rel');
			flashvars.w = obj.attr('w');
			flashvars.h = obj.attr('h');

			var params = {allowScriptAccess:'always'};
			params.wmode = "transparent";

			var attributes = {};
			attributes.id = "vdo_bg";
			attributes.name = "vdo_bg";
			$('#page_overlay').mousemove(_showVideoControls);
			swfobject.embedSWF(
			"/swf/player_prodeo.swf", "vdo_bg",
			"100%", "100%",
			"10.1.52", "/assets/swf/expressInstall.swf",
			flashvars, params, attributes,function(success) {});
			
			break;
		
		}
		return false;
	};
		
	var _filterScat = function(){
		var scat = $(this).attr('rel');
		
		$('.wrapper_projet ').each(function(){$(this).removeClass('off')});
		$('.wrapper_projet ').not('.all').not('.'+scat).addClass('off');

		return false;
	};

	

	self.diaporama = function(){
		clearTimeout(self.diapoTimeout);
		self.diapoTimeout = setTimeout(self.slideNext,5000);
		
	}

	self.slideNext = function (){
		
		var maxIdx = self.current.tabimages.length-1;
		if(curIdx < maxIdx)
			curIdx++;
		else
			curIdx = 0;

		$('.pagenav[idx="'+curIdx+'"]').click();
		
		
	}
	self.slidePrev = function (){
		
		var maxIdx = self.current.tabimages.length-1;
		if(curIdx > 0)
			curIdx--;
		else
			curIdx = maxIdx;

		$('.pagenav[idx="'+curIdx+'"]').click();
		
		
	}
	_init();

return self;
};
