var elements_list = new Array(// Element name, thumb, size 1, size 2, size 3, ...
                            new Array("E-300","E300_thumb.jpg","E300.jpg",216,481),
							new Array("E-400","E400_thumb.jpg","E400.jpg",216,503),
							new Array("E-450","E450_thumb.jpg","E450.jpg",216,128),
							new Array("E-500","E500_thumb.jpg","E500.jpg",216,192),
							new Array("E-510","E510_thumb.jpg","E510.jpg",216,192),
							new Array("E-520","E520_thumb.jpg","E520.png",216,255),
							new Array("E-600","E600_thumb.jpg","E600.jpg",216,352),
							new Array("E-840","E840_thumb.jpg","E840.jpg",216,160),
							new Array("E-850","E850_thumb.jpg","E850.jpg",432,160),
							new Array("E-870","E870_thumb.jpg","E870.jpg",648,160) //192
							//new Array("E-250","element_small.jpg","element_small.jpg","element_small.jpg","element_small.jpg"),
							//new Array("E-450","element_small.jpg","element_small.jpg","element_small.jpg","element_small.jpg")
						);																								
					
var scale = 3;
var color = 1;
var gridSize = new Array(0, 6, 4, 3, 2, 1.50);
var nbElements = 0;
var currentId = 0;
var MAX_ELEMENTS = 25;
var savedElements = new Array(25);
var baseLine = 272;
var base = baseLine+21;
var topAdjustment = 46;

