// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


Playroom = new Object();

Playroom.addToCartURL = '/carts/add_to_current'
Playroom.removeFromCartURL = '/carts/remove_from_current'
Playroom.cartInfoDefaultText = 'Dra varer inn i og ut av handlekurven for å legge til og fjerne dem.'
Playroom.cartUpdateInProgress = false

Playroom.addToCart = function(itemID){
  $('shopping-cart').scrollTop = 0
  Playroom.updateCartInfo('Legger til varen i kurven..', null, 'working')
  new Ajax.Request(Playroom.addToCartURL, {
    parameters: $H({id: itemID}).toQueryString(),
    onLoading: function(){
      Playroom.cartUpdateInProgress = true
    },
    onSuccess: function(xhr){
      
    },
    onComplete: function(){
      Playroom.cartUpdateInProgress = false
    }
  })
}

Playroom.removeFromCart = function(itemID, element){
  $('shopping-cart').scrollTop = 0
  new Ajax.Request(Playroom.removeFromCartURL, {
    parameters: $H({id: itemID}).toQueryString(),
    onLoading: function(){
      Playroom.cartUpdateInProgress = true
      Playroom.updateCartInfo('Fjerner varen fra kurven..', null, 'working')
    },
    onComplete: function(){
      Playroom.cartUpdateInProgress = false
    }
  })
}

Playroom.extractIdFromAttribute = function(att){
  return att
}

Playroom.updateCartInfo = function(text, hideDelay, highlightClassName, showDelay){
  
  Element.update('shopping-cart-info', text)
  
  if (Playroom.cartInfoHighlightClassName) {
    Element.removeClassName('shopping-cart-info', Playroom.cartInfoHighlightClassName)
  }
  
  if (highlightClassName) {
    Element.addClassName('shopping-cart-info', highlightClassName)
    Playroom.cartInfoHighlightClassName = highlightClassName
  }
  
  Playroom.showCartInfo(showDelay)
  
  if (hideDelay != false) {
    Playroom.hideCartInfo(hideDelay)
  }
}

Playroom.showCartInfo = function(delay){
  if (Playroom.showCartInfoTimeout) {
    clearTimeout(Playroom.showCartInfoTimeout)
  }
  
  if (delay){
    Playroom.showCartInfoTimeout = setTimeout(function(){
      Element.show('shopping-cart-info')
    }, delay*1000)
  } else {
    Element.show('shopping-cart-info')
  }
}

Playroom.hideCartInfo = function(delay){
  var delay = (delay == null) ? 5 : delay

  if (Playroom.removeCartInfoTimeout) {
    clearTimeout(Playroom.removeCartInfoTimeout)
  }
  
  if (delay){
    Playroom.removeCartInfoTimeout = setTimeout(function(){
      Element.hide('shopping-cart-info')
    }, delay*1000)
  } else {
    Element.hide('shopping-cart-info')
  }
}

