/* ///////////////////////////////////////////////////////////////////// 
//Function to load the Json by url
/////////////////////////////////////////////////////////////////////*/
function loadJson(jsonUrl) {	
	var request = new Request.JSON({
			url: jsonUrl,
			method: 'get',
			onSuccess: function(jsonObj,jsontext) {
				// !!!!! if we want to use a date object in the feed
				 //use jsontext with decode if we add a date object ( "date": new Date(2002,04,01) ) in the json in mootools 1.2 there are a parser pb.
				/*
JsonObject = jsonObj.artry ;
				jsonGallery = JsonObject.getLast().gallery
*/
				jsonGallery = jsonObj;
				
				//setSort();
				sortGallery('null'); // using null temporarily for the sort
								
			}
		}).send();
}

/* ///////////////////////////////////////////////////////////////////// 
// Function to sort Json to create all the painting 
// Right now, the first sort display all paintings but if we click on a filter ( available or sold...) we can't go back to all painting later
/////////////////////////////////////////////////////////////////////*/
function sortGallery( sort_num ){
		
	switch(sort_num)
		{
			case 'null':
			
				var string_sort = true ;
			
			break; 
			case 1: //0 or 1 is available but the time delivery is longer for 0
			
				var string_sort = ' gallery.status == 1 && gallery.try_status < 2 ';	
						
			break; 
			case 2:
			
				var string_sort = ' gallery.status == 1 && gallery.try_status == ' + sort_num;
				
			break; 
			case 3: 
			
				var string_sort = ' gallery.status == 2 || gallery.try_status == 3';	
						
			break; 
		}     

	$('gallery').empty();
	
	//empty the arr_selection array
	arr_selection.empty();
		
	//create a small painting with the clone element and insert it in the gallery	
	jsonGallery.each(function(gallery,key) {
					
			if(eval(string_sort)){
				arr_selection.push(key); //Add a new value to the end of the paintings selection array
						
				var divPainting = $('paintingModel').getFirst().clone();//clone the basic element
				divPainting.getFirst('a.paintingThumb').erase('href'); //we don't want any link, we want to load the painting in javascript when we click
				divPainting.getFirst().addEvent('click', function(){		
					
					//Hack while facebook don't provide window.scrollTo(0,0)	right now
					FB.Canvas.setSize({width:appSize,height:0});
					
					//hack to go back to the top
					window.scrollTo(0, 0);
										
					//loadPaintingView( key ); //push painting url already call the function - don't do that two times
					pushPaintingUrl.delay(5, '', [key] );	 //delay for safari to have time to do FB.setSize
					
					//Save the current painting state
					currentPainting = arr_selection.indexOf(key);
					
				});
				
				divPainting.getFirst('.paintingThumb span').setStyle('background-image', "url(" + get_link_image( gallery.painting , 'small') + ")" );
				divPainting.getFirst('.paintingDetails a strong').set('html', gallery.title);
				divPainting.getFirst('.paintingDetails span').set('html',  gallery.artist);
				divPainting.getFirst('.paintingDetails div').set('html', gallery.width + ' x ' + gallery.height + ' cm' );
				divPainting.inject($('gallery'));
			}		
	});
	//set the gallery state and display paintings
	History.pushState({state: 'gallery'}, 'Les toiles de la galerie', gallery  ); //be aware that changing url call the listener popstate who fire loadGalleryView();
	
	//Change painting number in the painting Page  header
   	$('paintingNumber').set('html', 'Peinture ' + 1  +' sur ' + arr_selection.length  );
}
/* ///////////////////////////////////////////////////////////////////// 
//Function to return the next or previous painting key
//Note: Loop when we are at the end or begining
/////////////////////////////////////////////////////////////////////*/
function nextPaintingKey(){

	if( arr_selection.length  < 2 ) //if it's a unique painting return the same
		return arr_selection.indexOf(currentPainting); //quick fix but we should hide the nex button when 1 result is display
	if( arr_selection.indexOf(currentPainting+1) == -1 ) //if we are at the begining we loop
		return arr_selection[0];
	else
		return arr_selection[currentPainting+1] ;
}
function prevPaintingKey(){
	if( arr_selection.length  < 2 )	//if it's a unique painting return the same
		return arr_selection.indexOf(currentPainting);
	if( arr_selection.indexOf(currentPainting-1) == -1 ) //if we are at the begining we loop
		return arr_selection.getLast() ;
	else
		return arr_selection[currentPainting-1];
}
/* ///////////////////////////////////////////////////////////////////// 
//Function to push a painting Url
/////////////////////////////////////////////////////////////////////*/
function pushPaintingUrl( key ){
	//before create a new push event we check if the previsous canvas is loaded, if not we do nothing (the user is not supposed to jump a painting)
	if( bool_canvasLoaded ){
		bool_canvasLoaded =false;
		var elem = jsonGallery[key];
		//tell the browser that we change the page
		History.pushState({state: 'painting','key':key}, elem.title, elem.link /* '?state=painting&key='+key */  );
	}
}
/* ///////////////////////////////////////////////////////////////////// 
//Function to init the upload wall form
// We create an iframe and redirect the form on it. Wen the page is loaded a listener 
//stop the loading and load the painting on our new wall
/////////////////////////////////////////////////////////////////////*/
function initUploadWallForm(){
	
	//Create an iframe 
	new IFrame({
			name: 'uploadIframe',
			styles: {
				display: 'none'
			},
			src: ''
		}).inject(document.body);
	
	//function who is fired when the iframe is loaded ( don't count the first load )	
	var wallLoadedEvent = function(){
		$('uploadIframe').removeEvent('load',	wallLoadedEvent); //remove the event for next changes
				
		var wallObject = JSON.decode( $('uploadIframe').contentDocument.body.innerHTML ); //get the result as Json object
				
		//if a wall exist we display it
		if(typeof wallObject.wall != "undefined"){
			//switch
			$('uploadWallMessage').show();
			$('uploadWallError').hide();
			//load new wall
			userWall = wallObject.wall; //change a user wall var for future loadpainting
			loadPaintingView( arr_selection[currentPainting]  );
		//if not we display an error
		}else{
			//switch
			$('uploadWallMessage').hide();
			$('uploadWallError').show();
			if(typeof wallObject.error != "undefined")
				$('uploadWallError').set('html',wallObject.error); //the error from the request
			else
				$('uploadWallError').set('html','Error : Your image could not be uploaded'); //a basic error if the request return a php error
		}	
		
		//switch Back Form and loading
		$('uploadWall').show();	
		$('uploadLoading').hide();
	}
	
	$('wall').addEvent('change',function() {	
		//switch	
		$('uploadWall').hide();
		$('uploadLoading').show();
		
		$('uploadWall').set('target', 'uploadIframe'); //Change the upload target destination to the iframe
		$('uploadWall').submit();//submit the upload
		$('uploadIframe').addEvent('load',wallLoadedEvent); //Listen when the iframe is loaded. The first load of the iframe is not listened
	});

}

