var IE;
var tempX = 0;
var tempY = 0;
var placeholderContainer;
var container;
var currentElement;	
var currentElementId;	
var nextFreePlaceholder;
var currentPlaceHolder;
var dropArea;	
var dropAreaDisplayed = false;
var boxPosition;
var merklisteBox = new Object();
var noMoveArea = 20;
var moveArea = 65;
var offset;
var maxSpeed = 7;

document.observe("dom:loaded", function() {
	IE = document.all ? true : false;
	var box = $("merklisteBox");
	if( box ){
		merklisteBox.w = box.getWidth();
		merklisteBox.h = box.getHeight();
		offset = box.cumulativeOffset();
	
		placeholderContainer = $('placeholderContainer');
		container = $('MerklistenContainer');
		var offsetX = container.getWidth()/2;
	  	var offsetY = container.getHeight()/2;
	   dropArea = $('dropArea');

		boxPosition = $(placeholderContainer).up(0).cumulativeOffset();

		Event.observe(document, 'mousemove', function( event ) {
			if( currentElement ) container.setStyle({left: event.pageX-offsetX+"px", top: event.pageY-offsetY+"px"});
		});
	
		document.onmousemove = getMouseXY;
		if (!IE) document.captureEvents(Event.MOUSEMOVE);
	
		setInterval( movePlaceHolders, 20 );
	}
	resizeBox();
});


function resizeBox(){
	var topicBox = $('topicBox').getHeight();
	if (topicBox > 225){
		
		var h = topicBox - 225;
		h = h + 672;
		$('mod-showroom').setStyle({ height: h+"px"});				// Resize topicBox to prevent menu overlapping
	}
	else $('mod-showroom').setStyle({ height: "672px"});
}

/* Functions called by Flash */
function saveToReminderList( url, id ){
	currentElementId = id;
	currentElement = url;

	var images = container.select('img');
	images.each(function(el){
		$(el).remove();
	});
	
   container.insert('<img id="thumb_'+id+'" width="35" height="35" src="'+url+'" alt="" />');
	placeElement();
	
	currentElementId = null;
	currentElement = null;
}

function dragAhead( url, id ){
	showDropArea();
	currentElementId = id;
	currentElement = url;
	var images = container.select('img');
	images.each(function(el){
		$(el).remove();
	})
	container.insert('<img id="thumb_'+id+'" width="35" heigh="35" src="'+url+'" alt="" />')
//	container.update('');
	container.observe( 'mouseup', function(e){
		if( checkIfInDropArea() ) placeElement();						// place element into reminder list, if mouse is inside of droparea	

		currentElementId = null;												// reset currentelement
		currentElement = null;												// reset currentelement
		container.setStyle({ top: -200+"px" });						// hide div container for thumb
		hideDropArea();														// fade out the drop area
	});
}



/* Reminderlist handling */
function placeElement(){
	var thumb = container.select('img');
	thumb = $(thumb[0]);
	if( thumb ){
		thumb.setStyle({width: "34px", height: "34px"});
		getNextFreePlace();
		var placedImage = nextFreePlaceholder.update( thumb );
		scrollToElement( placedImage );

		saveCookie( currentElementId );										// Save Current Element To List
	
		$('DragDropTrigger').observe( 'mousedown', function(event){
			showDropArea();
			currentElementId = thumb.readAttribute( "id" ).split("_")[1];
			currentPlaceHolder = placedImage;
			currentElement = thumb;
			container.update(thumb);
			Event.stop( event );
		});
	
		$('DragDropTrigger').observe( 'mouseup', function(event){
			if( checkIfInDropArea() ){
				placeElement();
			}else{				
				thumb.shrink({ duration: 0.2, afterFinish: function(){ 
					container.setStyle({ top: -200+"px" });
				}});
			}
			removeFromCookie( currentElementId );
		
		
			currentElementId = null;
			currentElement = null;
			hideDropArea();
			Event.stop( event );
		});
	}
}

function checkIfInDropArea(){
	var offsets = dropArea.cumulativeOffset();
	var dropAreaX = offsets.left;
	var dropAreaY = offsets.top;
	var dropAreaXW = offsets.left+dropArea.getWidth();
	var dropAreaYH = offsets.left+dropArea.getHeight();
	
	var containerX = parseInt(container.getStyle('left'));
	var containerY = parseInt(container.getStyle('top'));

	if( containerX > dropAreaX && containerX < dropAreaXW && containerY > dropAreaY && containerY < dropAreaYH ) return true;
	else return false;
}

function getNextFreePlace(){
	var placeholders = $$('.placeholder');
	var placeholdersLength = placeholders.length;
	for( var i = 0; i < placeholdersLength; i++ ){
		var item = $(placeholders[i]);
		var length = item.childElements().length;
		if( length == 0 ){
			nextFreePlaceholder = item;
			return;
		}
	}
	
	createNewPlaceHolder();
}

function createNewPlaceHolder(){
	var placeHolders = '<li><ul><li class="placeholder"></li><li class="placeholder"></li></ul></li>';
	placeholderContainer.insert( placeHolders );
	getNextFreePlace();
}

