//OBS! This file is only included for admins as is...
//Do not add box-specific files that us usable by users here!

var activeDragable = null;
var activeHover = null;
var lastActiveHover = null;
var activeOptions = null;

function attachDragEffects() {
	$$('.BoxObject').each(function(box){
		doAttachDragEffects(box.id);
	});
}

function doAttachDragEffects(box_id) {
	//if ( $(box_id) == null || $(box_id) == false || $(box_id) == undefined || $(box_id) == '' ) {
	if ( box_id == null || box_id == '' ) {
		//log( "doAttachDragEffects was called without an id" );
		return false;
	}
	
	//we want to try it twice (once for the normal, once for the admin version)
	$A([box_id, box_id + '_admin']).each(function(element_id){
		var box = $(element_id);
		
		if ( box != null && box.id ) {
			var head = $(box.id + "_head");
			var drag_handle = $(box.id + "_drag_handle");
	
			if (box.hasClassName('Undragable') == false) {
				Event.observe( drag_handle, 'mousedown', function(e){ 
					hitarea = Event.element(e).id;
					if( hitarea.indexOf("_option_li") == -1 && hitarea.indexOf("_edit_li") == -1 && hitarea.indexOf("_delete_li") == -1 ) {
						activeDragable = box;
				
						$$('.BoxOptionsPopup').each(function(menu){ 
							menu.hide(); 
						});
				
						$$('.DropArea').each(function(drop_box){ 
							drop_box.addClassName('Revealed'); 
						});
					}
				});

				Event.observe( head, 'mouseup', function(e){ 
					activeDragable = null;
					$$('.DropArea').each(function(drop_box){ 
						drop_box.removeClassName('Revealed'); 
					});
				});
			}
	
			Event.observe( box, 'mouseover', function(e){ 
				activeHover = box;
				box.addClassName('BoxHover');
			});
	
			Event.observe( box, 'mouseout', function(e){ 
				lastActiveHover = activeHover;
				activeHover = null;
				box.removeClassName('BoxHover');
			});
		} else {
			//log( "unable to find box id " );
		}
	});
}

function placeGlobalOptions( element, option_menu_dom_id ) {
	
	//log( "element => " + element );
	//log( "option_menu_dom_id => " + option_menu_dom_id );
	//log( "option_menu_dom => " + $(option_menu_dom_id) );
	
	if (option_menu_dom_id == undefined) {
		options_menu = $(element + '_option_menu');
	} else {
		options_menu = $(option_menu_dom_id);
	}
	

	//if( activeOptions == element ) {
	//	options_menu.hide();
	//	activeOptions = null;
	//} else {
		var point = findPos($(element));
		
		//dynamix width on options menu
		//static_options_menu_with = (options_menu.getDimensions().width + 2);
		
		//static width on options meny, (from css)
		static_options_menu_with = 142;
		
		if( element.indexOf("_page_") == -1 ) {
			//for boxes
			var top = point[1] - 1;
			var left = point[0] + $(element).getDimensions().width - static_options_menu_with;
			//var top = point[1] - 40;
		} else {
			//for menus
			//var top = point[1] + 40;
			var top = point[1] + 20;
			//var left = (point[0] + $(element).getDimensions().width - (options_menu.getDimensions().width + 2)) - 9;
			var left = point[0] + $(element).getDimensions().width - 24;
			//var left = left - 9;
		}
		
		//var left = point[0] + $(element).getDimensions().width - (options_menu.getDimensions().width + 2);
		
		Element.setStyle(options_menu, {top:top+"px", left:left+"px", display:"block", position:"absolute"});
		activeOptions = element;
	//}
	
/*	
	if( activeOptions == element ) {
		$('global_box_options').hide();
		activeOptions = null;
	} else {
		var point = findPos($(element));
		if( element.indexOf("_page_") == -1 ) {
			var top = point[1] - 1;
		} else {
			var top = point[1] + 40;
		}
		
		var left = point[0] + $(element).getDimensions().width - ($('global_box_options').getDimensions().width + 2);
		Element.setStyle($('global_box_options'), {top:top+"px", left:left+"px", display:"block", position:"absolute"});
		activeOptions = element;
	}
*/
}

