// Copyright (c) 2005 Thomas Fakes (http://craz8.com)
//
// This code is substantially based on code from script.aculo.us which has the
// following copyright and permission notice
//
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var ScaleMover = Class.create();
ScaleMover.prototype = {
  initialize: function(scaleelement, yearelements) {

    this.scaleElement      = $(scaleelement);
    this.scaleElementHandle  = this.scaleElement;
    this.yearElements = $$(yearelements);
    this.yearElementHandle  = this.yearElements;

    //Element.makePositioned(this.element); // fix IE

    //this.options      = options;

    this.active       = false;
    this.moving     = false;
    this.currentDirection = '';

    this.eventMouseDown = this.startResize.bindAsEventListener(this);
    this.eventMouseUp   = this.endResize.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);
    this.eventCursorCheck = this.cursor.bindAsEventListener(this);
    this.eventKeypress  = this.keyPress.bindAsEventListener(this);

    this.registerEvents();
  },
  destroy: function() {
    Event.stopObserving(this.scaleElementHandle, "mousedown", this.eventMouseDown);
    this.unregisterEvents();
  },
  registerEvents: function() {
    Event.observe(document, "mouseup", this.eventMouseUp);
    Event.observe(document, "mousemove", this.eventMouseMove);
    Event.observe(document, "keypress", this.eventKeypress);
    Event.observe(this.scaleElementHandle, "mousedown", this.eventMouseDown);
    Event.observe(this.scaleElementHandle, "mousemove", this.eventCursorCheck);
  },
  unregisterEvents: function() {
    //if(!this.active) return;
    //Event.stopObserving(document, "mouseup", this.eventMouseUp);
    //Event.stopObserving(document, "mousemove", this.eventMouseMove);
    //Event.stopObserving(document, "mousemove", this.eventCursorCheck);
    //Event.stopObserving(document, "keypress", this.eventKeypress);
  },
  startResize: function(event) {
    if(Event.isLeftClick(event)) {

      // abort on form elements, fixes a Firefox issue
      var src = Event.element(event);
      if(src.tagName && (
        src.tagName=='INPUT' ||
        src.tagName=='SELECT' ||
        src.tagName=='BUTTON' ||
        src.tagName=='TEXTAREA')) return;

	  //var dir = this.directions(event);
	  //if (dir.length > 0) {
	      this.active = true;
	      //this.startWidth = getPercentofViewPort(parseInt(Element.getStyle(this.element, 'width')));
	      //this.seconStartWidth = getPercentofViewPort(parseInt(Element.getStyle(this.secondElement, 'width')));
	      //this.startX = getPercentofViewPort(event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft);
	      this.startLeft = getPercentofViewPort(Element.getStyle(this.yearElements[1], 'left'),false);
	      this.startX = getPercentofViewPort(event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft, true);
	      //this.currentDirection = dir;
	      Event.stop(event);
	  //}
    }
  },
  finishResize: function(event, success) {
    // this.unregisterEvents();

    this.active = false;
    this.moving = false;



    //if (this.options.resize) {
    //	this.options.resize(this.scaleElement);
    //}
  },
  keyPress: function(event) {
    if(this.active) {
      if(event.keyCode==Event.KEY_ESC) {
        this.finishResize(event, false);
        Event.stop(event);
      }
    }
  },
  endResize: function(event) {
    if(this.active && this.moving) {
      this.finishResize(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.moving = false;
  },
  draw: function(event) {
    var pointer = getPercentofViewPort(Event.pointerX(event),true);

    var style = this.yearElements[1].style;
    //alert(Element.getStyle(this.yearElements[1],'left'));
    var newLeft = this.startLeft + pointer - this.startX;
    if (newLeft < 0 && newLeft > -35) {
    	//DEBUG output
    	//Element.update(this.yearElements[4], newLeft);
    	this.yearElements.each(function(item) {
            item.setStyle({
            left: newLeft + "%"
          });
        });
    }
    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  },
  between: function(val, low, high) {
  	return (val >= low && val < high);
  },
  //directions: function(event) {
  //  var pointer = [Event.pointerX(event), Event.pointerY(event)];
  //  var offsets = Position.cumulativeOffset(this.yearElements[1]);
	//var cursor = '';
	//if (this.between((offsets[0] + this.yearElements[1].offsetWidth) - pointer[0], 0, this.options.right)) cursor += 'e';

	//return cursor;
  //},
  cursor: function(event) {
	this.scaleElement.style.cursor = 'e-resize';
  },
  update: function(event) {
   if(this.active) {
      if(!this.moving) {
        var style = this.scaleElement.style;
        this.moving = true;

        if(Element.getStyle(this.scaleElement,'position')=='')
          style.position = "relative";
      }
      this.draw(event);

      // fix AppleWebKit rendering
      if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
      Event.stop(event);
      return false;
   }
  }
}
/* fix to get value in precen instead of px */
function getPercentofViewPort(value, force) {
	if (value.toString().indexOf("%") != -1) return parseInt(value);
	value = parseInt(value);

	if (Prototype.Browser.IE && force != true) return value;
	var viewPortWidth = 0;
    if (Prototype.Browser.Opera) {
    	viewPortWidth = document.body.clientWidth;
    }
    if (typeof window.innerWidth != 'undefined')
    {
      viewPortWidth =  window.innerWidth;
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
    {
      viewPortWidth =  document.documentElement.clientWidth;
    }
    // older versions of IE
    else
    {
      viewPortWidth =  document.getElementsByTagName('body')[0].clientWidth;
    }
    return value / (viewPortWidth / 100);
}

