/* ///////////////////////////////////////////////////////////////////// 
// This is the app that is used to display painting on a wall
// You can move the painting on the wall if the user is allowed
// Cookies are saved for later purpose
// The closeWall event is define here :  delete cookies and put pack the main wall
// The navigation is define here : go one painting ahead or go back one painting
/////////////////////////////////////////////////////////////////////*/

/* /////////////////////////////////////////////////////////////////////
//function resize to add the resize property to each corner of the painting
/////////////////////////////////////////////////////////////////////*/
function resize( handler , invert ){
	return $('painting').makeResizable({
						
			limit: {x: [75, 600],y:[75, 600]},
			handle:handler,
			onStart: function(){
				//save last coordinates before we resize				
				currentPaintingCoor = $('painting').getCoordinates();	
				
				//show a special cursor for the action ( remove the painting cursor )
				$(document.body).addClass('resizable');
				$('handler').removeClass('draggable');
				
				//delete painting events
				$('painting').removeEvents();
				
				//new event to check where is the mouse when we stop dragging and show or not the resizable corner
				mouseInside=false;
				$('painting').addEvent('mouseup', function(event){
					mouseInside=true;
				});
				
				//We add an event to listen if we leave the main window when resizing (usefull with iframe)
				//If we leave we stop the resizing and put evrythingback to normal by calling makeresiable complete event
				$(document.body).addEvent('mouseleave', function(){				
					this.stop('mouseup'); //stop the resize and fire complete event with mouseup ( who then stop this listener )
				}.bind(this) );
	
			},
			invert:invert,
			onDrag: function(){				
				
				var newPaintingCoor = $('paintingImg').getCoordinates(); //dont get the "painting" div coor because height is not the real paintingheight
				//change the position of the image to resize by the middle ( current position + (size of the current - size of the new one )/2 )
				$('painting').setStyles({ 
					'top'	: (currentPaintingCoor.top  - currentBackgroundCoor.top)   + ( ( ( currentPaintingCoor.height - newPaintingCoor.height ) ) / 2 ) +'px',
					'left' 	: (currentPaintingCoor.left  - currentBackgroundCoor.left) + ( ( ( currentPaintingCoor.width  - newPaintingCoor.width  ) ) / 2 ) +'px'
				});
				
				//hook to avoid a big height for the painting and not be able to drag everywhere
				$('painting').setStyle('height', '');
				
				//update the coor data after the change
				newPaintingCoor = $('paintingImg').getCoordinates(); 
				
				//check if the painting is out of the canvas
				if( newPaintingCoor.top < currentBackgroundCoor.top ){
					$('painting').setStyle('top', 0 );
				}
				if( newPaintingCoor.left < currentBackgroundCoor.left ){
					$('painting').setStyle('left', 0 );
				}
				if( ( newPaintingCoor.right )  >  currentBackgroundCoor.right ){
					$('painting').setStyle('left', currentBackgroundCoor.right - newPaintingCoor.width  );
				}
				if( ( newPaintingCoor.bottom )  >  currentBackgroundCoor.bottom ){
					$('painting').setStyle('top', currentBackgroundCoor.height - newPaintingCoor.height  );
				}
				
			},
			onComplete: function(){
				
				//remove the leave window listener
				$(document.body).removeEvents('mouseleave'); 
				
				//put back the right cursor
				$(document.body).removeClass('resizable');
				$('handler').addClass('draggable');
				
				//give back the hover paiting effect
				paintingHover();
				
				//check where is the mouse to fire the event
				if(mouseInside)
					$('painting').fireEvent('mouseover');
				else 
					$('painting').fireEvent('mouseout');
					
					
				//delete the event
				$('painting').removeEvents('mouseup');
				
				//check if the painting has a bigger height than the canvas
				if($('painting').getStyle('height').toInt() > currentBackgroundCoor.height ){
					
					//set position of the image for a new background
				 	$('painting').setStyle('width', currentBackgroundCoor.width / 3);
				 	$('painting').setStyle('height', ''); //Change the heigth to fit the painting after width modification
					$('painting').position({relativeTo: 'background'});
					
				}
				//check if the painting has a bigger width than the canvas
				if($('painting').getStyle('width').toInt() > currentBackgroundCoor.width ){
					
					//set position of the image for a new background
				 	$('painting').setStyle('width', currentBackgroundCoor.width / 3);
				 	$('painting').setStyle('height', ''); //Change the heigth to fit the painting after width modification
					$('painting').position({relativeTo: 'background'});
					
				}		
				//save data for next time
				saveCoor();
				
				//change the image link if the limit is here
				if( $('painting').getStyle('width') < 190 )
	    			$('paintingImg').set(  'src' , newPaintingImage.src );
	    		else
	    			$('paintingImg').set(  'src' , newPaintingBigImage.src );
			}								
	})
}
/* /////////////////////////////////////////////////////////////////////
//function who save the coordinates of the painting for a given background in a cooki 
/////////////////////////////////////////////////////////////////////*/
function saveCoor(){
	//Get Data
	currentPaintingCoor = $('painting').getCoordinates();
				
	//build the coor string
	userCoor = 	(currentPaintingCoor.left - currentBackgroundCoor.left )	+ '_' + //painting-left(from the backgroundImg
				(currentPaintingCoor.top  - currentBackgroundCoor.top ) 	+ '_' +	//painting-top(from the backgroundImg)
				currentPaintingCoor.width  									+ '_' +	//painting-width
				currentBackgroundCoor.width								;		//background-width
	
	//write cookies details
	Cookie.write( currentWall ,userCoor ,{duration:15,path:'/'} );
	
}
/* /////////////////////////////////////////////////////////////////////
//function who set what happend when the mouse is hover the painting div
/////////////////////////////////////////////////////////////////////*/
function paintingHover(){
	//make the painting be transparent or not
  	$( 'painting' ).addEvent(	'mouseover'	, function(){$('paintingImg').setStyle('opacity',0.8);});
  	$( 'painting' ).addEvent(	'mouseout'	, function(){$('paintingImg').setStyle('opacity',1);});
	//make the resizable icon hide on mouseout
	$( 'painting' ).addEvent( 
		'mouseout'	, 
		function(){
			$(	'resizeL'	).hide();
			$(	'resizeR'	).hide();
			$(	'resizeBL'	).hide();
			$(	'resizeBR'	).hide();
			$(	'bigPainting'	).hide();
		}
 	);
 	//make the resizable icon show on mouseover
 	$( 'painting' ).addEvent( 
		'mouseover'	, 
		function(){
			$(	'resizeL'	).show();
			$(	'resizeR'	).show();
			$(	'resizeBL'	).show();
			$(	'resizeBR'	).show();
			$(	'bigPainting'	).show();
			
		}
 	);
}
/* /////////////////////////////////////////////////////////////////////
// Make the painting resizable or not
//Argument : bool_resizable -> true or false if the painting should be resizable or not
/////////////////////////////////////////////////////////////////////*/
function paintingResizable(bool_resizable){
	if(bool_resizable){
		//hide the painting link
		$('fullScreen').hide();
		
		//make the painting draggable and resizable and not linkable
	    draggablePainting.attach();
	    $('handler').addClass('draggable');
	    
	    resizeLeft.attach();
	    resizeRight.attach();
	    resizeBottomLeft.attach();
	  	resizeBottomRight.attach();
	  	
	  	paintingHover();
	  	
	}else{
		//show the painting link
		$('fullScreen').show();
		
		draggablePainting.detach();
		$('handler').removeClass('draggable');
		
		$('painting').fireEvent('mouseout');
		
		resizeLeft.detach();
	    resizeRight.detach();
	    resizeBottomLeft.detach();
	  	resizeBottomRight.detach();
	  	
	  	//delete painting events
		$('painting').removeEvents();
	}
}


