var old_x = 0; 
var old_y = 0;

var old_x_div = 0;
var old_y_div = 0;

var save = false;
var div_pos = 1;
var tmp_pos = -1;
var id = '';
function saveCur(t,e) // keeping the initial coordinates
{	
	if(e.button == 0 || e.button == 1)	// if was pressed the left mouse button	
	{	
		save = true;
		clearSelection(); // function cancels selection
		old_x = getCur(e).x; //	keeps the cursor coordinates
		old_y = getCur(e).y;
		id = $(t).parents().attr('id'); // save id of current box
		old_x_div = parseInt($('#' + id).css('left')); // keeps the top left corner
		old_y_div = parseInt($('#' + id).css('top'));	
		
		$('#' + id).fadeTo(300, 0.5).css('zIndex',1000); // change transparency
		
		if($.browser.msie) // fix a bug in IE with z-index
		{
			$('.rect').css('zIndex',0);
			$('#' + id).parents().css('zIndex',1000);
		}
	}
}
function moveBox(t,e) // moving block
{
	if(save == true) // was to press the left button
	{
		clearSelection(); // function cancels selection
		var x = getCur(e).x;
		var y = getCur(e).y; // coordinates of the cursor
		
		if(x % 8 == 0 || y % 8 == 0) // reduces the load on the processor       ZMENA
		{
			var left = x - (old_x - old_x_div); // sets a new position of box
			var top = y - (old_y - old_y_div);
			
			$('#' + id).css('left',left).css('top',top);
						
			var arr_obj = new Array();
			var marg = parseInt($('.box').css('marginBottom')); // gets margin-bottom in class box
			
			arr_obj[0] = 0;
			
			$('#' + getRecOn(e) + ' .box').each(function() // calculating coordinates of vertices of all boxes
			{
				arr_obj[arr_obj.length] = arr_obj[arr_obj.length - 1] + $(this).height() + marg;
			});	
									
			var new_top;
			var cur_divs = new Array();
			cur_divs[0] = 0;
			
			$('#' + $('#' + id).parents().attr('id') + ' .box').each(function() // calculating coordinates of vertices of all boxes wich containe div
			{
				if($(this).attr('id') == id)
				new_top = cur_divs[cur_divs.length-1];
				cur_divs[cur_divs.length] = cur_divs[cur_divs.length - 1] + $(this).height() + marg;
			});	
			new_top = new_top + top ;		
						
			if(new_top < 0) // test the limits of coordinates box and count the position in which it is inserted
			{
				div_pos = 1;
			}
			else if(new_top >= arr_obj[arr_obj.length-1])
			{
				div_pos = arr_obj.length ;
			}
			else
			{
				for(var i = 0;i < arr_obj.length;i++)
				{
					if(new_top >= arr_obj[i] - 25 && new_top <= arr_obj[i] + 25)
					{
						div_pos = i + 1;
					}		
				}
			}
			
			if($('#' + id).parents().attr('id') != getRecOn(e)) // 	puts temporary box
			{
				$('#tmp_div').remove(); // inserts a temporary box is moving within this div
				setPos('tmp_div', '<div style="height:' + $('#' + id).height() + 'px;z-index:0"><br/></div>', getRecOn(e), div_pos);
				tmp_pos = div_pos;
			}
			else 
			{ // set position box in his native div
				$('#tmp_div').remove();
				var i = 0;
				var cur_pos = 0;
				$('#' + $('#' + id).parents().attr('id') + ' .box').each(function()
				{
					if($(this).attr('id') == id)
						cur_pos = i + 1;
					i++;
				});	
				
				if(cur_pos != div_pos) // adjust the position of Box				
				{
					//$('#tmp_div').remove();
					if(div_pos > i)
						div_pos = i;
					cur_pos = div_pos;					
				}
			}
		}
	}
}
function done(t,e) // completes move
{
	if(save == true && ((getCur(e).x - old_x != 0 && old_x != 0) || (getCur(e).y - old_y != 0 && old_y != 0)))
	{
		var div_cont = $('#' + id).html();
		var div_rec_on = getRecOn(e);
		$('#' + id).remove(); // remove box
		setPos(id, div_cont, div_rec_on , div_pos);	// insert in new position	
		$('#tmp_div').remove();	//remove tmp box
		boxInfo();
	}
	
	save = false;
	if(id != '')
		$('#' + id).fadeTo(300,1).css('zIndex',1); // restore transparency
	old_x = 0;
	div_pos = 1;
	tmp_pos = -1;
	id = '';	
}
function setPos(id, div, container, pos) // set in position curent box
{
	var tmp_obj = div;
	var arr_obj = new Array();
	var arr_id = new Array();
	
	$('#' + container + ' .box').each(function() // select all boxes and their id from our div
	{
		arr_obj[arr_obj.length] = $(this).html();
		arr_id[arr_id.length] = $(this).attr('id');
	});
	var tmp_cont = '';
	
	for(var i = 0; i < arr_obj.length; i++) // loop insert current box in div
	{
		if(i + 1 == pos)
		{	
			if(id != 'tmp_div')
				tmp_cont = tmp_cont + '<div id="' + id + '" class="blok_obal box">' + tmp_obj + '</div>';
			else
				tmp_cont = tmp_cont + '<div id="' + id + '">' + tmp_obj + '</div>';
		}	
		tmp_cont = tmp_cont + '<div id="' + arr_id[i] + '" class="blok_obal box">' + arr_obj[i] + '</div>';
	}
	if(pos == arr_obj.length + 1)
	{
		if(id != 'tmp_div')
			tmp_cont = tmp_cont + '<div id="' + id + '" class="blok_obal box">' + tmp_obj + '</div>';
		else
			tmp_cont = tmp_cont + '<div id="' + id + '">' + tmp_obj + '</div>';
	}
	$('#' + container).html(tmp_cont + '<div><br/></div>'); // 	insert new content into our div
}
function getCur(e) // gets the cursor coordinates
{
  var x = 0, y = 0;   
  
  if (!e) e = window.event;   
	  if (e.pageX || e.pageY)   
	  {   
		x = e.pageX;   //coordinates in other browsers
		y = e.pageY;   
	  }   
	  else if (e.clientX || e.clientY) //coordinates in IE  
	  {   
		x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;   
		y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;   
	  }
	
	x = x - parseInt($('.rect').css('left'));
	y = y - parseInt($('.rect').css('top'));

	return {'x':x, 'y':y};  //return object with coordinates
}