$(document).ready(function() {
     
     $("#select_scale").change(function(){
          setScale(this.value);
     });

	//draw_grid("#grid");
	create_thumbnails();
	create_colors("#sidebar");

	$('#grid').addClass('droppable-active')
		.droppable({
			accept: '.draggable',
			tolerance: 'fit',
			drop: function(ev, ui) {

				if( nbElements >= MAX_ELEMENTS ) {
					alert('Maximum number of elements reached');
					return;
				}

                var id = ui.draggable.attr('id').substring(6);//ui.draggable.element.id.substring(6);
				//alert(id);
				var l = parseInt($("#dragged-"+id).css("left"));
				if( id == "porte" ) l += 591;
				else if( id == "fenetre" ) l += 591;
				else l += 160;				

                var topV = parseInt($("#dragged-"+id).css("top"));
				// Base top value on the grid
				if( id == "porte" ) topV = 500 + topV - topAdjustment;
				else if( id == "fenetre" ) topV = 500 + topV - topAdjustment;
				else topV = 396 + topV - topAdjustment;

				l = l + "px";

				if( id == "porte" ){

                         // Create element to be added to the grid
     				var img = root+"app_displayPictureCropped.php?filename=images/elements/porte.jpg";
     				var newW = parseInt((216/6)*gridSize[scale]);
     				var newH = parseInt((504/6)*gridSize[scale]);
     				img = img + "&width="+newW+"&height="+newH;

     				var node = $.create("img", {"id":"node-"+currentId,"src":img,"class":"porte"});
     				$('#grid').append(node);
     				$("#node-"+currentId).css("position","absolute");
     				$("#node-"+currentId).css("left",l);
     				$("#node-"+currentId).css("z-index",350+currentId);
     				$("#node-"+currentId).draggable({
     					//grid: [gridSize[scale],gridSize[scale]],
     					containment: 'parent'
     				});
     				
     				// Place element on the base line
     				var h = $("#node-"+currentId).css("height");
     				h = baseLine - parseInt(h.substring(0, h.length-2));
                         h = h + "px";
                         $("#node-"+currentId).css("top",h);

                    } else if( id == "fenetre" ){
                         // Create element to be added to the grid
     				var img = root+"app_displayPictureCropped.php?filename=images/elements/fenetre.jpg";
     				var newW = parseInt((216/6)*gridSize[scale]);
     				var newH = parseInt((288/6)*gridSize[scale]);
     				img = img + "&width="+newW+"&height="+newH;

     				var node = $.create("img", {"id":"node-"+currentId,"src":img,"class":"fenetre"});
     				$('#grid').append(node);
     				$("#node-"+currentId).css("position","absolute");
     				$("#node-"+currentId).css("left",l);
     				$("#node-"+currentId).css("z-index",350+currentId);
     				$("#node-"+currentId).draggable({
     					//grid: [gridSize[scale],gridSize[scale]],
     					containment: 'parent'
     				});

                         // Place element on the base line
     				if( topV+newH > baseLine ) topV = baseLine-newH-50;
     				var h = topV+"px";
     				$("#node-"+currentId).css("top",h);


                    } else { // Regular element

     				// Create element to be added to the grid
     				if( id >= 7 )
                              var img = root+"app_displayPictureCropped.php?filename=images/elements/color"+color+"/"+elements_list[id][2];
          			else var img = root+"app_displayPictureCroppedPng.php?filename=images/elements/color"+color+"/"+elements_list[id][2];
                         var newW = parseInt((elements_list[id][3]/6)*gridSize[scale]);
     				var newH = parseInt((elements_list[id][4]/6)*gridSize[scale]);
     				img = img + "&width="+newW+"&height="+newH;
     				
     				var node = $.create("img", {"id":"node-"+currentId,"src":img,"class":"node"});
     				$('#grid').append(node);
     				$("#node-"+currentId).css("position","absolute");
     				$("#node-"+currentId).css("left",l);
     				$("#node-"+currentId).css("z-index",1000+currentId);
     				if( id >= 7 ){
                              $("#node-"+currentId).css("z-index",500+currentId);
                         }
     				$("#node-"+currentId).draggable({
     					//grid: [gridSize[scale],gridSize[scale]],
     					containment: 'parent'
     				});

     				// Place element on the base line
     				var h = $("#node-"+currentId).css("height");
     				var hV = parseInt(h.substring(0, h.length-2))
                         h = base - hV;

                         //alert("TOP: "+topV);

                         if( id >= 7 ){ //id == 2 || //id == 3 || id == 4 ||
                              calculateSnapValues();
                              var closestValue = 9999;
                              for(snap in snapValues){
                                   var bottom = topV+hV;
                                   var check = Math.abs(bottom - snapValues[snap]);
                                   if( check < closestValue ){
                                        h = snapValues[snap]-hV;
                                        closestValue = check;
                                   }
                              }
                         } 
                         if( id >= 7 && h == (base - hV) ) {
                              h -= (192/6) * gridSize[scale];
                         }
                         if( id == 2 ) {
                              h = Math.floor((base - (((192+160)/6) * gridSize[scale]))) - hV;
                              //alert(h);
                         }

                         
                         //alert(snapValues[2] + " vs " + topV);
                         //h = snapValues[2]-hV;

                         h = h + "px";
                         $("#node-"+currentId).css("top",h);


     			}

				savedElements[nbElements] = new Array(currentId,id,l,h,color);
				nbElements++;
				currentId++;

				return;
			}
		});
		
    $('#grid').addClass('droppable-active')
        .droppable({
            accept: '.node',
            tolerance: 'touch',
            drop: function(ev, ui) {
				// Update position
				var id = ui.draggable.attr('id').substring(5);
				//if( $("#node-"+id) == null ) return;
				var l = $("#node-"+id).css("left");
				//if( typeof l == 'undefined' ) return;
				var lV = parseInt(l.substring(0, l.length-2));
				var t = $("#node-"+id).css("top");
				var tV = parseInt(t.substring(0, t.length-2));

				var h = $("#node-"+id).css("height");
     			var hV = parseInt(h.substring(0, h.length-2));

     			var el = document.getElementById("node-"+id);//$("#"+ui.draggable.attr('id'));
     			//alert(el.id);
     			
     			//alert(ui.draggable.attr('id'));        			

     			if( tV < 50 && lV < 50 ) {
                         for( var i=0; i<nbElements; i++){
                    		if( savedElements[i][0] == id ){
                                   savedElements[i] = new Array(-1, 0, 0, 0, 0);
                                   for( var j=0; j< nbElements; j++ ){
                    				if( j > i ){
                                             savedElements[j-1] = savedElements[j];
                                             savedElements[j] = new Array(-1, 0, 0, 0, 0);
                    				}
                    			}
                    			nbElements--;
                    			break;
               	    	    }
                    	}
                    	el.parentNode.removeChild(el);
                    	return;
                    }
                    
                    //alert(tV+" "+hV);

   				for(i in savedElements){
					if( savedElements[i][0] == id ){

                              
                              // Place element on the base line
          				h = base - hV;
                              elType = savedElements[i][1];

                              if( elType == 7 ){ //elType == 2 || elType == 3 || elType == 4 ||
                                   calculateSnapValues();
                                   var closestValue = 9999;
                                   var bottom = tV+hV;
                                   for(snap in snapValues){
                                        var check = Math.abs(bottom - snapValues[snap]);
                                        if( check < closestValue ){
                                             h = snapValues[snap]-hV;
                                             closestValue = check;
                                        }
                                   }
                              }
                              if( elType >= 7 && h == (base - hV) ) {
                                   h -= (192/6) * gridSize[scale];
                              }
                              if( elType == 2 ) {
                                   h = Math.floor((base - (((192+160)/6) * gridSize[scale]))) - hV;
                                   //alert(h);
                              }
                              h = h + "px";
                              $("#node-"+id).css("top",h);

						savedElements[i][2] = l;
						savedElements[i][3] = h;
						break;
					}
				}
			}
		});
		$('#grid').addClass('droppable-active')
		.droppable({
			accept: '.porte',
			tolerance: 'fit',
			drop: function(ev, ui) {
				// Update position
				var id = ui.draggable.attr('id').substring(5);
				var l = $("#node-"+id).css("left");
				var lV = parseInt(l.substring(0, l.length-2));
				var h = $("#node-"+id).css("height");
     			var hV = parseInt(h.substring(0, h.length-2));
     			var t = $("#node-"+id).css("top");
				var tV = parseInt(t.substring(0, t.length-2));

                //var el = $(ui.draggable);
                var el = document.getElementById("node-"+id);

     			if( tV < 50 && lV < 50 ) {
                         for( var i=0; i<nbElements; i++){
                    		if( savedElements[i][0] == id ){
                                   savedElements[i] = new Array(-1, 0, 0, 0, 0);
                                   for( var j=0; j< nbElements; j++ ){
                    				if( j > i ){
                                             savedElements[j-1] = savedElements[j];
                                             savedElements[j] = new Array(-1, 0, 0, 0, 0);
                    				}
                    			}
                    			nbElements--;
                    			break;
               	    	    }
                    	}
                    	el.parentNode.removeChild(el);
                    	return;
                    }

   				h = baseLine - hV;
                    h = h + "px";
                    $("#node-"+id).css("top",h);
				for(i in savedElements){
					if( savedElements[i][0] == id ){
						savedElements[i][2] = l;
						savedElements[i][3] = h;
					}
				}
			}
		});
		$('#grid').addClass('droppable-active')
		.droppable({
			accept: '.fenetre',
			tolerance: 'fit',
			drop: function(ev, ui) {
				// Update position
				var id = ui.draggable.attr('id').substring(5);
				var l = $("#node-"+id).css("left");
				var lV = parseInt(l.substring(0, l.length-2));
				var t = $("#node-"+id).css("top");
				var tV = parseInt(t.substring(0, t.length-2));
				var h = $("#node-"+id).css("height");
     			var hV = parseInt(h.substring(0, h.length-2));

                //var el = $(ui.draggable);
                var el = document.getElementById("node-"+id);

     			if( tV < 50 && lV < 50 ) {
                         for( var i=0; i<nbElements; i++){
                    		if( savedElements[i][0] == id ){
                                   savedElements[i] = new Array(-1, 0, 0, 0, 0);
                                   for( var j=0; j< nbElements; j++ ){
                    				if( j > i ){
                                             savedElements[j-1] = savedElements[j];
                                             savedElements[j] = new Array(-1, 0, 0, 0, 0);
                    				}
                    			}
                    			nbElements--;
                    			break;
               	    	    }
                    	}
                    	el.parentNode.removeChild(el);
                    	return;
                    }

   				if( tV+hV > 271 ) tV = 271-hV-70;

                    h = tV + "px";

                    $("#node-"+id).css("top",h);
				for(i in savedElements){
					if( savedElements[i][0] == id ){
						savedElements[i][2] = l;
						savedElements[i][3] = h;
					}
				}
			}
		});

	// Create garbage bin
	var node = $.create("img",{"id":"bin", "src":root+"images/bin.jpg","alt":""});
	$("#grid").append(node);
	$("#bin").css("position","absolute");
	$("#bin").css("left","11px");
	$("#bin").css("top","5px");
	$("#bin").css("z-index","5");
	
	$('#bin')
		.droppable({
			accept: '.node,.fenetre,.porte',
			tolerance: 'touch',
			hoverClass: 'hover',
			drop: function(ev, ui) {
				// Remove element
				//var el = $(ui.draggable);
				//alert(ui.draggable.attr('id'));
				var id = ui.draggable.attr('id').substring(5);
				var el = document.getElementById(ui.draggable.attr('id'));	
				//alert("Removing: "+"node-"+id);
				//alert(el.id);			
				//deleteNode(ui.draggable.element);
				
                    for( var i=0; i<nbElements; i++){
               		if( savedElements[i][0] == id ){
                              savedElements[i] = new Array(-1, 0, 0, 0, 0);
                              for( var j=0; j< nbElements; j++ ){
               				if( j > i ){
               					savedElements[j-1] = savedElements[j];
               					savedElements[j] = new Array(-1, 0, 0, 0, 0);
               				}
               			}
               			nbElements--;
               			break;
               		}
               	}
               	$(ui.draggable).remove();
               	//el.parentNode.removeChild(el);
			}
		});
	import_elements();
     //correctPNG();
     
     // Grid onsubmit
     $("#save_grid").submit(function(){
          this.action = "?data="+escape(export_text());
     });
});

