/**
 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.3
 * @dependencies prototype.js 1.5.1+, effects.js
 */

/*
 * Thanks to Andrew Dupont for refactoring help and code cleanup -
 * http://andrewdupont.net/
 */

Glider = Class.create();
Object.extend(Object.extend(Glider.prototype, Abstract.prototype), {
  initialize            : function(wrapper, options, start, limit, url, ivwCode, pageName) {
    this.url = url; // *
    this.scrolling = false;
    this.wrapper = $(wrapper);
    this.scroller = this.wrapper.down('div.scroller');
    this.sections = this.wrapper.getElementsBySelector('div.section');
    this.options = Object.extend({
          duration  : 1.0,
          frequency : 3
        }, options || {});
    /* this.dayWeek = 0; */
    this.optionsCopy = options;
    this.elementId = wrapper;
    this.start = start;
    this.limit = limit;
    this.startCopy = start;
    this.limitCopy = limit;
    this.initialElements = limit;
    this.cityPanelUrl = null;
    this.ivwCode  = ivwCode;
    this.pageName = pageName;
    
    this.sections.each(function(section, index) {
          section._index = index;
        });
    
    this.events = {
      click : this.click.bind(this)
    };
    
    this.addObservers();
    if (this.options.initialSection) this.moveTo(this.options.initialSection,
        this.scroller, {
          duration : this.options.duration
        }
    ); // initialSection should be the id of the section you want to show up on
        // load
    if (this.options.autoGlide) this.start();
    this.reset(); // *
  },
  
  addObservers          : function() {
    var controls = this.wrapper.getElementsBySelector('div.controls a');
    controls.invoke('observe', 'click', this.events.click);
  },
  
  setUrl                : function(url) {
    this.url = url;
  },
  
  setCityPanelUrl       : function(url) {
    this.cityPanelUrl = url;
  },
  
  replaceUrlParameter   : function(param, value) {
    if (this.url) {
      if (this.url.indexOf(param) > -1) {
        var parts = this.url.split('?');
        var regExp = new RegExp('(' + param + '=).*?(&|$)(.*)', 'g');
        /* regExp.compile('('+param+'=).*?(&|$)(.*)','g'); */
        this.url = parts[0] + '?'
            + parts[1].replace(regExp, "$1" + value + "$2$3");
      } else {
        if (this.url.indexOf('?')) {
          this.url += '&' + param + '=' + value;
        } else {
          this.url += '?' + param + '=' + value;
        }
      }
    }
  },
  
  reset                 : function(newOrder, head) {
    this.options.initialSection = 1;
    if (newOrder) {
      this.replaceUrlParameter('orderby', newOrder);
    }
    
    this.replaceUrlParameter('start', 0);
    this.replaceUrlParameter('limit', this.initialElements);
    
    /* this.replaceUrlParameter('day', this.dayWeek); */
    this.limit = this.limitCopy;
    this.start = this.startCopy;
    /* this.dayWeek = this.dayWeekCopy; */
    $(this.elementId + 'Content').style.left = '0px';
    $(this.elementId + 'Content').innerHTML = this.retrieveElements();
    $(this.elementId + 'Content').innerHTML = $(this.elementId + 'Content').innerHTML
        .replace(/_counted/g, "test");
    $(this.elementId + 'Content').innerHTML = $(this.elementId + 'Content').innerHTML
        .replace(/_index/g, "test");
    
    this.scroller = this.wrapper.down('div.scroller');
    this.sections = this.wrapper.getElementsBySelector('div.section');
    this.sections.each(function(section, index) {
          section._index = index;
        });
    
    if (this.options.initialSection) this.moveTo(this.options.initialSection,
        this.scroller, {
          duration : this.options.duration
        }
    ); // initialSection should be the id of the section you want to show up on
        // load
    /*
     * $(this.elementId+'Left').className='first reiter-passiv';
     * $(this.elementId+'Middle').className='reiter-passiv';
     * if($(this.elementId+'Fourth')){
     * $(this.elementId+'Right').className='reiter-passiv';
     * $(this.elementId+'Fourth').className='last reiter-passiv'; } else {
     * $(this.elementId+'Right').className='last reiter-passiv'; }
     * $(head).className=$(head).className + ' reiter-aktiv';
     */
  },
  
  retrieveElements      : function() {
    if (this.url) {
      var transporter = getTransporter();
      transporter.open("GET", this.url, false); // Synchron = false, Asynchron =
                                                // true
      transporter.send(null);
      return transporter.responseText ? transporter.responseText : false;
    } else {
      return false;
    }
  },
  
  retrieveCityPanelData : function(cityPanelUrl) {
    if (cityPanelUrl) {
      
      xmlHttp = getTransporter();
      if (xmlHttp == null) {
        alert("Browser does not support HTTP Request");
        return false;
      }
      
      xmlHttp.onreadystatechange = stateChanged;
      xmlHttp.open("GET", cityPanelUrl, false);
      xmlHttp.send(null);
      
      return xmlHttp.responseText;
      
    } else {
      return false;
    }
    
  },
  
  refreshCityPanel      : function(kgs, dayZone, dayWeek, reference) {
    var dataArray = new Array();
    var cityPanelData = new Array();
    
    cityPanelData = this.retrieveCityPanelData(this.cityPanelUrl + "?kgs="
        + kgs + "&day_zone=" + dayZone + "&day_week=" + dayWeek);
    dataArray = cityPanelData.split("#");
    
    $('wind_kmh_txt').innerHTML = dataArray[0];
    $('wind_direction_txt').innerHTML = dataArray[1];
    $('rainfall_perc_txt').innerHTML = dataArray[2];
    $('humidness_txt').innerHTML = dataArray[3];
    $('baro_pressure_txt').innerHTML = dataArray[4];
    $('sun_txt_up').innerHTML = dataArray[5];
    $('sun_txt_down').innerHTML = dataArray[6];
    $('moonphase_icon').src = dataArray[7];
    $('sun_duration_txt').innerHTML = dataArray[8];
    $('uv_value_txt').innerHTML = dataArray[9];
    $('ozon_txt').innerHTML = dataArray[10];
    $('gef_temp_txt').innerHTML = dataArray[11];
    $('wind_kmh_icon').src = dataArray[12];
    $('rainfall_perc_icon').src = dataArray[13];
    $('humidness_icon').src = dataArray[14];
    $('baro_pressure_icon').src = dataArray[15];
    $('uv_value_icon').src = dataArray[16];
    $('filename_icon').src = dataArray[17];
    $('weather_info').style.backgroundImage = dataArray[18];
    $('temp_time_of_day_txt').innerHTML = dataArray[19];
    $('unwetter_img').style.visibility = dataArray[20];
    $('wetter_txt_titel').innerHTML = dataArray[21];
    if ($('unwetter_img').style.visibility == "visible") {
      $('unwetter_icon').src = dataArray[22];
    }
    
    /* Maximale Anzahl der Elemente(Tagesabschnitte) die iteriert werden sollen */
    var max_count = 40;
    
    for (i = 0; i < max_count; i++) {
      if ($('desc_temp_txt' + i) == null) {
        break;
      }
      $('desc_temp_txt' + i).style.backgroundColor = "#5D93C9";
    }
    
    $(reference).style.backgroundColor = "#FC7E04";
    
    MTC.reloadTracking(this.ivwCode, this.pageName);
  },
  
  click                 : function(event) {
    this.stop();
    var element = Event.findElement(event, 'a');
    if (this.scrolling) this.scrolling.cancel();
    
    this.moveTo(element.href.split("#")[1], this.scroller, {
          duration : this.options.duration
        });
    Event.stop(event);
  },
  
  moveTo                : function(element, container, options) {
    if ($(element) != null) {
      this.current = $(element);
      Position.prepare();
      var containerOffset = Position.cumulativeOffset(container), elementOffset = Position
          .cumulativeOffset($(element));
      
      this.scrolling = new Effect.SmoothScroll(container, {
            duration : options.duration,
            x        : (elementOffset[0] - containerOffset[0]),
            y        : (elementOffset[1] - containerOffset[1])
          });
      return false;
    }
  },
  
  getNextElements       : function() {
    this.replaceUrlParameter('start', this.start + this.limit);
    this.replaceUrlParameter('limit', this.limitCopy);
    /*
     * if(this.dayWeek == 6) {
     *  } else { this.dayWeek++; }
     */
    /* this.replaceUrlParameter('day', this.dayWeek+1); */
    var elements;
    if (elements = this.retrieveElements()) {
      this.limit = this.limit + this.limitCopy;
    }
    return elements;
  },
  
  next                  : function() {
    var elements;
    if (elements = this.getNextElements()) {
      $(this.elementId + 'Content').innerHTML += elements;
      $(this.elementId + 'Content').innerHTML = $(this.elementId + 'Content').innerHTML
          .replace(/_counted/g, "test");
      $(this.elementId + 'Content').innerHTML = $(this.elementId + 'Content').innerHTML
          .replace(/_index/g, "test");
    }
    
    this.scroller = this.wrapper.down('div.scroller');
    this.sections = this.wrapper.getElementsBySelector('div.section');
    this.sections.each(function(section, index) {
          section._index = index;
        });
    
    this.events = {
      click : this.click.bind(this)
    };
    
    this.addObservers();
    // if(this.options.initialSection) this.moveTo(this.options.initialSection,
    // this.scroller, { duration:this.options.duration }); // initialSection
    // should be the id of the section you want to show up on load
    // if(this.options.autoGlide) this.start();
    if (this.current) {
      if (this.current._index) {
        var currentIndex = this.current._index;
        var nextIndex = (this.sections.length - 1 == currentIndex)
            ? 0
            : currentIndex + 1;
      } else var nextIndex = 1;
    } else var nextIndex = 1;
    
    this.moveTo(this.sections[nextIndex], this.scroller, {
          duration : this.options.duration
        });
    
    MTC.reloadTracking(this.ivwCode, this.pageName);
  },
  
  previous              : function() {
    if (this.current) {
      var currentIndex = this.current._index;
      var prevIndex = (currentIndex == 0)
          ? this.sections.length - 1
          : currentIndex - 1;
    } else var prevIndex = this.sections.length - 1;
    
    this.moveTo(this.sections[prevIndex], this.scroller, {
          duration : this.options.duration
        });
    
    MTC.reloadTracking(this.ivwCode, this.pageName);
  },
  
  stop                  : function() {
    clearTimeout(this.timer);
  },
  
  start                 : function() {
    this.periodicallyUpdate();
  },
  
  periodicallyUpdate    : function() {
    if (this.timer != null) {
      clearTimeout(this.timer);
      this.next();
    }
    this.timer = setTimeout(this.periodicallyUpdate.bind(this),
        this.options.frequency * 1000
    );
  }
  
}
);

Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype,
        Effect.Base.prototype
    ), {
      initialize : function(element) {
        this.element = $(element);
        var options = Object.extend({
              x    : 0,
              y    : 0,
              mode : 'absolute'
            }, arguments[1] || {});
        this.start(options);
      },
      setup      : function() {
        if (this.options.continuous && !this.element._ext) {
          this.element.cleanWhitespace();
          this.element._ext = true;
          this.element.appendChild(this.element.firstChild);
        }
        
        this.originalLeft = this.element.scrollLeft;
        this.originalTop = this.element.scrollTop;
        
        if (this.options.mode == 'absolute') {
          this.options.x -= this.originalLeft;
          this.options.y -= this.originalTop;
        }
      },
      update     : function(position) {
        this.element.scrollLeft = this.options.x * position + this.originalLeft;
        this.element.scrollTop = this.options.y * position + this.originalTop;
      }
    }
);
