$(document).ready(function() {

/**
 * UPLOAD
 *
 * The upload process uploads the file in the #uploadForm and returns a XML
 * with the response. 
 * 
 * The XML structure is:
 *
 *	<xml>
 *	<root>
 *		<src/>
 *		<message/>
 *		<colours/>
 *	</root>
 *	</xml>
 *
 * - The src tag contains a string with the source path to the thumbnail generated if
 *   it was processed right. An empty string in other case.
 *
 * - Message shows the response error if there an error
 *
 * - Colours contains a string of hexadecimal colours separated by comma. The first colour
 *   is the background transparent colour if there is one.
 *
 **/
 

	//Upload form including file input
	$('#uploadform').ajaxForm({
			beforeSubmit:  showIndicator,
			dataType:  'xml', 
	    success: processXML     
	});		
	
	//Function to show indicator and block step1
	function showIndicator() {
		$('#main-section').append('<div id="upload-indcator"></div>');
		$('#step1').append('<div class="blocked"></div>');
	}
	
	//Function to remove indicator and unblock step1
	function hideIndicator() {
		$('#upload-indcator').remove();
		$('#step1 .blocked').remove();
	}
	
	//Function to process the XML
	function processXML(responseXML) {
		var src = $('src', responseXML).text(); 
		var message = $('message', responseXML).text(); 
		var colours = $('colours', responseXML).text(); 

    if (src==""){	    	
    	hideIndicator();
    	showWarning(message);    	
    }
    else {
    	if ($('#grid-painter').hasClass('modified'))
    		clearGrid('#step-preview-grid td, #preview-grid td,#grid-painter td');
    		
    	    	
    	if ($('#step-preview-icon img').size()>0){
    		$('#step-preview-icon img').attr('src',src);
    		$("#preview img").attr('src',src);
    	}
    	else {
    		$("#step-preview-icon").prepend('<img src="'+src+'" >');    	
    		$("#preview").prepend('<img src="'+src+'" >');
    		$('#grid-painter').addClass('modified');
    	}

    	eval('cols = new Array('+colours+')');  	
    	//Transparent color
    	transp = cols[0];
    	$("#transp").val(transp);
    	
    	
    	i = 1;
    	$("#grid td").each(function(){  
    		//If the color is not transparent then colorize cell
    		if (transp!=cols[i]){
	    		$(this).css('background-color',cols[i]);
	    		$(this).attr('abbr',cols[i]);
    		}
    		i++;
    	});    	
    	
    	hideIndicator();
    	unblock();
    }
	}	

	//Function to clear background colours from tables with old paintings
	function clearGrid(elements) {
  	$(elements).each(function(){    		
  		$('#'+this.id).css('background-color','transparent');
  	});
  }	
	
	
	
	
	
/**
 * DOWNLOAD
 *
 * The download process uploads a text input containing a list of colours
 * with the modified image that was loaded in the grid
 *
 **/ 	


	//Function to get hex format a rgb colour
	function rgb2hex(rgb) {		
		//generates the hex-digits for a colour.
		function hex(x) {
			hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
			return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
		}
		
		return "#" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
	}	
	
	
	//Process each of the cells of the grid table to get the colour of each cell and
	//stores the info in a text field
	function processGrid(){
		var colours = "";
		
  	$("#grid td").each(function(){  	
  		if ($(this).css('background-color')!='transparent'){
  			if ($(this).css('background-color').charAt(0)=='#')
  				colours += $(this).css('background-color') + ","; 			
  			else {  			
	  			col = $(this).css('background-color').split('rgb')[1].split(',');
		  		red = col[0].substring(1);
		  		green = col[1];
		  		blue = col[2].substring(0,col[2].length-1);
	  		
	  			colours += rgb2hex(new Array(red,green,blue)) + ",";
  			}
  		}
  		else {
  			colours += $("#transp").val() + ",";
  		}
  	});		
  	
  	colours = colours.substring(0,colours.length-1);
  	$("#arrgrid").val(colours);
  	
  	return true;  	
	}
	
		
		
	//Start download process
	function download(){
		processGrid();			
		$('#downloadform').submit();
	}
	
	
/**
 * GRID FUNCTIONS
 *
 **/

	var isMousedown = false;
	
	$("#grid td")
	.mousedown(function(){      	
		    	    	
		isMousedown = true;
		
		switch($("#grid-tools .active:eq(0)").attr("id")){
			//Fill with color
			case 'brush':
	    	setColor($(this),$("#p"+this.id));
	    break;
	
	    //Remove background color
	    case 'erase':
	    	eraseColor($(this),$("#p"+this.id));
	    break;
	
			//Restore original color      
	    case 'restore':      	     	 	
				restoreColor($(this),$("#p"+this.id));
	    break;
	    
			//Pick color
	    case 'pick':  	      	
				pickColor($(this));
	    break;        
		}
	})
	.mouseover(function(){
		
		//See if the mouse is clicked and the brush is active to paint the current px
	  if (isMousedown && $("#brush").hasClass("active")) 
	  	setColor($(this),$("#p"+this.id));
	  	
	  //If the mouse is clicked and the eraser too then remove background color
	  else if (isMousedown && $("#erase").hasClass("active"))
	   eraseColor($(this),$("#p"+this.id));
	     
		//If the mouse is clicked and the picker is active then select color
	  else if (isMousedown && $("#pick").hasClass("active"))
	   pickColor($(this));	   
	   
	  else if (isMousedown && $("#restore").hasClass("active"))
					restoreColor($(this),$("#p"+this.id)); 
	})
	.mouseup(function(){
		isMousedown = false;
	});
	
	
	
	//Colorize pixel
	function setColor(obj,prevobj){
	  obj.css({backgroundColor:$('#colour').val()});        
	  prevobj.css({backgroundColor:$('#colour').val()});
	}
	
	//Remove color from pixel
	function restoreColor(obj,prevobj){
		(obj.attr('abbr'))? obj.css({backgroundColor:obj.attr('abbr')}) : obj.css({backgroundColor:''});      
	  prevobj.css({backgroundColor:''});
	}            
	
	//Erase pixel
	function eraseColor(obj,prevobj){
		obj.css({backgroundColor:''});        	              
	  prevobj.css({backgroundColor:''});    	
	}   
	
	//Pick color
	function pickColor(obj){
		color = obj.css('background-color');
		
		if (color == 'transparent')
			return false;
		else if (color.charAt(0)=='#')
			color = color; 			
		else {
			col = color.split('rgb')[1].split(',');
			red = col[0].substring(1);
			green = col[1];
			blue = col[2].substring(0,col[2].length-1);
		
			color = rgb2hex(new Array(red,green,blue));
		}
	
		$.farbtastic('#gridpicker').setColor(color);
	}
	
	      
	       
		
	        
	
		
/**
 * Step functions
 *
 **/

	// Step1: upload image
	$('#upload-send').click(function(){
		$('#uploadform').submit();
	});
	
	
	// Step 1 and step 2: launch grid painter
	$('#new-draw, #step-modify').click(function(){		
		$('#grid-painter').modal({
			overlayId: 'bg-grid-painter',
			containerId: 'grid-painter-wrapper',
			closeClass: 'cancel-grid',
			onOpen: grid.open,
			onClose: grid.close,
			onShow: grid.show,
			close: false,
			persist: true
		});
		
		if (this.id=='new-draw'){
			$('#grid-painter td').css('background-color','transparent');		
			$('#transp').val('none');
		}
						
		return false;
	});
	

	
	// Grid painter methods
	var grid = {
		open: function (dialog) {	
			
			dialog.overlay.fadeIn(100,function(){
				dialog.data.fadeIn(100,function(){
					dialog.container.fadeIn(400);
				});					
			});	
			
			$('#grid-tools .active').removeClass('active');
			$('#grid-painter').addClass('modified');				
		},
		show: function (dialog) {
			
			$('#accept').click(function (e) {
				e.preventDefault();
							
				for (i=0; i<16; i++)
					for (j=0; j<16; j++){
						$('#spg'+i+'_'+j).css('background-color',$('#g'+i+'_'+j).css('background-color'));
					}
					
					$("#cancel").click();
					unblock();
			});		
							
		},
		close: function (dialog) {
			
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		}
	}	
	
	
	unblock = function(){
		if ($('div.blocked').size()>0)
			$('#step2,#step3').animate(
				{'opacity':'1'},
				500,
				'linear',
				function() {
					$('div.blocked').remove();
				}
			);					
	}
	
	
	
	// Step 3: download favicon
	$('#download').click(function(){
		download();
	});
	
	
	
	showWarning = function (message){
		$('#warning').prepend('<p>'+message+'</p>');
		$('#warning').modal({
			overlayId: 'bg-warning',
			containerId: 'warning-wrapper',
			closeClass: 'cancel-warning',
			onOpen: warning.open,
			onClose: warning.close,
			onShow: warning.show,
			close: false
		});
	}
	
	
	
	// Warning methods
	var warning = {
		open: function (dialog) {	
			
			dialog.overlay.fadeIn(100,function(){
				dialog.data.fadeIn(100,function(){
					dialog.container.fadeIn(400);
				});					
			});	
		},
		show: function (dialog) {
			
			$('#accept').click(function (e) {
				e.preventDefault();
														
				$.modal.close();
			});									
		},
		close: function (dialog) {
			
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		}
	}		
	
	
	
	


	
	
/**
 * Initialization 
 *
 **/

	//Activate brush, erase, restore and pick
  $('#brush,#restore,#erase,#pick').click(function(){
  	$("#grid-tools .active:not(#"+this.id+")").removeClass('active');
  	$(this).hasClass('active')? $(this).removeClass('active') : $(this).addClass('active');    	
  });

  
  
  //Farbtastic color picker
  var picker = $.farbtastic('#gridpicker',function(){
  	$('#colour').val(picker.color);
  	$('#previewpicker').css('background-color',picker.color);
  });
  
  picker.setColor('#000000');  
	
  
  
  
  $('#uploadfile-wrapper,#upload-send,#new-draw,#download').hover(function(){
  	$(this).addClass('active');
  },function(){
  	$(this).removeClass('active');
  });
  
  
  
  // preload images
	var img = ['picker/marker.png','picker/mask.png','picker/wheel.png','style/prompt.gif','style/grid-tools.gif','style/grid-transparency.gif'];
	$(img).each(function () {
	 var i = new Image();
	 i.src = 'imgs/' + this;
	});
  
	$('#step2,#step3').animate({opacity: 0.5},800);
  
}); 	