function moveToElement(){
	var placeholders = $$('.placeholder');
	var placeholdersLength = placeholders.length;
	var col = 0;
	for( var i = 0; i < placeholdersLength; i++ ){
		if(placeholders[i] == currentElement) col = Math.floor(i/2);
	}
}

function scrollToElement(el){
	if( el ){
		var minScrolling = 0;
		var maxScrolling = 222 - placeholderContainer.getWidth();   // 222 = full width of box

		var containerPosition = placeholderContainer.cumulativeOffset();
		var elementPosition = el.cumulativeOffset();
		var elementLeft = containerPosition.left - elementPosition.left;
		
		if( elementPosition.left >= boxPosition.left+222 || elementPosition.left < boxPosition.left ){
			if( elementLeft < 0 && maxScrolling > elementLeft  && elementLeft ){		
				
				elementLeft = elementLeft < maxScrolling ? maxScrolling : elementLeft;
				var currentPosition = parseInt(placeholderContainer.getStyle('marginLeft'));
				
				/* Move Boxes => element should be in visible area */
				var effect = new Effect.Tween(
					placeholderContainer, 
					currentPosition, 
					elementLeft, 
					{ 
						duration: 0.5,
						transition: Effect.Transitions.sinoidal 
					}, 
					function( p ){
						placeholderContainer.setStyle({ 
							marginLeft: p+"px" 
						});
					}
				);
				
				
			}
		}
	}   
}

function movePlaceHolders(){
	if( !dropAreaDisplayed ){
		if( tempY > offset.top && tempY < offset.top+merklisteBox.h ){
			var x = tempX;
			var currentPos = parseInt(placeholderContainer.getStyle("marginLeft"));
			var newMarginLeft = 0;
	
			if( x > offset.left && x < offset.left+merklisteBox.w ){
				if( x < offset.left+moveArea ){
					var percentLeft = 100-((100/moveArea)*(x-offset.left));
					newMarginLeft = ((10/100)*percentLeft)*-1;
				}else{
					if( x > (offset.left+merklisteBox.w-moveArea) ){
						var percentRight = (100/moveArea)*(x-(offset.left+156));
						newMarginLeft = ((10/100)*percentRight);
					}
				}
			}
			var allowedTotalMove = merklisteBox.w-Math.round(placeholderContainer.getWidth());
	
			var totalMarginLeft = currentPos-newMarginLeft;
			totalMarginLeft = ( totalMarginLeft + ( currentPos - totalMarginLeft ) / 1.5 );
	
			if( totalMarginLeft < 0 && totalMarginLeft > allowedTotalMove ){
				placeholderContainer.setStyle({ marginLeft: totalMarginLeft+"px" });	
			}else{
				if( totalMarginLeft > 0 ) placeholderContainer.setStyle({ marginLeft: 0+"px" });	
				if( totalMarginLeft < allowedTotalMove ) placeholderContainer.setStyle({ marginLeft: allowedTotalMove+"px" });	
			}
		}
	}
}



/* Referenzen */
function showReferenzen( categories ){
	var url = $('AjaxReferenzen').readAttribute('href');
	new Ajax.Request(url+"?Kategorien="+categories, { method: 'get',
	  onSuccess: function( transport ){
			$('RefernzenContainer').update( transport.responseText );
	  }
	});
}



/* Cookie Handling */
function readCookie(){
	if( Cookie.exists("Merkliste") ) return Cookie.get("Merkliste");
	return "";
}

function saveCookie( value ){
	var savedImages = readCookie();
	savedImages = savedImages.split(",");
	if( !inArray( value, savedImages ) ){
		savedImages.push( value );
		Cookie.set( "Merkliste", savedImages.join(',') );
	}
}

function removeFromCookie( value, el ){
	var savedImages = readCookie().split(",");
	var newCookie = "";
	for( var i = 0; i< savedImages.length; i++ ){
		if( savedImages[i] != value ) newCookie += savedImages[i]+",";
	}
	Cookie.set( "Merkliste", newCookie );
	if( el ){
		$(el).blindUp({ duration: 0.2 });
	}
}



/* Helpers */
function resizeFlash( h ){
	var Index = 100;
	var bgPos = 'left bottom';
	if( h > 421 ) {
		Index = 500;
		bgPos = '0 -10px';
	}
	if( h == 420 ) Index = 100;
	$('ShowroomFlash').setStyle({ height: h+"px", zIndex: Index, backgroundPosition: bgPos});
	var currentHeight = $('ShowroomFlash').getStyle('height');
}

function inArray( value, arr ){
	for( var i = 0; i<arr.length; i++ ){
		if( arr[i] == value ) return true;
	}
	return false;
}

function showDropArea(){
	dropArea.appear({ duration: 0.5, from: 0, to: 1 });
	dropAreaDisplayed = true;
}

function hideDropArea(){
	dropArea.fade({ duration: 0.3, from: 1, to: 0 });
	dropAreaDisplayed = false;
}

function getMouseXY(e) {
  if (IE){
	tempX = event.clientX + document.body.scrollLeft
	tempY = event.clientY + document.body.scrollTop
  }else{
	tempX = e.pageX;
	tempY = e.pageY;
  }
  if (tempX < 0) tempX = 0;
  if (tempY < 0) tempY = 0;
  
  return true;
}
