/************************************************************************************************************
	(C) www.dhtmlgoodies.com, January 2006
	
	This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	
	
	Terms of use:
	You are free to use this script as long as the copyright message is kept intact. However, you may not
	redistribute, sell or repost it without our permission.
	
	Thank you!
	
	www.dhtmlgoodies.com
	Alf Magne Kalleland
	
	************************************************************************************************************/	

	var modul_info_text = '';
  var modul_info_name = '';
  var modul_info_float = '';
  var modul_info_colls = '';
  var modul_info_items = '';
  
  var myAjax = new Request(
			{
				url: "ajax_com.php?action=language&id=index",
				method:'post',
        onFailure: function(e){showError(this.xhr)},
        onComplete: function(e){
          	modul_info_text = this.xhr.responseXML.documentElement.getElementsByTagName('start_info')[0].firstChild.data;
            modul_info_name = this.xhr.responseXML.documentElement.getElementsByTagName('start_name')[0].firstChild.data;
            modul_info_float = this.xhr.responseXML.documentElement.getElementsByTagName('start_float')[0].firstChild.data;
            modul_info_colls = this.xhr.responseXML.documentElement.getElementsByTagName('start_colls')[0].firstChild.data;
            modul_info_items = this.xhr.responseXML.documentElement.getElementsByTagName('start_items')[0].firstChild.data;
            modul_info_text2 = this.xhr.responseXML.documentElement.getElementsByTagName('start_info2')[0].firstChild.data;
        }
      }
	).send();
	
	


	var rectangleBorderWidth = 2;	// Used to set correct size of the rectangle with red dashed border
	var useRectangle = true;	
	var autoScrollSpeed = 4;	// Autoscroll speed	- Higher = faster

	/* Don't change anything below here */
	
	
	var dragableElementsParentBox;
	var opera = navigator.appVersion.indexOf('Opera')>=0?true:false;
		
	var rectangleDiv = false;
	var insertionMarkerDiv = false;
	var mouse_x;
	var mouse_y;
	
	var el_x;
	var el_y;
		
	var dragDropTimer = -1;	// -1 = no drag, 0-9 = initialization in progress, 10 = dragging
	var dragObject = false;
	var dragObjectNextObj = false;
	var dragableObjectArray = new Array();
	var destinationObj = false;	
	var currentDest = false;
	var allowRectangleMove = true;
	var insertionMarkerLine;
	var dragDropMoveLayer;
	var autoScrollActive = false;
	var documentHeight = false;
	var documentScrollHeight = false;
	var dragableAreaWidth = false;
	
	function getTopPos(inputObj)
	{		
	  var returnValue = inputObj.offsetTop;
	  while((inputObj = inputObj.offsetParent) != null){
	  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
	  }
	  return returnValue;
	}
	
	function getLeftPos(inputObj)
	{
	  var returnValue = inputObj.offsetLeft;
	  while((inputObj = inputObj.offsetParent) != null){
	  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
	  }
	  return returnValue;
	}
		
	function cancelSelectionEvent()
	{
		if(dragDropTimer>=0)return false;
		return true;
	}
	
	function getObjectFromPosition(x,y)
	{
		var height = dragObject.offsetHeight;
		var width = dragObject.offsetWidth;
		var indexCurrentDragObject=-5;
		for(var no=0;no<dragableObjectArray.length;no++){			
			ref = dragableObjectArray[no];			
			if(ref['obj']==dragObject)indexCurrentDragObject=no;
			if(no<dragableObjectArray.length-1 && dragableObjectArray[no+1]['obj']==dragObject)indexCurrentDragObject=no+1;
			if(ref['obj']==dragObject && useRectangle)continue;	
			if(x > ref['left'] && y>ref['top'] && x<(ref['left'] + (ref['width']/2)) && y<(ref['top'] + ref['height'])){
				if(!useRectangle && dragableObjectArray[no]['obj']==dragObject)return 'self';
				if(indexCurrentDragObject==(no-1))return 'self';
				return Array(dragableObjectArray[no],no);
			}
			
			if(x > (ref['left'] + (ref['width']/2)) && y>ref['top'] && x<(ref['left'] + ref['width']) && y<(ref['top'] + ref['height'])){
				if(no<dragableObjectArray.length-1){
					if(no==indexCurrentDragObject || (no==indexCurrentDragObject-1)){
						return 'self';
					}
					if(dragableObjectArray[no]['obj']!=dragObject){
						return Array(dragableObjectArray[no+1],no+1);
					}else{
						if(!useRectangle)return 'self';
						if(no<dragableObjectArray.length-2)return Array(dragableObjectArray[no+2],no+2);
					}
				}else{
					if(dragableObjectArray[dragableObjectArray.length-1]['obj']!=dragObject)return 'append';	
					
				}
			}
			if(no<dragableObjectArray.length-1){
				if(x > (ref['left'] + ref['width']) && y>ref['top'] && y<(ref['top'] + ref['height']) && y<dragableObjectArray[no+1]['top']){
					return Array(dragableObjectArray[no+1],no+1);
				}
			}
		}	
		if(x>ref['left'] && y>(ref['top'] + ref['height']))return 'append';				
		return false;	
	}
		
	function initDrag(e)
	{
		var thisElement = $(this);
		dragObject = thisElement;
		
		if(document.all)e = event;
		mouse_x = e.clientX;
		mouse_y = e.clientY;
		if(!documentScrollHeight)documentScrollHeight = document.documentElement.scrollHeight + 100;
		el_x = getLeftPos(thisElement)/1;
		el_y = getTopPos(thisElement)/1;
		if(useRectangle){
			rectangleDiv.style.width = thisElement.clientWidth - (rectangleBorderWidth*2) +'px';
			rectangleDiv.style.height = thisElement.clientHeight - (rectangleBorderWidth*2) +'px';
			rectangleDiv.className = thisElement.className;
			$('rectangle').setStyle('float', thisElement.get('boxfloat'));
			
      try{
       if(($('input_list').get('value'))&&($('active_box').get('value'))){
         change_items($('active_box').get('value'),$('modul_options').getElement('input').get('value'));
       };  
      }catch(e){
       if($('modul_options').getStyle('display')=='none')$('modul_options').setStyle('display','none');
      }; 
      
      var ItemsText = '';
			if((thisElement.id=='chatbox')||(thisElement.id=='newusers')||(thisElement.id=='usersonline')||(thisElement.id=='comments')||(thisElement.id=='blogbox')||(thisElement.id=='newimages')||(thisElement.id=='newdocuments')||(thisElement.id=='newvideos')||(thisElement.id=='newaudios')||(thisElement.id=='bestrated')){
        ItemsText = '<li><form action="" class="boxform" onsubmit="return false;">'+modul_info_items+': <input type="text" maxlenght="10" id="input_list" value="'+thisElement.get('boxitems')+'" size="5" /><input type="hidden" id="active_box" value="'+thisElement.id+'" onchange="change_items2(\''+thisElement.id+'\');" /></form></li>';
      };

      $('modul_options').set('html', '<li>'+modul_info_name+': <b>'+thisElement.getElement('h2').get('text')+'</b></li><li>'+modul_info_float+': <span id="float_act">'+thisElement.get('boxfloat')+'</span> [<a href="javascript:change_float(\'' + thisElement.id + '\',\'left\');">left</a>|<a href="javascript:change_float(\'' + thisElement.id + '\',\'right\');">right</a>|<a href="javascript:change_float(\'' + thisElement.id + '\',\'none\');">none</a>]</li><li>'+modul_info_colls+': <span id="class_act">'+(thisElement.className.substr(5,1))+'</span> [<a href="javascript:change_class(\'' + thisElement.id + '\',\'col-s1\');">1</a>|<a href="javascript:change_class(\'' + thisElement.id + '\', \'col-s2\');">2</a>|<a href="javascript:change_class(\'' + thisElement.id + '\', \'col-s3\');">3</a>|<a href="javascript:change_class(\'' + thisElement.id + '\', \'col-s4\');">4</a>]'+ItemsText+'</li>');
      if($('modul_options').getStyle('display')=='none')$('modul_options').setStyle('display','block');
		}else{
			insertionMarkerLine.style.width = '6px';
		}
		dragDropTimer = 0;
		dragObjectNextObj = false;
		if(thisElement.nextSibling){
			dragObjectNextObj = thisElement.nextSibling;
			if(!dragObjectNextObj.tagName)dragObjectNextObj = dragObjectNextObj.nextSibling;
		}
		initDragTimer();
		return false;
	}
	
	function initDragTimer()
	{
		if(dragDropTimer>=0 && dragDropTimer<10){
			dragDropTimer++;
			setTimeout('initDragTimer()',5);
			return;
		}
		if(dragDropTimer==10){
			
			if(useRectangle){
				dragObject.style.opacity = 0.5;
				dragObject.style.filter = 'alpha(opacity=50)';
				dragObject.style.cursor = 'default';
			}else{
				var newObject = dragObject.cloneNode(true);
				dragDropMoveLayer.appendChild(newObject);
			}
		}
	}
	
	
	function autoScroll(direction,yPos)
	{
		if(document.documentElement.scrollHeight>documentScrollHeight && direction>0)return;
		
		window.scrollBy(0,direction);
		
		if(direction<0){
			if(document.documentElement.scrollTop>0){
				mouse_y = mouse_y - direction;
				if(useRectangle){
					dragObject.style.top = (el_y - mouse_y + yPos) + 'px';
				}else{
					dragDropMoveLayer.style.top = (el_y - mouse_y + yPos) + 'px';
				}			
			}else{
				autoScrollActive = false;
			}
		}else{
			if(yPos>(documentHeight-50)){		

				mouse_y = mouse_y - direction;
				if(useRectangle){
					dragObject.style.top = (el_y - mouse_y + yPos) + 'px';
				}else{
					dragDropMoveLayer.style.top = (el_y - mouse_y + yPos) + 'px';
				}				
			}else{
				autoScrollActive = false;
			}
		}
		if(autoScrollActive)setTimeout('autoScroll('+direction+',' + yPos + ')',5);
	}
	
	function moveDragableElement(e)
	{
		if(document.all)e = event;

		try{
    if(dragDropTimer<10)return;
    }catch(e){
    return;
    };
		if(!allowRectangleMove)return false;
		
		
		if(e.clientY<50 || e.clientY>(documentHeight-50)){
			if(e.clientY<50 && !autoScrollActive){
				autoScrollActive = true;
				autoScroll((autoScrollSpeed*-1),e.clientY);
			}
			
			if(e.clientY>(documentHeight-50) && document.documentElement.scrollHeight<=documentScrollHeight && !autoScrollActive){
				autoScrollActive = true;
				autoScroll(autoScrollSpeed,e.clientY);
			}
		}else{
			autoScrollActive = false;
		}
		if(useRectangle){			
       if(dragObject.style.position!='absolute'){
				dragObject.style.position = 'absolute';
				setTimeout('repositionDragObjectArray()',50);
			}
		}		
	
		if(useRectangle){
			rectangleDiv.style.display='block';
		}else{
			insertionMarkerDiv.style.display='block';	
			dragDropMoveLayer.style.display='block';	
		}
		
		if(useRectangle){
			dragObject.style.left = (el_x - mouse_x + e.clientX + Math.max(document.body.scrollLeft,document.documentElement.scrollLeft)) + 'px';
			dragObject.style.top = (el_y - mouse_y + e.clientY) + 'px';
		}else{
			dragDropMoveLayer.style.left = (el_x - mouse_x + e.clientX + Math.max(document.body.scrollLeft,document.documentElement.scrollLeft)) + 'px';
			dragDropMoveLayer.style.top = (el_y - mouse_y + e.clientY) + 'px';
		}
		dest = getObjectFromPosition(e.clientX+Math.max(document.body.scrollLeft,document.documentElement.scrollLeft),e.clientY+Math.max(document.body.scrollTop,document.documentElement.scrollTop));
		
		if(dest!==false && dest!='append' && dest!='self'){
			destinationObj = dest[0]; 
			
			if(currentDest!==destinationObj){
				currentDest = destinationObj;
				if(useRectangle){
					destinationObj['obj'].parentNode.insertBefore(rectangleDiv,destinationObj['obj']);
					repositionDragObjectArray();
				}else{
					if(dest[1]>0 && (dragableObjectArray[dest[1]-1]['obj'].offsetLeft + dragableObjectArray[dest[1]-1]['width'] + dragObject.offsetWidth) < dragableAreaWidth){
						insertionMarkerDiv.style.left = (getLeftPos(dragableObjectArray[dest[1]-1]['obj']) + dragableObjectArray[dest[1]-1]['width'] + 2) + 'px';
						insertionMarkerDiv.style.top = (getTopPos(dragableObjectArray[dest[1]-1]['obj']) - 2) + 'px';
						insertionMarkerLine.style.height = dragableObjectArray[dest[1]-1]['height'] + 'px';
					}else{					
						insertionMarkerDiv.style.left = (getLeftPos(destinationObj['obj']) - 8) + 'px';
						insertionMarkerDiv.style.top = (getTopPos(destinationObj['obj']) - 2) + 'px';
						insertionMarkerLine.style.height = destinationObj['height'] + 'px';
					}
					
					
				}
			}
		}
		
		if(dest=='self' || !dest){
			insertionMarkerDiv.style.display='none';
			destinationObj = dest;	
		}
		
		if(dest=='append'){
			if(useRectangle){
				dragableElementsParentBox.appendChild(rectangleDiv);
				dragableElementsParentBox.appendChild(document.getElementById('clear'));
			}else{
				var tmpRef = dragableObjectArray[dragableObjectArray.length-1];
				insertionMarkerDiv.style.left = (getLeftPos(tmpRef['obj']) + 2) + tmpRef['width'] + 'px';
				insertionMarkerDiv.style.top = (getTopPos(tmpRef['obj']) - 2) + 'px';
				insertionMarkerLine.style.height = tmpRef['height'] + 'px';	
			}
			destinationObj = dest;
			repositionDragObjectArray();
		}	
		
		if(useRectangle && !dest){
			destinationObj = currentDest;
		}
		
		allowRectangleMove = false;
		setTimeout('allowRectangleMove=true',50);
	}
	
	function stop_dragDropElement()
	{
		dragDropTimer = -1;
		
		if(destinationObj && destinationObj!='append' && destinationObj!='self'){
			destinationObj['obj'].parentNode.insertBefore(dragObject,destinationObj['obj']);
		}
		if(destinationObj=='append'){
			dragableElementsParentBox.appendChild(dragObject);
			dragableElementsParentBox.appendChild(document.getElementById('clear'));
		}
		
		if(dragObject && useRectangle){
			dragObject.style.opacity = 1;
			dragObject.style.filter = 'alpha(opacity=100)';
			dragObject.style.cursor = 'move';
			dragObject.style.position='static';
		}
		rectangleDiv.style.display='none';
		insertionMarkerDiv.style.display='none';
		dragObject = false;
		currentDest = false;
		resetObjectArray();
		destinationObj = false;
		if(dragDropMoveLayer){
			dragDropMoveLayer.style.display='none';
			dragDropMoveLayer.innerHTML='';
		}
		autoScrollActive = false;
		documentScrollHeight = document.documentElement.scrollHeight + 100;
		
	}
	
	function cancelEvent()
	{
		return false;
	}
	
	function repositionDragObjectArray()
	{
		for(var no=0;no<dragableObjectArray.length;no++){
			ref = dragableObjectArray[no];
			ref['left'] = getLeftPos(ref['obj']);
			ref['top'] = getTopPos(ref['obj']);			
		}	
		documentScrollHeight = document.documentElement.scrollHeight + 100;
		documentHeight = document.documentElement.clientHeight;
	}
	
	function resetObjectArray()
	{
		dragableObjectArray.length=0;
		var subDivs = dragableElementsParentBox.getElementsByTagName('*');
		var countEl = 0;

		for(var no=0;no<subDivs.length;no++){
			var attr = subDivs[no].getAttribute('dragableBox');
			if(opera)attr = subDivs[no].dragableBox;
			if(attr=='true'){
				var index = dragableObjectArray.length;
				dragableObjectArray[index] = new Array();
				ref = dragableObjectArray[index];
				ref['obj'] = subDivs[no];
				ref['width'] = subDivs[no].offsetWidth;
				ref['height'] = subDivs[no].offsetHeight;
				ref['left'] = getLeftPos(subDivs[no]);
				ref['top'] = getTopPos(subDivs[no]);
				ref['index'] = countEl;
				countEl++;
			}
		}	
	}
	

	
	function initdragableElements()
	{
		dragableElementsParentBox = document.getElementById('dragableElementsParentBox');
		insertionMarkerDiv = document.getElementById('insertionMarker');
		insertionMarkerLine = document.getElementById('insertionMarkerLine');
		dragableAreaWidth = dragableElementsParentBox.offsetWidth;
		
		if(!useRectangle){
			dragDropMoveLayer = document.createElement('DIV');
			dragDropMoveLayer.id = 'dragDropMoveLayer';		
			document.body.appendChild(dragDropMoveLayer);	
		}
		
		var subDivs = dragableElementsParentBox.getElementsByTagName('*');
		var countEl = 0;
		for(var no=0;no<subDivs.length;no++){
			var attr = subDivs[no].getAttribute('dragableBox');
			if(opera)attr = subDivs[no].dragableBox;
			if(attr=='true'){
				subDivs[no].style.cursor='move';	
				subDivs[no].onmousedown = initDrag;
				
				var index = dragableObjectArray.length;
				dragableObjectArray[index] = new Array();
				ref = dragableObjectArray[index];
				ref['obj'] = subDivs[no];
				ref['width'] = subDivs[no].offsetWidth;
				ref['height'] = subDivs[no].offsetHeight;
				ref['left'] = getLeftPos(subDivs[no]);
				ref['top'] = getTopPos(subDivs[no]);
				ref['index'] = countEl;
				countEl++;
			}
		}
		
		/* Creating rectangel indicating where item will be dropped */
		rectangleDiv = document.createElement('DIV');
		rectangleDiv.id='rectangle';
		rectangleDiv.style.display='none';
		dragableElementsParentBox.appendChild(rectangleDiv);
		
		
		document.body.onmousemove = moveDragableElement;
		document.body.onmouseup = stop_dragDropElement;
		document.body.onselectstart = cancelSelectionEvent;
		document.body.ondragstart = cancelEvent;
		window.onresize = repositionDragObjectArray; 
		
		documentHeight = document.documentElement.clientHeight;
	}