/* /////////////////////////////////////////////////////////////////////
// Function to load the canvas
/////////////////////////////////////////////////////////////////////*/

function loadCanvas( wall, painting, coor, resizable, onComplete, onLoaded ){	
	
	//remove event for inactivity
	//$('canvas').removeEvent('mousemove',hideInactivity);
	//clearTimeout(inactTimer);
				
	newWallImage = new Image();
	newPaintingImage = new Image();
	newPaintingBigImage = new Image();
		
	//Step 1 : When Wall is loaded	load the painting	
	newWallImage.onload = function() {
		
		//Step 2: When painting is loaded	
		newPaintingImage.onload = function() {
		
			//Step 3: When Big painting is loaded	
			newPaintingBigImage.onload = function() {
		
				//Step 3 : Set the painting on the canvas		
				//remove the loading
				$('paintingLoading').hide();
				//-----------------------------
				//Get new coor for painting and background on the canvas
				var newPaintingCoor = new Object();	
				currentBackgroundCoor = $('background').getCoordinates();
				var newBackgroundHeight = ( currentBackgroundCoor.width / newWallImage.width) * newWallImage.height;
												
			 	//if coor exist we load the new position (painting-left, painting-top, painting-width, background-width)
				if(coor != ''){
					coor = coor.split('_');	 	
					
					var percent = currentBackgroundCoor.width / coor[3];					
										
					newPaintingCoor.width = percent * coor[2];
					newPaintingCoor.height = newPaintingImage.height / ( newPaintingImage.width / newPaintingCoor.width );
					newPaintingCoor.top  = ( percent * coor[1] ) ;
					newPaintingCoor.left = ( percent * coor[0] ) ;
					newPaintingCoor.bottom = newPaintingCoor.top + newPaintingCoor.height;
										
					//check if the painting is out of the canvas
					if( newPaintingCoor.top < 0 ){
						newPaintingCoor.top = 0;
					}
					if( newPaintingCoor.left < 0 ){
						newPaintingCoor.left = 0;
					}
					if( newPaintingCoor.right  >  currentBackgroundCoor.width ){
						newPaintingCoor.left = currentBackgroundCoor.width - newPaintingCoor.width;
					}
					if( newPaintingCoor.bottom  >  newBackgroundHeight ){
						newPaintingCoor.top = newBackgroundHeight - newPaintingCoor.height;
					}
						
					//check if the painting is not bigger than the canvas if yes we set as new wall
					if(newPaintingCoor.height > newBackgroundHeight || newPaintingCoor.width > currentBackgroundCoor.width ){
						//set position of the image as a new wall
						newPaintingCoor.width = currentBackgroundCoor.width / 3;
						newPaintingCoor.height = newPaintingImage.height / ( newPaintingImage.width / newPaintingCoor.width );
						newPaintingCoor.top = ( currentBackgroundCoor.height - newPaintingCoor.height ) / 2 ;
						newPaintingCoor.left = ( currentBackgroundCoor.width - newPaintingCoor.width ) / 2 ;
					}
								
				}else{
					//set position of the image as a new wall
					newPaintingCoor.width = currentBackgroundCoor.width / 3;
					newPaintingCoor.height = newPaintingImage.height / ( newPaintingImage.width / newPaintingCoor.width );
					newPaintingCoor.top = ( currentBackgroundCoor.height - newPaintingCoor.height ) / 2 ;
					newPaintingCoor.left = ( currentBackgroundCoor.width - newPaintingCoor.width ) / 2 ;
				}
				 
				//make a transition to change the background with a cool visual effect		
				backgroundFx = new Fx.Tween('background', {
				    duration: 'normal',
				    transition: Fx.Transitions.linear.easeOut,
				    onComplete : function() {
				    	//We can now change images Links   	
				    	$('backgroundImg').erase('src');
			    		$('backgroundImg').set( 'src' 	, newWallImage.src ); 
			    		
			    		$('paintingImg').erase('src');
			    		if( newPaintingCoor.width < 190 )
			    			$('paintingImg').set(  'src' , newPaintingImage.src );
			    		else
			    			$('paintingImg').set(  'src' , newPaintingBigImage.src );
			    			
			    		//change the painting coor
			    		$('painting').setStyles({
						 	'width': newPaintingCoor.width	,  
							'top':	 newPaintingCoor.top	,
						    'left':	 newPaintingCoor.left	
						 });						 
						 
						//create last effect to display the new painting and sometimes a new background
						$('paintingNavigation').fade.delay(600, $('paintingNavigation'), ['in']);
			    		$('backgroundImg').fade.delay(600, $('backgroundImg'), ['in']);
			    		$('painting').fade.delay(1000, $('painting'), ['in']);
			    		
			    		//if resizeable we display a close button
			    		if(resizable)
			    			$('closeWall').fade.delay(600, $('closeWall'), ['in']);
			    		
			    		//allow next loadcanvas query
			    		//we should wait the end of the last fading but it's almost ok
						bool_canvasLoaded = true;
						
						//update current background Coor
						currentBackgroundCoor = $('background').getCoordinates();
						currentPaintingCoor = $('painting').getCoordinates();
						
						// Hide some element after a certain delay of inactivity on the canvas
						//$('canvas').addEvent.delay(2000,$('canvas'),['mousemove',hideInactivity]); //delay the event to have a nice effect
						//inactTimer = $('paintingNavigation').set('fade', {duration: 'long'}).fade.delay(5000, $('paintingNavigation'), ['out']);
						
						onLoaded();
			    	}
				});	
				
				//Create transition fade for the painting and background opacity and transition toward the new background height
				backgroundFx.start.delay(300, backgroundFx, ['height', newBackgroundHeight]); //delay this effect to be in sync with bakgroundimg opacity fade
				$('painting').fade('out');
				
				//check if the wall is changing for a fading or not
				if( currentWall != wall ){
					$('backgroundImg').fade.delay(300, $('backgroundImg'), ['out']); //delay the background fading for sweet effect with painting fading 
					$('paintingNavigation').fade.delay(300, $('paintingNavigation'), ['out']);
					//if resizable we fading the close wall button too
					if(resizable)
			    		$('closeWall').fade.delay(300, $('closeWall'), ['out']);
				}	
				
				//-----------------
				//Make it resizable or not
				paintingResizable(resizable);		  	
				
				//save the current wall number for cookies and to check if the next loading wall is similar 
				currentWall = wall; 
				
				//call a onComplete function when loadCanvas is done
				onComplete();
			}
		 	newPaintingBigImage.src = get_link_image( painting , appSize )  ;
		 	
		 	newPaintingBigImage.onerror= function(){
		    	bool_xfbmlParsed = true; //we force to parse XFBML markup again
		    	//if no connection we try again with a delay to save cpu
		    	loadCanvas.delay(3000,this,[wall, painting, coor, onComplete, onLoaded]);
	    	}	

			 
	 	}
	 	newPaintingImage.src = get_link_image( painting , 'small')  ;
	 	
	 	newPaintingImage.onerror= function(){
	    	bool_xfbmlParsed = true; //we force to parse XFBML markup again
	    	//if no connection we try again with a delay to save cpu
	    	loadCanvas.delay(3000,this,[wall, painting, coor, onComplete, onLoaded]);
    	}	
    	
	}
	newWallImage.src = _IMG_WALL_URL + get_link_image( wall + '.jpg' , appSize ) ;

	//Display a Loading image if wall and painting are not preloded
	if( !newWallImage.complete || !newPaintingImage.complete || !newPaintingBigImage.complete ){
        $('paintingLoading').show();
    }
    
    //keep tracking of a lost connexion or a not loaded image to be able to load the painting again
    newWallImage.onerror= function(){  	
    	bool_xfbmlParsed = true; //we force to parse XFBML markup again
    	//if no connection we try again with a delay to save cpu
    	loadCanvas.delay(3000,this,[wall, painting, coor, onComplete, onLoaded]);
    }
    
}
/* /////////////////////////////////////////////////////////////////////
// Function hide everything on the canvas ( painting, wall, button ...)
/////////////////////////////////////////////////////////////////////*/
function setCanvas(){
	
	//Hide current images and Nav
	$('painting').setStyle('opacity',0);
	$('backgroundImg').setStyle('opacity',0);
	$('background').setStyle('height','');

	$('paintingNavigation').setStyle('opacity',0);
	$('closeWall').setStyle('opacity',0);
	
}
/* /////////////////////////////////////////////////////////////////////
// Function to hide some part of the page when the mouse is inactive
/////////////////////////////////////////////////////////////////////*/
//Role : set some element hidden (light view) when the user is inactive
//
/*
function hideInactivity(){

	$('paintingNavigation').setStyle('opacity',1);
	clearTimeout(inactTimer);
	inactTimer = $('paintingNavigation').set('fade', {duration: 'long'}).fade.delay(5000, $('paintingNavigation'), ['out']);
	
}
*/
/* ///////////////////////////////////////////////////////////////////// 
//Function to return the painting link version like wordpress (thumb, small, medimum,520,760, big )
/////////////////////////////////////////////////////////////////////*/
function get_link_image(image, suffix){
	var name = image.substring(0,image.lastIndexOf("."));
	var ext = '.' + image.split('.').pop();
		
	return name + '-' + suffix + ext;
}
/* ///////////////////////////////////////////////////////////////////// 
//function to set the try painting app
/////////////////////////////////////////////////////////////////////*/
function paintingInit(){		
			
	//init data
	currentWall = userWall;	 //the current wall number
	//inactTimer='';  //an intervall for hideInactivity
	
	//when we click the close button 
	$('closeWall').addEvent('click',function(){
		//check if a wall is set as userwall		
			$('closeWall').setStyle('opacity',0);
				  		
	  		//send a request to delete the wall
	  		//var myRequest = new Request({method: 'post', url: $('uploadWall').get('action') });
			//myRequest.send('ajax=removeWall&wall='+userWall);
	  		Cookie.dispose('wall_img');
	  		Cookie.dispose('userWall');
	  		
	        userWall= 0; // delete the user wall
	        userCoor = '';
	        
	        loadPaintingView( arr_selection[currentPainting]  );
			  	
  	});
	
	$('fullScreen').erase('href');
	
	//hide current details and images	
	setCanvas(); 
		
	//create the resize property for all corners
	resizeRight 		= resize(	$('resizeR')	,false	);
	resizeLeft 			= resize(	$('resizeL')	,true	);
	resizeBottomRight 	= resize(	$('resizeBR')	,false	);
	resizeBottomLeft 	= resize(	$('resizeBL')	,true	);
	 
	//create the draggable property for the painting 
	draggablePainting = $('painting').makeDraggable({
							
							container: $('background'),
							handle:$('handler'),
							onStart: function(){
								//We add an event to listen if we leave the main window when draging (usefull with iframe)
								//If we leave we stop the resizing and put everything back to normal by calling makedraggable complete event
								$(document.body).addEvent('mouseleave', function(){				
									this.stop('mouseup'); //stop the resize and fire complete event with mouseup ( who then stop this listener )
									
								}.bind(this) );
							},
							onComplete: function(){	
								//remove the leave window listener
								$(document.body).removeEvents('mouseleave');	
								//save data as cookie for next time
								saveCoor();								
							}						
						}).detach();
}