function replaceIfHasContainer( html, container ) {
	if ( $(container) ) {
		new Insertion.Top(container, html);
	}
}

function hideMenu( menu_dom_id ) {
	if( $(menu_dom_id) ) {
		$(menu_dom_id).hide();
	}
	if( $(menu_dom_id + '_admin') ) {
		$(menu_dom_id + '_admin').hide();
	}
}

function toggleBoxHeads() {
	$$('.BoxObject').each(function(box){
		box.toggleClassName('BoxHoverExpose');
	});
	toggleInnerHTML( 'toggle_box_head_link', 'Exponera boxar', 'Dölj exponering' );
	
	$$('.DropArea').each(function(drop_box){ drop_box.toggleClassName('Revealed'); });
}

function toggleBoxSort() {
	$$('.BoxObject').each(function(box){
		box.toggleClassName('Sort');
		box.toggleClassName('BoxHoverSort');
	});
	$$('.DropArea').each(function(drop_box){ drop_box.toggleClassName('Revealed'); });
	
	toggleInnerHTML( 'toggle_box_sort_mode_link', 'Visa sorteringsläge', 'Dölj sorteringsläge' );
}

var periodical_entry_scroller; //enables the PeriodicalExecuter to be stopped
function nextShowroomEntry( box_id, position, stop ) {
	var thumb_container = $('showroom_box_' + box_id + '_thumb_entries');
	var entries_container = $('showroom_box_' + box_id + '_entries');
	var thumbs = Selector.findChildElements(thumb_container, ['li'])
	var entries = Selector.findChildElements(entries_container, ['.ShowroomEntry'])
	var number_of_entries = thumbs.length;
	var mask_width = entries[1].getDimensions().width;
	var position = parseInt( position );
	var absolute_move = (-mask_width*position);
	
	entries_container.visualEffect('move', {'duration': 1.0, 'mode': 'absolute', 'x': absolute_move});
	
	var thumb_pos = 0;
  thumbs.each(function(entry){
		if( thumb_pos == position ) {
			entry.addClassName('Active');
		} else {
			entry.removeClassName('Active');	
		}
		thumb_pos += 1;
  });

	if ( stop != undefined && periodical_entry_scroller != undefined ) {
		periodical_entry_scroller.stop();
	}
		
/*  In this version the loop is perfect. The downside is that an infinite amount of clones are created
		This crashes the browser after some minutes
			
		if ( position == (number_of_entries-2) ) {
			creat_clones = true;
		}
		
		if( create_clones ) {
			entry_to_copy = (number_of_entries-2) - position;
			log( "position: " + position + ", entry_to_copy: " + entry_to_copy );
			clone = entries[position].cloneNode(true);
			clone.addClassName( "Clone" );
			entries_container.appendChild(clone);
		}
		
		entries_container.visualEffect('move', {'duration': 1.0, 'mode': 'relative', 'x': -mask_width});
*/		
}

function periodicalScrollEntry( box_id, num_entries, frequency ) {
	var pos = 0; 
	periodical_entry_scroller = new PeriodicalExecuter(function() {
		if ( pos >= num_entries ) {
			nextShowroomEntry( box_id, 0 );
			pos = 1;
		} else {
			nextShowroomEntry( box_id, pos );
			pos += 1;	
		}
	}, frequency);
}