function sort_start(site){
  initdragableElements();
  if(site=='start'){
  $('modul_options').set('html', modul_info_text);
  }else{
  $('modul_options').set('html', modul_info_text2);
  };
  $('modul_options').setStyle('display','block');  
  $('index_start_arrange_content').setStyle('display','none');
  $('index_save_arrange_content').setStyle('display','block');
}
function sort_save(site){
    var subDivs = dragableElementsParentBox.getElementsByTagName('*');
		var countEl = 0;
		for(var no=0;no<subDivs.length;no++){
			var attr = subDivs[no].getAttribute('dragableBox');
			if(opera)attr = subDivs[no].dragableBox;
			if(attr=='true'){
				subDivs[no].style.cursor='none';	
				subDivs[no].onmousedown = '';
			}
		}
		
  	document.body.onmousemove = '';
		document.body.onmouseup = '';
		document.body.onselectstart = '';
		document.body.ondragstart = '';
		
		 try{
       if(($('input_list').get('value'))&&($('active_box').get('value'))){
         change_items($('active_box').get('value'),$('modul_options').getElement('input').get('value'));
       };  
      }catch(e){
       if($('modul_options').getStyle('display')=='none')$('modul_options').setStyle('display','none');
      }; 
		
		var saveString = "";
		for(var no=0;no<dragableObjectArray.length;no++){
			if(saveString.length>0)saveString = saveString + ';';
			ref = dragableObjectArray[no];
			saveString = saveString + ref['obj'].id+'#'+$(ref['obj'].id).get('boxfloat')+'#'+$(ref['obj'].id).get('boxcols')+'#'+$(ref['obj'].id).get('boxitems');
		}	
		
		//alert(saveString);
	
  var myAjax = new Request(
			{
				url: "ajax_com.php?action=startpage",
				method:'post',
        onFailure: function(e){showError(this.xhr)},
        onComplete: function(e){
        //console.log(e);
        window.location.reload();
        },
        data:'options=' + saveString
			}
	).send();
  	
  $('index_start_arrange_content').setStyle('display','block');
  $('index_save_arrange_content').setStyle('display','none');
  $('modul_options').setStyle('display','none');
  
}
function change_float(id,value){
 $(id).setStyle('float',value);
 $(id).set('boxfloat',value);
 $('float_act').set('html', value);
}
function change_class(id,value){
 if(value!='col-s1')$(id).removeClass('col-s1');
 if(value!='col-s2')$(id).removeClass('col-s2');
 if(value!='col-s3')$(id).removeClass('col-s3');
 if(value!='col-s4')$(id).removeClass('col-s4');
 $(id).addClass(value);
 $(id).set('boxcols',value.substr(5,1))
 $('class_act').set('html', value.substr(5,1));
}
function change_items(id, value){
 $(id).set('boxitems',value);
}
function change_items2(id){
 $(id).set('boxitems',$('modul_options').getElement('input').get('value'));
}