function draw_grid(id){
	var w = $(id).width();
	var h = $(id).height();
	
	// Draw vertical lines
	for( var i=9; i<w-10; i+=gridSize[scale] ){
		var node = $.create("div", {"id": "vline-"+i, "class": "vertical_line"}, [""]);
		$(id).append(node);
		$("#vline-"+i).css("position","absolute");
		$("#vline-"+i).css("left",i+"px");
		$("#vline-"+i).css("height",h+"px");
		$("#vline-"+i).css("z-index","0");
	}
	// Draw horizontal lines
	for( var i=2; i<h; i+=gridSize[scale] ){
		var node = $.create("div", {"id": "hline-"+i, "class": "horizontal_line"}, [""]);
		$(id).append(node);
		$("#hline-"+i).css("position","absolute");
		$("#hline-"+i).css("top",i+"px");
		$("#hline-"+i).css("width",w+"px");
		$("#hline-"+i).css("z-index","0");
	}	
}
function create_thumbnails(){
	for(element in elements_list){
        var node = $.create("img",{"id":"thumb-"+element,"class":"draggable", "src":root+"images/elements/color"+color+"/"+elements_list[element][1],"alt":elements_list[element][0]});
		$("#elements").append(node);
		$("#thumb-"+element).draggable({
			helper: function() {
				var id = parseInt(this.id.substring(6));
				if( id >= 7 )
     				var img = root+"app_displayPictureCropped.php?filename=images/elements/color"+color+"/"+elements_list[id][2];
     			else var img = root+"app_displayPictureCroppedPng.php?filename=images/elements/color"+color+"/"+elements_list[id][2];
				//alert(img);
				var newW = parseInt((elements_list[id][3]/6)*gridSize[scale]);
				var newH = parseInt((elements_list[id][4]/6)*gridSize[scale]);
				img = img + "&width="+newW+"&height="+newH;
				//alert(img);

                    //$("#url").html(encode(img));
                    return $.create("img", {"id":"dragged-"+id,"src":img});
                    //$(document.createElement('img')).src(img).appendTo("body")[0];
                    //
			}//,
			//grid: [gridSize[scale],gridSize[scale]]
		});
          $("#thumb-"+element).css("width","50px");
	}
	
	// porte
	var node = $.create("img",{"id":"thumb-porte","class":"draggable", "src":root+"images/elements/porte_thumb_"+lang+".jpg","alt":"Porte"});
	$("#elements_special").append(node);
	$("#thumb-porte").draggable({
		helper: function() {
			var img = root+"app_displayPictureCropped.php?filename=images/elements/porte.jpg";
			var newW = parseInt((216/6)*gridSize[scale]);
			var newH = parseInt((504/6)*gridSize[scale]);
			img = img + "&width="+newW+"&height="+newH;
          return $.create("img", {"id":"dragged-porte","src":img});//$(document.createElement('img')).src(img).appendTo("body")[0];
		}//,
		//grid: [gridSize[scale],gridSize[scale]]
	});
	// fenetre
	var node = $.create("img",{"id":"thumb-fenetre","class":"draggable", "src":root+"images/elements/fenetre_thumb_"+lang+".jpg","alt":"Fenêtre"});
	$("#elements_special").append(node);
	$("#thumb-fenetre").draggable({
		helper: function() {
			var img = root+"app_displayPictureCropped.php?filename=images/elements/fenetre.jpg";
			var newW = parseInt((216/6)*gridSize[scale]);
			var newH = parseInt((288/6)*gridSize[scale]);
			img = img + "&width="+newW+"&height="+newH;
          return $.create("img", {"id":"dragged-fenetre","src":img});//$(document.createElement('img')).src(img).appendTo("body")[0];
		}//,
		//grid: [gridSize[scale],gridSize[scale]]
	});

}
function create_colors(id){
     for(var i=1;i<=6;i++){
          var node = $.create("img",{"id":"color"+i,"src":root+"images/couleur"+i+".jpg","alt":"color"+i});
		$(id).append(node);
		$("#color"+i).click(function(){
			changeColor(parseInt(this.id.substring(this.id.length-1)));
		});
	}
	$("#color1").addClass("selected");
}