function try_page_init(){
	
	//init variables
	currentPainting = 0; //current painting variable to the first element
	bool_xfbmlParsed = true; //to check if a xfbml parse is running
	arr_selection = []; // an array of paintings for the sort
	bool_paintingBigView = false; 
	bool_canvasLoaded=true; //to check if something is running
	
	//hide current details
	$('paintingFooter').setStyle('opacity',0);
	$('paintingStatusBtn').erase('href'); //a reverifier
	
	//init upload wall form and event
	initUploadWallForm();
	
	//init the history script
	var History = window.History; // Note: We are using a capital H instead of a lower h
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
        var State = History.getState(); // Note: We are using History.getState() instead of event.state        
        //if it's a painting state we load the painting        
        
        if(State.data.state =='painting'){
        	loadPaintingView( State.data.key  );
        }
        else if(State.data.state =='gallery'){
        	loadGalleryView();
        }
    });
	//set  transitions effect
	paintingEffect = new Fx.Morph('painting', {
	    duration: 'normal',
	    transition: Fx.Transitions.linear.easeOut,
    	onComplete : function() {
    	
    		if(!bool_paintingBigView){ //if we are going back as wall view we show the navigation
    			$('paintingNavigation').fade('in');
				//if we are in a resize mode we make the painting act resizable
				if(resizable){
					$('closeWall').fade('in');
					paintingResizable(true);
				}
				//if the painting is small we change the link
				if( currentPaintingCoor.width < 190 )
		    		$('paintingImg').set(  'src' , newPaintingImage.src );
					
			}
			$('painting').toggleClass('imgShadow');	//add or remove the shadow
    		// Resize the window for Facebook ( no scrollbar )
			FB.Canvas.setSize();
			bool_canvasLoaded =true;
    	}
	});
	
	$('nextWall').addEvent( 'click' , function(){
		pushPaintingUrl( nextPaintingKey() );
	});
	$('prevWall').addEvent( 'click' , function(){
		pushPaintingUrl( prevPaintingKey() );
	});
	$('fullScreen').addEvent( 'click' , function(){
		switchPaintingView();
	});
	$('bigPainting').addEvent( 'click' , function(){
		switchPaintingView();
	});
	
	paintingInit();	
}