showroom_thumb_position = 0;
function scrollEntry( dir, box_id ) {
	var outer_container_id = 'showroom_box_' + box_id;
	var box_width = $(outer_container_id).getDimensions().width;
	
	var container_id = 'showroom_box_' + box_id + '_thumb_entries';
	var entry_width = $(container_id).childElements()[0].getDimensions().width;
	
	if ( box_width > (entry_width+10) ) {
		var x_movment = (entry_width * dir);
		var y_movment = 0;
	} else {
		var x_movment = 0;
		var y_movment = (entry_width * dir);
	}
	
	//log( 'box_width: ' + box_width );
	//log( 'entry_width: ' + entry_width );
	
	//new Effect.Move(container_id, {x: x_movment, 'duration': 0.5});
	//new Effect.Move(container_id, {y: x_movment, 'duration': 0.5});
	new Effect.Move(container_id, {x: x_movment, y: y_movment, 'duration': 0.5});
	
	//element.visualEffect('move', {'duration': 0.5, 'x': (element.firstChild.getDimensions().width * dir)});
	
	
	//$('showroom_box_' + box_id + '_thumb_entries').visualEffect('move', {'duration': 0.5, 'x': ($('showroom_box_' + box_id + '_thumb_entries').firstChild.getDimensions().width * dir)});
	
	//dir < 0 means show new entries from the right (move the entries to the left)
	//dir > 0 means show new entries from the left (move the entries to the rigth)
	
	/*var entries_container = $('showroom_box_' + box_id + '_thumb_entries');
	var thumb_width = entries_container.firstChild.getDimensions().width;
	var number_of_entries = entries_container.childNodes.length;
	var loop_length = thumb_width * number_of_entries
	
	log( 'number_of_entries => ' + number_of_entries );
	
	log( 'showroom_thumb_position => ' + showroom_thumb_position );
	showroom_thumb_position = (showroom_thumb_position+(-dir));
	log( 'showroom_thumb_position => ' + showroom_thumb_position );	
	
	//TODO: make this go in the moved style instead (make the move absolute)
	
	if( showroom_thumb_position < -2 ) {
		showroom_thumb_position = showroom_thumb_position + 1
		entries_container.visualEffect('shake');
		window.setTimeout(function() { entries_container.setStyle( {'position': 'relative'} ); }, 501);
		return false;
	} else if( showroom_thumb_position >= number_of_entries ) {
		showroom_thumb_position = showroom_thumb_position - 1
		entries_container.visualEffect('shake');
		window.setTimeout(function() { entries_container.setStyle( {'position': 'relative'} ); }, 501);
		return false;
	} else {
		
		entries_container.visualEffect('move', {'duration': 0.5, 'x': (thumb_width * dir)});
	}*/
}

function change_geometry( dom_id, url, options ) {	
	var dimensions = $(dom_id).getDimensions();
	var w = dimensions.width;
	var h = dimensions.height;
	
	log( "WxH => " + w + "x" + h );
	
	url = url.replace('__w__', w );
	url = url.replace('__h__', h );
	url = url.gsub('&amp;', '&' );
	
	new Ajax.Request( url, options );
}




// ------------ InfiniteScroll -------------- //
/* Usage:
 * 1) Include the file
 * 2) on load, create a new instance of the class "Control.ContiniousInfiniteScroll"
 *    arguments to the constructor should be the element containing the stuff that
 *    will be scrolled and the elements that onmouseover/out will scroll the stuff
 *    back and forth (see the function initialize).
 * 3) An optional fourth argument containing configuration stuff can be passed along,
 *    se configuration below.
 *
 */

/* Usage:
 * 1) Include the file
 * 2) on load, create a new instance of the class "Control.ContiniousInfiniteScroll"
 *    arguments to the constructor should be the element containing the stuff that
 *    will be scrolled and the elements that onmouseover/out will scroll the stuff
 *    back and forth (see the function initialize).
 * 3) An optional fourth argument containing configuration stuff can be passed along,
 *    se configuration below.
 *
 */

function initShowroomBoxes() {
	//$$('#ShowroomBox').each(function(box){
		if ( $('showroom_box_9') ) {
			new Control.ContiniousInfiniteScroll('showroom_box_9');
		}
	//});
}

if (!Control) var Control = {};