function export_text(){
	var ex = lang+";"+scale+";";
	for(var i=0; i < nbElements; i++){
		var el = savedElements[i];
		var z = $("#node-"+el[0]).css("z-index");
		if( el[0] != -1 ) ex = ex + el[1] + "," + el[2] + "," + el[3] + "," + el[4] + "," + z + ";";
		//var node = $("node-"+i)
	}
	return ex;
}

function clearGrid(){
	for(i in savedElements){
		if( i > nbElements ) break;
		
		//alert("#node-"+savedElements[i][0]);
		
		var el = $("#node-"+savedElements[i][0])[0];
		if( el ) {
			el.parentNode.removeChild(el);
		}
	}

	savedElements = new Array(MAX_ELEMENTS);
	nbElements = 0;
}

function import_elements(){	
	for( i in savedElements ){	
	
		if( i > nbElements ) break;		
		
		var id = savedElements[i][1];
		var l = savedElements[i][2];
		var t = savedElements[i][3]
		var c = savedElements[i][4];
		var zIndex = savedElements[i][5];

		if( id == "porte" ){
               
               // Create element to be added to the grid
			var img = root+"app_displayPictureCropped.php?filename=images/elements/porte.jpg";
			var newW = parseInt((216/6)*gridSize[scale]);
			var newH = parseInt((504/6)*gridSize[scale]);
			img = img + "&width="+newW+"&height="+newH;

			var node = $.create("img", {"id":"node-"+savedElements[i][0],"src":img,"class":"porte"});


          } else if( id == "fenetre" ){

               // Create element to be added to the grid
			var img = root+"app_displayPictureCropped.php?filename=images/elements/fenetre.jpg";
			var newW = parseInt((216/6)*gridSize[scale]);
     		var newH = parseInt((288/6)*gridSize[scale]);
               img = img + "&width="+newW+"&height="+newH;

			var node = $.create("img", {"id":"node-"+savedElements[i][0],"src":img,"class":"fenetre"});
          } else {
               if( id >= 7 )
                    var img = root+"app_displayPictureCropped.php?filename=images/elements/color"+c+"/"+elements_list[id][2];
               else var img = root+"app_displayPictureCroppedPng.php?filename=images/elements/color"+c+"/"+elements_list[id][2];
               var newW = parseInt((elements_list[id][3]/6)*gridSize[scale]);
               var newH = parseInt((elements_list[id][4]/6)*gridSize[scale]);
               img = img + "&width="+newW+"&height="+newH;

     		var node = $.create("img", {"id":"node-"+savedElements[i][0],"src":img,"class":"node"});
          }
          $('#grid').append(node);
		$("#node-"+savedElements[i][0]).css("position","absolute");
		$("#node-"+savedElements[i][0]).css("left",l);
		$("#node-"+savedElements[i][0]).css("top",t);
		$("#node-"+savedElements[i][0]).css("z-index",zIndex);
		$("#node-"+savedElements[i][0]).draggable({
			containment: 'parent'
		});

	}
	// Take the 
}