/* ///////////////////////////////////////////////////////////////////// 
//Function to load the Gallery
/////////////////////////////////////////////////////////////////////*/
function loadGalleryView(){
	
	//switch
	$('paintingPage').hide();
	$('galleryPage').show();
	bool_paintingBigView = false;
	
	//stop painting effect if exist
	if(typeof backgroundFx != "undefined"){
		backgroundFx.cancel();
	}
		
	setCanvas(); //set canvas to nothing
	bool_canvasLoaded = true;
	
	// Resize the window for Facebook ( no scrollbar )
	FB.Canvas.setSize();
}
/* ///////////////////////////////////////////////////////////////////// 
//Function to switch between fullscreen and try view
/////////////////////////////////////////////////////////////////////*/
function switchPaintingView(){
if( bool_canvasLoaded ){
	bool_canvasLoaded =false;
	if( bool_paintingBigView ){ //going back in normal view
		
		bool_paintingBigView = false;
		
		//start effects
		paintingEffect.start({
		    'width': currentPaintingCoor.width,  
			'top':	 currentPaintingCoor.top  - currentBackgroundCoor.top	, //difference between the canvas top and the background top (padding)
		    'left':	 currentPaintingCoor.left - currentBackgroundCoor.left	,
		});
		$('background').tween('height', currentBackgroundCoor.height);	
		$('backgroundImg').fade('in');
		
		//add event inactivity
		//$('canvas').addEvent.delay(300,$('canvas'),['mousemove',hideInactivity]);
		
	}
	else{ //display a fullscreen view
		
		bool_paintingBigView = true;
		
		//remove event for inactivity
		//clearTimeout(inactTimer);
		//$('canvas').removeEvent('mousemove',hideInactivity);
		
		//Save data for later (only for chrome..... as those variables are already global)
		//currentBackgroundCoor = $('background').getCoordinates();
		currentPaintingCoor = $('painting').getCoordinates();
		
		//calcul of the newBackground
		var newBackgroundHeight = ( currentBackgroundCoor.width / currentPaintingCoor.width) * currentPaintingCoor.height;
			
		//start effects
		paintingEffect.start({
		    'width': currentBackgroundCoor.width,  
			'top':	 0 ,
		    'left':	 0 ,
		});
		$('background').tween('height', newBackgroundHeight);	
		$('backgroundImg').fade('out');	
		$('paintingNavigation').setStyle('opacity',0);
		
		//Change the painting image by the bigger one
		$('paintingImg').set(  'src' , newPaintingBigImage.src );
			
		
		//if we are in a resize mode we stop that for a while
		if(resizable){
			paintingResizable(false);
			$('closeWall').setStyle('opacity',0);
		}
	}
}

}    
/* ///////////////////////////////////////////////////////////////////// 
//Function to display and parse XFBML Markup
// Note: if it's already parsing we wait and add the key in the queue
// Argument : 	
//		key -> the painting number associated with FB markups 
//		xfbmlParsed -> a boolean that say yes or not that the previous key is parsed and that we can parse this one.
/////////////////////////////////////////////////////////////////////*/
function displayXfbmlMarkup(key,xfbmlParsed){
	 
	if(xfbmlParsed){
		bool_xfbmlParsed = false; //don't parse again until it's this one is ready
		var elem = jsonGallery[key]; //get data

		//Change XFBML Facebook Markup in the page
		$('paintingLike').empty();
		new Element('fb\\:like',{"layout":"button_count","href": elem.link }).inject($('paintingLike')); //colons in namespaced tags have to be 2x escaped.
		$('paintingComments').empty();
		new Element('fb\\:comments',{"width":"520","href": elem.link }).inject($('paintingComments')); //colons in namespaced tags have to be 2x escaped.
		
		//Parse but listen the callback function
		FB.XFBML.parse($('paintingPage'),function() {
			
			//if it's a new painting that is displayed we load and display the new painting markup by calling again this function
			if(key != arr_selection[currentPainting] ){
				displayXfbmlMarkup(arr_selection[currentPainting],true); //we force the function to jump the "if check" with the "true" parameter.
			}else{
				bool_xfbmlParsed = true; //yes we can now parse again
				// Resize the window for Facebook ( no scrollbar )
				FB.Canvas.setSize();
			}	
		});
	}
}