Playroom.createCartDraggable = function(element){

  element.hasBeenDragged = false
  
  var image = document.getElementsByClassName('cart-item-preview', element)[0]
	new Draggable(element, {
	  revert: true,
	  starteffect: function(element) {
		//Element.setStyle('shopping-cart', {overflow: 'visible'})
	    new Effect.Opacity(element, {duration:0.2, from:1.0, to:0.5}); 
	  },
	  endeffect: function(element) {
      //Element.setStyle('shopping-cart', {overflow: 'auto'})
	    if (!Element.hasClassName(element, 'removable')) {//Keep
	      new Effect.Opacity(element, {duration:0.2, from:0.5, to:1.0}); 
	    } else {//Remove from cart
	      Playroom.removeFromCart(image.getAttribute('item-id'))
	      Element.setStyle(element, {position: 'absolute'})
			//	Element.setStyle(element, {position: 'relative'})
	      //new Effect.Fade(element, {duration: 0.2})
	      Element.remove(element)
	      Element.removeClassName('shopping-cart', 'accept-removal')
	    }
	  },
	  change: function(instance){
	    instance.element.hasBeenDragged = true
	    var offset = Position.cumulativeOffset(instance.element)
	    Position.withinIncludingScrolloffsets($('shopping-cart'), offset[0], offset[1])
	    var overlap = Position.overlap('horizontal', $('shopping-cart'))
	    if (overlap < 0.25 || overlap > 1.75) {
        Element.addClassName('shopping-cart', 'accept-removal')
        Element.addClassName(instance.element, 'removable')
        Playroom.updateCartInfo('Slipp varen for å fjerne den fra handlekurven', false, 'highlight')
	    } else {
	     Element.removeClassName('shopping-cart', 'accept-removal')
	     Element.removeClassName(instance.element, 'removable')
	     Playroom.hideCartInfo(false)
	    }
	  }
	})
	
	//Stop propagation when dragged
	Event.observe(element, 'click', function(e){
	  if (element.hasBeenDragged) {
	    Event.stop(e)
	    element.hasBeenDragged = false
	  }
	})

}

Playroom.CartObserver = Class.create();
Playroom.CartObserver.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Element.hasClassName(this.element, 'accept-drop');
  }
});


Playroom.bodyMovinBodyMovinWeBeGettingDownAndYouKnowWereCrushGroovin = function () {

  $$('#messages *').each(function(element){
    element.title = 'Dobbelklikk for å fjerne'
    Event.observe(element, 'dblclick', function(e){
      new Effect.Fade(element)
    })
  })
  
  
  //Make items draggable
  $$('#left .item-preview').each(function(element){
  
    element.hasBeenDragged = false
  
    element.setAttribute(
      'title', 'Klikk for å vise denne varen eller dra den til handlekurven for å legge den til'
    )
    
    new Draggable(element, {
      revert: true,
      ghosting: true,
		  change: function(){
		    element.hasBeenDragged = true
		  }
    })
    
    //Stop propagation when dragged
		Event.observe(element, 'click', function(e){
		  if (element.hasBeenDragged) {
		    Event.stop(e)
		    element.hasBeenDragged = false
		  }
		})
    
  })
  
  //Make shopping cart a droppable
  if ($('shopping-cart')) {
  
    var cartDrop = $('shopping-cart')
    Droppables.add(cartDrop, {
 //     accept: ['item-preview'],
			accept: 'item-preview',
      hoverclass: 'accept-drop',
      onDrop: function(draggable, droppable){
        if (!Element.hasClassName(draggable, 'remove')) {
          Playroom.addToCart(
            Playroom.extractIdFromAttribute(
              draggable.getAttribute('item-id')
            )
          )
        }
      }
    })
    
  }
  
  /*
  $$('#shopping-cart-items .delete').each(function(element){
    Playroom.hijackCartDeleteLink(element)
  })*/
  
  new Playroom.CartObserver($('shopping-cart'), 0.5, function(cart, acceptingDrop){
    if (acceptingDrop) {
      $('shopping-cart').scrollTop = 0
      Playroom.updateCartInfo('Slipp varen for å legge den i handlekurven.', false, 'highlight')
    } else if (!Playroom.cartUpdateInProgress) {
      Playroom.hideCartInfo(false)
    }
  })
  
  //Make items in shopping cart draggable
  document.getElementsByClassName('shopping-cart-item', 'shopping-cart-items').each(function(element){
    
    Playroom.createCartDraggable(element)
    
  })
  
  new Insertion.Bottom('shopping-cart', '<div id="shopping-cart-info" style="display:none"></div>')
  Element.update('shopping-cart-description', 'Dra varer inn i eller ut av handlekurven for å legge til eller fjerne.')

}

Event.observe(window, 'load', Playroom.bodyMovinBodyMovinWeBeGettingDownAndYouKnowWereCrushGroovin)