function displayUrl(t){
	$("#url").html("Lien: <a href=\"grid_drag.php?data="+escape(t)+"\">grid_drag.php?data="+escape(t)+"</a>");
}

function setScale(s){
	//window.location = "?scale="+s;
	//return;

	clearGrid();
	
	while( $("#grid > *").length > 1 ){	
		for( var i=0; i < $("#grid > *").length; i++ ){
			var el = $("#grid > *")[i];	
			if( el.id != "bin" ) el.parentNode.removeChild(el);
		}
	
	}
	
	//alert($("#grid > *").length);
	
	scale = parseInt(s);
	//alert(scale);
   	//draw_grid("#grid");   	
}

function changeColor(c){
     for(var i=1;i<=6;i++){
          $("#color"+i).removeClass("selected");
     }
     $("#color"+c).addClass("selected");
     color = c;
     for(element in elements_list){
          //var el = $("#thumb-"+element);
          document.getElementById("thumb-"+element).src =root+"images/elements/color"+color+"/"+elements_list[element][1];
	}
	
	for( i in savedElements ){
	
		if( i > nbElements ) break;		
		
		var id = "node-"+savedElements[i][0];
		document.getElementById(id).src = document.getElementById(id).src.replace("color"+savedElements[i][4], "color"+c);
		savedElements[i][4] = c;
	}
}
var snapValues;
var snapValues2;
function calculateSnapValues(){
     snapValues = new Array(  base,
                              Math.floor((base - ((192/6) * gridSize[scale])))//,
                              //Math.floor((base - (((192+160)/6) * gridSize[scale])))
                              //Math.floor((base - ((126/6) * gridSize[scale]))),
                              //Math.floor((base - ((126/6) * 2 * gridSize[scale])))
                            );
}

function deleteNode(id){
     //var id = el.id.substring(5);
     //alert("REMOVING: "+id);

	var l = $("#node-"+id).css("left");
	var t = $("#node-"+id).css("top");

	for( var i=0; i<nbElements; i++){
		if( savedElements[i][0] == id ){
               savedElements[i] = new Array(-1, 0, 0, 0, 0);
               for( var j=0; j< nbElements; j++ ){
				if( j > i ){
					savedElements[j-1] = savedElements[j];
					savedElements[j] = new Array(-1, 0, 0, 0, 0);
				}
			}
			nbElements--;
			break;
		}
	}
	var el = document.getElementById("node-"+id);
	el.parentNode.removeChild(el);
}