function getRecOn(e) // gets id that div on a moving current box   
{
	var x = getCur(e).x;
	var rect_width = $('.rect').width();           
	var return_Rec = $('#' + id).parents().attr('id');
	
	var firstLeft = (pageWidth()-parseInt($('.main').css('width')))/2;
  var rectWidth = parseInt($('.main').css('width'))/3; 
  if(x < (firstLeft + rectWidth)){
    return_Rec = 'first';
  }else if( (firstLeft + rectWidth) < x && x < (firstLeft + 2 * rectWidth)){
    return_Rec = 'second';
  }else if( (firstLeft + 2 * rectWidth) < x ){
    return_Rec = 'third';
  }
	return return_Rec; // return id div
}

function clearSelection()
{
	var sel;
	if(document.selection && document.selection.empty)
	{
		document.selection.empty(); // remove all selections
	}
	else if(window.getSelection)
	{
		sel = window.getSelection();
		if(sel && sel.removeAllRanges)
			sel.removeAllRanges(); // cancels selection
	}
}
function boxInfo()                   //ZMENA
{  
	// box position to database
  
  i = 1;
  j = 1;
  querySTR ="";
	  var infoDiv = document.getElementById('infoDiv');
  $('#first .box').each(function() // record ID boxes
	{ 		
		querySTR += "&pos"+j+'=';
    querySTR +="1d"+i+"d"+$(this).attr('id');
		i++;
		j++
	});	
	
	i = 1;
	$('#second .box').each(function() // record ID boxes
	{ 
    querySTR += "&pos"+j+"=";
    querySTR +="2d"+i+"d"+$(this).attr('id');
		i++;
		j++
	});	
	
	i = 1;
	$('#third .box').each(function() // record ID boxes
	{
     querySTR += "&pos"+j+"=";
     querySTR +="3d"+i+"d"+$(this).attr('id');
     i++;
     j++
  });
   if(querySTR != ""){
    if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
          httpRequest = new XMLHttpRequest();
        }
        var url = "/redakce/ajax.php?akce=zapis_bloku"+querySTR;
        httpRequest.open("GET", url, true);
        httpRequest.send(null);
  }  
    
}

function pageWidth() {
return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;
}