
var Prodeo = Prodeo || {};


Prodeo.realisations = function(params) {

	var self = {};
	var filter = params.filter;
	var liste = params.liste;
	var noAjax = params.noAjax;

	var $projets = {};
	var $bg =  $('#bg');
	var $img_bg ;
	var $menu = $('#realisations');
	var $content_wrapper = $('#realisations_wrapper');
	var $volet = $('#volet');

	var vDim = {w:278,h:201};
	var oDim = {w:278,h:201};
	
	var viewport = { w : 0 , h : 0 };

	var hMax,wMax ,nCol ,maxCol, maxRow ,nRow;
	var totalDown = nbUp = nbDown= 0;
	var $fleche_up = $('#fleche_up');
	var	$fleche_down = $('#fleche_down');
	
	var nbUp = nbDown = 0;
	var isMenuProjet = false;
	var initiated = false;
	
	var _initiate_projets = function(){
		$fleche_up = $fleche_up.detach();
		$fleche_down = $fleche_down.detach();

		$projets = $('#projets').empty().detach();
		$('#bg *:not(#img_bg)').remove();
		$projets.appendTo($bg);
		$projets.css({right:0,width:'',left:310});

		$fleche_up.appendTo($bg).hide();
		$fleche_down.appendTo($bg).hide();
		initiated = true;
	};

	var _init = function(){
		$('#fb_share').remove();
		if(noAjax){
			controller.openContent(true);
			
		}
		controller.typePage = 'rubrique';
		//console.log("viewport w"+viewport.w);
		controller.hide_overlay();
		$('#realisations_wrapper').empty();
		$('#projets_wrapper').remove();
		$menu.siblings('ul.sous_menu').slideDown();
		$menu.addClass('actif');
		$(window).unbind('resize.infiniteScroll');

		$('#volet_foot').show();
		
		$('#bg').css({left:0,right:0});
	
		
/*		hMax = screen.availHeight - 30;
		wMax = screen.availWidth - 340;

		maxCol = Math.floor(wMax / vDim.w);
		maxRow = Math.ceil(hMax / vDim.h);
		origX = 310;
*/		
		//$fleche_up = $fleche_up.detach();
		//$fleche_down = $fleche_down.detach();

		//$projets = $('#projets').empty().detach();
		
		
		$('#bg').css({left:0});
		
		_initiate_projets();
		$('#img_bg').remove();
		$img_bg = $('<img />').attr('src',"/uploads/backgrounds/bg_realisations.jpg").addClass('full_screen').attr('id','img_bg').attr('type','image');
		
		$img_bg.load(function(){
			
			controller.updateBg($img_bg);
			controller.resizeFullScreen();
			$(this).show();
			
			});

		$img_bg.prependTo($bg);
		
		
		//$projets.appendTo($bg);
		//$projets.css({right:0,width:'',left:310});

		//$fleche_up.appendTo($bg).hide();
		//$fleche_down.appendTo($bg).hide();

		hash = $.bbq.getState();
		
		$projets = $('#projets');
		_setDimensions();
		var initDelta = Math.ceil(viewport.h / vDim.h);
		$projets.css({top:-initDelta*vDim.h});

		

		self.displayVignettes(hash['c']);

		
		
		$fleche_up.css({width:''});
		$fleche_down.css({width:''});

		$bg.unbind('mouseenter');
		$bg.unbind('mouseleave');
		$bg.mouseenter(function(e){
			$fleche_up.fadeIn();
			$fleche_down.fadeIn();
		});

		$bg.mouseleave(controller.current.hideFleches);

		$projets.unbind('mousewheel');
		if(_isIpad() || _isIphone()){
			$projets.unbind('swipemove');
			//$projets.bind('swipemove',$.debounce( 75, _swipeMove ));
			$projets.bind('swipemove',_swipeMove);
			//$projets.unbind('swipeone');
			//$projets.bind('swipeone',_swipeOne);

		}
		$projets.mousewheel(_handleMouseWheel);
		$fleche_up.unbind('click');
		$fleche_down.unbind('click');
		$fleche_up.click(_moveUp);
		$fleche_down.click(_moveDown);
		

		
		$('.vdo_togglePlayPause').click(_playPauseVideo);
		$(window).bind('resize.infiniteScroll',$.debounce( 75, _resetPos ));
		

	}
	
	var _isIpad = function(){
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		return isiPad;
	};
	var _isIphone = function(){
		var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
		return isiPhone;
	};

	var _playPauseVideo = function() {
		//console.log('here');
		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;
	};
	
	

	self.displayVignettes = function(filtre) {
		
		if(filtre)
			filter = filtre;
		else
			filter='';
		_checkIfSubmenu(filtre);
		_resetPos(true);
		
	}
	
	self.defaultAction = function(){
		_init();
	};

	var _handleMouseWheel = function(e,delta) {
		e.preventDefault();
		
		if(delta>0)
			{

			_moveUp();
			}
		else
			{
			_moveDown();
			}
	};
	var _swipeMove = function(event,e){
			var deltaY = e.delta[0].lastY;
			var newTop = $projets.position().top +  deltaY;
			$projets.css({top:newTop});
			if(deltaY >0){
				_deplaceUp($('#projets div.start'));
			}
			else
			{
				_deplaceDown($('#projets div.start'));
			}

		};
	var _swipeOne = function(event,e){
			var deltaY = e.delta[0].lastY;
			var deltaRow = Math.ceil(deltaY / vDim.h);
			var direction = (deltaRow>0)?'up ':'down';
			
			for(var i=0;i<deltaRow;i++)
				{
				switch(direction){
					case 'up':
						_moveUp(deltaY);
					break;
					case 'down':
						_moveDown(deltaY);
					break;
					}
				}
			
			

		};
	var _moveUp = function(delta){

		nbUp++;
		nbUp = Math.min(nbUp,nRow);
		_deplaceUp($('#projets .wrapper_projet.start'));
		var coef = (delta) ? ($projets.position().top+delta) + nbDown*vDim.h : $projets.position().top +  nbUp*vDim.h;
		var time = 300 * nbUp;
		$projets.stop().animate(
			{top:coef},{easing:'swing',
						duration:time,
						queue:false,
						complete:function(){ 
							_deplaceUp($('#projets div.start'));
							nbUp = 0;
							}
						});
		return false;
	};



	var _moveDown = function(delta){

		nbDown++;
		nbDown = Math.min(nbDown,nRow);
		var coef = (delta) ? ($projets.position().top+delta) - nbDown*vDim.h : $projets.position().top - nbDown*vDim.h;
		var time = 300 * nbDown;
		_deplaceDown($('#projets .wrapper_projet.start'));
		$('#projets').stop().animate(
			{top:coef},{easing:'swing',
						duration:time,
						queue:false,
						complete:function(){ 
							_deplaceDown($('#projets div.start'));
							nbDown = 0;
							}
						});
		return false;
	};

	var _deplaceDown = function(obj) {
		
		$(obj).each(function(){
			var coordY = $(this).offset().top;
			
			if(coordY < 15 -(nRow * vDim.h))
			{
				
				var coords = _getBottomList();
				var maliste = _getLineFromFirst($(this));

				var nr = Math.floor(coords[1]/vDim.h) +1;
				var i = (nr * nCol ) ;
				
				$(maliste).each(function(){

					var idCol = (Math.abs(i)%nCol);
					var idRow = Math.floor(i / nCol);
					$(this).css({left:idCol*vDim.w,top:vDim.h*idRow});
					$(this).appendTo($projets);
					i++;
				});
				
			}
		});
	_changeAltProjets();
	}

	var _deplaceUp = function(obj)
	{

		$(obj).each(function(){
			
		var coordY = $(this).offset().top;
		var idCol = idRow =0;

		if(coordY > (((nRow) * vDim.h)+15))
		{
			
			var coords = _getTopList();
			var maliste = _getLineFromFirst($(this));

			var nr = Math.floor(coords[1]/vDim.h);
			var deltax =(coords[0] / vDim.w)  ;

			var i = (nr * nCol ) -1 ;

			var j = nCol-1;
			$(maliste).reverse().each(function(){
				
				var idCol = j;
				var idRow = Math.floor((i) / nCol);
				$(this).css({left:idCol*vDim.w,top:vDim.h*idRow});
				$(this).prependTo($projets);
				i--;
				j--;
			});
			
			
			
		}});
		_changeAltProjets();
	}

	var _getLineFromFirst = function(obj)
	{
		var maliste = [];
		var next = obj.nextUntil('.start').detach();
		maliste = $.merge(new Array(obj.detach()),next);
		return maliste;

	};

	var _getBottomList = function(){
		var maxY,maxY;
		maxY = maxX = 0;

		var last = $projets.children('.wrapper_projet').last();
		maxY = parseInt(last.css('top'));	
		maxX = parseInt(last.css('left'));

		return [maxX,maxY];
	};

	var _getTopList = function(){
		var maxY,maxY;
		maxY = maxX = 0;

		var first = $projets.children('.start').first();
		maxY = parseInt(first.css('top'));	
		maxX = parseInt(first.css('left'));
		
		return [maxX,maxY];
	};

	var _checkIfSubmenu = function(filtre){
		var sub_cats = [];
		if(liste[filtre])
		{
			for(var i=0 ; i < liste[filtre].length; i++)
			{
				if(liste[filtre][i].scat != 'all'){
					sub_cats.push(liste[filtre][i].scat);
					
				}

			}
			
			if(sub_cats.length >0)
				_appendFilter($('.submenu.subactif'),sub_cats);
		}
	};
	
	self.hideFleches = function(e){
		$fleche_up.hide();
		$fleche_down.hide();
	};
	


	var _appendFilter = function(obj,sub_cats) {
		
		$('.ter_menu').remove();
		var filter = $('<ul class="ter_menu"></ul>').show();
		
		if($.inArray('corporate',sub_cats)>-1)
		{
			filter.append('<li><a href="#" class="scat_filter" rel="corporate" onclick="">Corporate</a></li>');
		}
		
		if($.inArray('grand_public',sub_cats)>-1)
		{
			filter.append('<li><a href="#" class="scat_filter" rel="grand_public" onclick="">Grand public</a></li>');
		}
		filter.appendTo(obj.parent()).slideDown();

		return filter;
	};

	var _createDomElement = function(data,idRow,idCol){

		var element = $('<div class="wrapper_projet '+data.scat+'"></div>').attr('id','div'+$projets.children().length).css({position:'absolute',width:vDim.w-2,height:vDim.h-2,top:(vDim.h*idRow),left:(vDim.w*idCol)});
			
		var lien= $('<a href="/home/projet/'+data.id+'" class="lien_projet" ></a>').attr('rel',data.id).attr('idx',count).attr('cat',data.cat);
		var img = $('<img />').attr('src',data.image).attr('border',0).addClass('hidden');
		
		var titre = $('<div class="titre_projet"><a href="/home/projet/'+data.id+'" style="color:white" >'+data.titre+'</a></div>').css({position:'absolute',bottom:0,right:0,left:0});
		img.appendTo(lien);

		lien.appendTo(element);
		
		titre.appendTo(element);
		
		img.load(function(){
			$(this).fadeIn();
		});

		element.hover(function(){
			$(this).children('.titre_projet').show();
		},function(){
			$(this).children('.titre_projet').hide();
		});

		lien.click(function(){
			controller.changeHash($(this).attr('rel'),'a');
			return false;
		});

		return element;
	};
	var _resetPos = function(init) {
	
		var i=0;
		var oldNCol = nCol;
		var oldNRow = nRow;
		_setDimensions();

		//var nbElements = $projets.children('.wrapper_projet').length;
		var newnRow = Math.ceil(viewport.h / vDim.h);

		//console.log('viewport width:'+viewport.w);
		if(nCol != oldNCol || newnRow != nRow || init)
		{

			_injectList();
			_changeAltProjets();
			$projets.animate({top:-nRow*vDim.h});

		}
		else{

			nCol = oldNCol;
			nRow = oldNRow;
		}

	}

	var _changeAltProjets = function(){
		$(window).unbind('resize.infiniteScroll');
		
		var i=count=0;
		$projets.children('.wrapper_projet').each(function()
		{

			if(count%nCol==0)
				$(this).addClass('start');
			else
				$(this).removeClass('start');

			if(nCol%2==1)
				{
					if(count%nCol==0)
						{
						count = 0;
						}
					if(count%2==0){
						$(this).removeClass('alt_projet');
					}
					else
					{
						$(this).addClass('alt_projet');
					}
				}
				else{
					if(count%2==0)
						$(this).addClass('alt_projet');
					else
						$(this).removeClass('alt_projet');
				}
			count++;
			i++;
		});

		$(window).bind('resize.infiniteScroll',$.debounce( 75, _resetPos ));
	}
	
	var _setDimensions = function(){
		
		
		viewport = { w : $('#projets').width() , h : $('#bg').height() };
		
		//console.dir(viewport);
		//console.dir($bg);
		
		nCol = Math.round(viewport.w / oDim.w);

		vDim.w = Math.round(viewport.w / nCol);
		vDim.h = Math.round(oDim.h * vDim.w /oDim.w);
		nRow = Math.ceil(viewport.h / vDim.h);


	};

	var _calculeQuantite = function(){

		_setDimensions();

		var hauteurMax = screen.availHeight - 30;
		var largeurMax = screen.availWidth - 340;

		var nombreColonnes = Math.round(viewport.w / oDim.w);


		var nombreLignes = Math.ceil(viewport.h / vDim.h);

		var nombreAffiche = nombreColonnes * nombreLignes *3 ;// 3 pages pleines pour avoir du rabe
		var reste = nombreColonnes - (nombreAffiche % nombreColonnes); // le nombre de case manquant pour finir la dernière ligne

		var quantite = nombreAffiche + reste; // le nombre
		
		return quantite;
	};

	var _buildListe = function(maliste){
		var idx;
		
		var nMin = _calculeQuantite();
		var finalListe = [];
		for(var i=0;i<nMin;i++)
		{
			idx = i%maliste.length;
			finalListe.push(maliste[idx]);
		}
		return finalListe;
	};

	var _injectList = function() {

		$projets.children('.wrapper_projet').remove();

		var i = count = 0;
		var elt = new Object();
		if(filter!='')
			var listeOptimisee = _buildListe(liste[filter]);
		else
		{
			var maliste = [];
			$.each(liste,function(key,value){
				
				maliste = $.merge(maliste,value);

			});
			var listeOptimisee = _buildListe(maliste);
			
		}
		while(listeOptimisee[i]){

			var idCol = (count%nCol);
			var idRow = Math.floor(count / nCol);
			$projets.append(_createDomElement(listeOptimisee[i],idRow,idCol));
			count ++;
			i++;

		}
	};
	var _searchListe = function(liste,key,val){

		for(var i=0;i<liste.length;i++)
		{
		if ( liste[i][key]==val)
		{
			return i;
		}
		}
		return -1;
	}

	self.navigateListe = function() {
	
		if($(this).hasClass('current')){
			
			$('#menu_projet').click();
		}
		else
		{
			var obj = $(this);
			var maliste = liste[obj.parent().attr('rel')];
			
			var curIndex = _searchListe(maliste,'id',obj.siblings('.current').attr('rel'));
		
			switch (obj.attr('rel'))
			{
			case 'prev':
				var nextIndex = (curIndex>0)?curIndex-1 : maliste.length-1;
				break;
			case 'next':
				var nextIndex = (curIndex<maliste.length-1)?curIndex+1 : 0;		
				break;
			}
			
			//controller.getProjet(maliste[nextIndex].id);
			controller.changeHash(maliste[nextIndex].id,'a');
		}
		return false;
	}
	
	var _creeMenuProjets = function(nbCol,filtre)
	{
		
		var wbg = $('#bg').width();
		var xProj = $('#projets').position().left;

		var newRight = wbg - (xProj+(nbCol*oDim.w));
		$projets = $projets.detach();

		$projets.appendTo($bg);
		
		$projets.css({right:'',width:nbCol*oDim.w,backgroundColor:'#ffffff'});
		
		//console.dir($projets.css('width'));
		_setDimensions();
		self.displayVignettes(filtre);
		$projets.unbind('mousewheel');

		$projets.mousewheel(_handleMouseWheel);

	}
	self.showMenuProjets = function(filtre) {
		if(!initiated)
			_initiate_projets();
		isMenuProjet = true;
		_creeMenuProjets(1,filtre);
		var origX = $('#volet').width()+parseInt($('#volet').css('left'));
		$projets.css({left:origX-(1*vDim.w)});
		$projets.show();
		$('#menu_projet').show();
		$projets.animate({left:origX},{ queue: false,  easing:'linear' , complete: function(){	
			$('#fleche_up').css({right:'',width:vDim.w}).appendTo($('#bg'));
			$('#fleche_down').css({right:'',width:vDim.w}).appendTo($('#bg'));
			} });
		$('#page_overlay').animate({left:314+(1*vDim.w)},{ queue: false,  easing:'linear' , complete: function(){} });
		
		$('#ombre_droite').clone().attr('id','ombre_menu').css({right:'',left:0}).prependTo('#wrapper_menu_projet');
	}

	self.destroyMenuProjets = function() {
		$(window).unbind('resize.infiniteScroll');
		self.hideFleches();
		if(!isEmpty($projets)){
			$projets.empty().hide();
		
			$('#page_overlay').css({left:314});
			$projets.css({backgroundColor:''});
		}

	}
	self.hideMenuProjets = function(anim) {
		
		self.hideFleches();
		$(window).unbind('resize.infiniteScroll');
		
		isMenuProjet = false;
		if(anim===true)
		{
			var posBt = $volet.width()+parseInt($volet.css('left'));
			$projets.animate({left:posBt-$('#projets').width()},{ queue: false,  easing:'linear' , complete: function(){$('#ombre_menu').remove();$projets.children().remove();} });
			$('#page_overlay').animate({left:314},{ queue: false,  easing:'linear' , complete: function(){} });
			$projets.css({backgroundColor:''});
		}
		else
		{
			if(!isEmpty($projets)){
				var posBt = $volet.width()+parseInt($volet.css('left'));
				$projets.css({left:posBt-$projets.width()});
				$('#ombre_menu').remove();
				$projets.children().remove();
				$('#page_overlay').css({left:314});
				$projets.css({backgroundColor:''});
			}
		}
	}
	//_init();

return self;
}