/* ///////////////////////////////////////////////////////////////////// 
//Function to load the Painting view
//Argument : 	
//		key -> the painting number to load 
/////////////////////////////////////////////////////////////////////*/
function loadPaintingView(key){	
		
	//switch
	$('galleryPage').hide();	
	$('paintingPage').show();
	FB.Canvas.setSize();	
	
	//display infos
	var elem = jsonGallery[key];
	
	//if a userWall exist
	if( userWall != 0 ){
		wall = userWall;
		coor = userCoor
		resizable = true;
	}else{
		wall = elem.wall;
		coor = elem.coor;
		resizable = false;
	}
	
	
	//load canvas
	loadCanvas( wall, elem.painting , coor , resizable,
	
		function onComplete(){
		
			//------------------------------------
			//process Painting details
			//Fade out current details
			$('paintingFooter').setStyle('opacity',0);
			
			//Change and parse the facebook markup for this painting if a previous one is not already parsing ( checked with bool_xfbmlParsed )
			displayXfbmlMarkup(key,bool_xfbmlParsed);	
			
			//add shadow class
			$('painting').addClass('imgShadow');
			
			bool_paintingBigView = false;
			
			//change current painting
			currentPainting = arr_selection.indexOf(key);
			
			//------------------------------------
			//Preloading next and prev paintings	
			var paintingNext = new Image();	
			paintingNext.src = get_link_image( jsonGallery[nextPaintingKey()].painting , appSize);	
			var paintingPrev = new Image();	
			paintingPrev.src = get_link_image( jsonGallery[prevPaintingKey()].painting , appSize);		
			//Preloading next and prev wall if a userWall is not set	
			if(userWall == 0){
				var wallPrev = new Image();	
				wallPrev.src = _IMG_WALL_URL + get_link_image( jsonGallery[prevPaintingKey()].wall + '.jpg' , appSize);
				var wallNext = new Image();	
				wallNext.src = _IMG_WALL_URL + get_link_image( jsonGallery[nextPaintingKey()].wall + '.jpg' , appSize);
			}
			
			//Change painting number in the header
   			$('paintingNumber').set('html', 'Peinture ' + (currentPainting+1)  +' sur ' + arr_selection.length  );
			
		},
		function onLoaded(){
		
			//change details while it's hidden
	    	$('paintingTitle').set('html', elem.title);
			$('paintingSize').set('html', elem.width + ' x ' + elem.height + ' cm' );
			$('paintingStatusBtn').set('href', elem.link + '?try=true' ); // change this with a real try link later
			
			//display back details in same time as painting
   			$('paintingFooter').fade.delay(800, $('paintingFooter'), ['in']);
		
		}
	);		
}

 