Control.ContiniousInfiniteScroll = Class.create(
{

  /* shared static members,
   * don't change these or else confusion will follow
   */
  dir: {back: -1, forth: 1},
  orientation: {horizontal: 1, vertical:-1},

  initialize: function (scrollHolder, backLink, forthLink, attrs) {
    /* configuration, this is the fourth argument
     * to the constructor. defaults explained below:
     */
    var defaultAttributes = {
      //element holding the elements to scroll
      scrollerQuery: '.Thumbs',
      //element that hides the overflow
      paneQuery: '.ShowroomMask',
      //how many pixels to move per interval. higher makes the movement
      //faster but more choppy.
      pixelsPerInterval: 10,
      //how long (in seconds) to wait between each move.
      intervalWait: 0.03,
      //true for endless, false will probably induce strange results
      faking: true,
      //set to true, this will show the center-most elements after
      //initialization.
      centerOnStart: false,
      orientationAuto: true
    };


    var a = this.attrs = attrs ? Object.extend(defaultAttributes, attrs) : defaultAttributes;

    this.scrollHolder = $(scrollHolder);
    this.backLink = $(this.scrollHolder.id + '_left_scroll_link');
    this.forthLink = $(this.scrollHolder.id + '_right_scroll_link');
		
		//this.forthLink = $(forthLink);
		//this.backLink = $(backLink);
		
    this.scroller = this.scrollHolder.select(a.scrollerQuery)[0];
    this.visibleArea = this.getArea(this.scrollHolder.select(a.paneQuery)[0]);
    this.scrollerArea = this.getArea(this.scroller);
		
		//disable onclick
		this.backLink.onclick = 'return false;'
		this.forthLink.onclick = 'return false;'

    if (!this.scroller)
      return;

    if (a.orientationAuto)
      this.attrs.orientation = this.findOrientation();

    // build child table
    this.extractElements();
    if (this.scrollElements.length == 0)
      return;


    this.pixelsPerInterval = a.pixelsPerInterval;
    this.intervalWait = a.intervalWait;


    if (a.faking)
      this.createFakes();
    else
      this.setCurrentOffs(0);

    this.bindings();
  },

  extractElements: function () {
    var scrollNodes = this.scroller.select("li"), vert = this.isVertical();

    var scrollElements = [], elementsArea = 0;


    var that = this;
    scrollNodes.each(function(item)
    {
      var offs = item.positionedOffset(), w = item.getWidth(), h = item.getHeight();
      var a = that.getArea(item);

      scrollElements.push(
	{
	  node: item,
	  area: a
	}
      );
      elementsArea += a;

    });

    this.scrollElements = scrollElements;
    this.elementsArea = elementsArea;
  },

  /* set up event handlings */
  bindings: function() {
    var fl = this.forthLink, bl = this.backLink;
    var b = this.dir.back, f = this.dir.forth;

    bl.observe("mouseover", this.startScroll.bindAsEventListener(this, b));
    bl.observe("mouseout", this.stopScroll.bindAsEventListener(this, b));

    fl.observe("mouseover", this.startScroll.bindAsEventListener(this, f));
    fl.observe("mouseout", this.stopScroll.bindAsEventListener(this, f));
  },

  /* Insert fakes */
  createFakes: function () {
    var that = this, vis = this.visibleArea, se = this.scrollElements;

    var fakesInsertAtFront = [], leftFakeArea = 0;
    for (var i = 0; leftFakeArea < vis; i++) {
      var fakeIdx = se.length - 1 - (i % se.length);
      fakesInsertAtFront.push(
	se[fakeIdx].node.cloneNode(true)
      );
      leftFakeArea += se[fakeIdx].area;
    }


    var fakesInsertAtBack = [], rightFakeArea = 0;
    for (var j = 0, len = 0; rightFakeArea < vis; j++) {
      var fakeIdx = j %  se.length;
      fakesInsertAtBack.push(
	se[fakeIdx].node.cloneNode(true)
      );
      rightFakeArea += se[fakeIdx].area;
    }

    // Re-adjust scroller size to compensate for the faked elements
    var scroller = this.scroller;
    this.scrollerArea = rightFakeArea + this.elementsArea + leftFakeArea;
    this.setArea(scroller, this.scrollerArea + "px");



    fakesInsertAtBack.each(function(item) {
      scroller.appendChild(item);
    });
    fakesInsertAtFront.each(function(item) {
      scroller.insertBefore(item, scroller.firstChild);
    });

    fakesInsertAtBack.concat(fakesInsertAtFront).each(function (item) {
      item.removeAttribute('id');
    });

    var start = this.attrs.centerOnStart ?
      (this.scrollElements[this.scrollElements.length-1].rOffs - this.slidePaneArea)/2
      : leftFakeArea;
    this.setCurrentOffs(start);

    this.leftFakeArea = leftFakeArea, this.rightFakeArea = rightFakeArea;
  },

  /* scrolling functions */
  startScroll: function(ev, direction) {
    this.attrs.test = "asdf";

    //var slideStepFunction = faking ? this.slideStepFaking : this.slideStep;
    var slideStepFunction = this.slideStepFaking;

    this.pe = new PeriodicalExecuter(
      slideStepFunction.bind(this, direction) ,
      this.intervalWait
    );
  },

  stopScroll: function() {
    if (this.pe) this.pe.stop();
  },

  /* Step functions */
  slideStep: function (direction) {
    var newOffs = this.getCurrentOffs() + direction*this.pixelsPerInterval;
    this.setCurrentOffs(newOffs);
  },

  slideStepFaking: function (direction) {
    var leftFakeArea = this.leftFakeArea, rightFakeArea = this.rightFakeArea, elementsArea = this.elementsArea;
    var jumpToEndStartOffs = leftFakeArea + elementsArea;
    var newOffs = this.getCurrentOffs() + direction*this.pixelsPerInterval;

    //verkar som att det här ska skrivas helt annorlunda för vertikala
    if (newOffs > jumpToEndStartOffs) { //vi har gått för långt åt höger
      newOffs = leftFakeArea + newOffs % jumpToEndStartOffs;
    }
    else if (newOffs < 0) { //vi har gått för långt åt vänster
      newOffs = leftFakeArea + (elementsArea - leftFakeArea) + newOffs;
    }

    this.setCurrentOffs(newOffs);
  },


  /* Offset-functions */
  setCurrentOffs: function(offs) {
    this.currentOffs = offs;
    var m = this.isHorizontal() ? {x: offs} : {y: offs};
    this.move(this.scroller, m);
  },

  getCurrentOffs: function() {
    return this.currentOffs;
  },

  /* Area functions
   * area is height in a vertical scroller,
   * width in a horizontal.
   * */
  getArea: function(e) {
    if (this.isHorizontal())
      return e.getWidth();
    else
      return e.getHeight();
  },

  getCompArea: function(e) {
    if (this.isHorizontal())
      return e.getHeight();
    else
      return e.getWidth();
  },

  setArea: function(e, a) {
    if (this.isHorizontal())
      return e.setStyle({width: a});
    else
      return e.setStyle({height: a});
  },

  setCompArea: function(e, a) {
    if (this.isHorizontal())
      return e.setStyle({height: a});
    else
      return e.setStyle({width: a});
  },

  /* orientation helpers */
  findOrientation: function () {
    var dims = this.scroller.getDimensions();
    if (dims.width > dims.height)
      return this.orientation.horizontal;
    else
      return this.orientation.vertical;
  },

  isHorizontal: function() {
    return this.attrs.orientation == this.orientation.horizontal;
  },
  isVertical: function() {
    return this.attrs.orientation == this.orientation.vertical;
  },

  /* moving stuff */
  move: function(el, mattrs ) {
    if (el.getStyle('position') != 'relative')
      el.setStyle({position: 'relative'});

    if (mattrs.x)
      el.setStyle({right: mattrs.x + "px"});
    if (mattrs.y)
      el.setStyle({bottom:  mattrs.y + "px"});
  }
});

function showDir(d) { if (d == -1) return "back"; else return "forth";}