/*
 * m8 application server
 * js engine for website salitos.com
 * Copyright(c) 2006-2009, markt8, ms@markt8.de, Michael Schreckenberg
 */


Ext.ns('Salitos');

// carousel
Salitos.Carousel = Ext.extend(Ext.ux.Carousel, {
  
  isAvailable: function() {
    return (this.carouselSize > 0) ? true : false; 
  },
  
  containsSlider: function(str) {
    if(str.match(/slider\-content/)) {
      return true;
    }
    return false;
  },
  
  getTextHeight: function() {
    var table = Ext.get(this.slides[this.activeSlide].select('table').elements[0]);
    var h  = (table.getHeight() + 34);
    return h;
  },
  
  slideNext: function() {
    if((this.activeSlide+1) >= this.carouselSize) {
      return;
    }
    this.next();
  },
  
  slideBack: function() {
    if(this.activeSlide <= 0) {
      return;
    }
    this.prev();
  },
  
  updateNav: function() {
    Ext.get('slide-back').removeClass('disabled');
    Ext.get('slide-next').removeClass('disabled');
    if(this.activeSlide <= 0) {
      Ext.get('slide-back').addClass('disabled');
    }
    if ((this.activeSlide + 1) >= this.carouselSize) {
      Ext.get('slide-next').addClass('disabled');
    }
  }
  
});


// salitos tv
Salitos.TV = Ext.extend(Ext.util.Observable, {
    
  movies: [],
  first: 1,
  max: 5,
  width: 135,
    
  // constructor
  init: function() {
    this.first  = 1;
    this.movies = [];
    // init filmrole
    this.initFilmrole();
    // init slider
    this.initSlider();
    // init buttons
    this.initButtons();
    this.updateButtons();
  },
  
  // init slider
  initSlider: function() {
    this.count = this.movies.length;
    this.sliderWrap = Ext.get('salitos-tv-filmrole');
    this.slider = Ext.get('salitos-tv-filmrole-slider');
    this.slider.setWidth(this.count*this.width);
  },
  
  // init buttons
  initButtons: function() {
    this.back = Ext.get('salitos-tv-slide-back');
    this.next = Ext.get('salitos-tv-slide-next');
  },
  
  // update buttons
  updateButtons: function() {
    this.next.hide();
    this.back.hide();
    if(this.count >= (this.first+this.max)) {
      this.next.show();
    }
    if(this.first > 1) {
      this.back.show();
    }
  },
  
  slideNext: function() {
    this.slider.setLeft(this.slider.getLeft(true) - this.width);
    this.first++;
    this.updateButtons();
  },
  
  slideBack: function() {
    this.slider.setLeft(this.slider.getLeft(true) + this.width);
    this.first--;
    this.updateButtons();
  },
  
  // init filmrole
  initFilmrole: function() {
    // update filmrole navigation
    Ext.select('#salitos-tv-filmrole a.video').each(function(el) {
      this.movies.push(el);
      el.on('click', function(e, t) {
        e.preventDefault();
        var url = Ext.get(t).parent().getAttribute('rel');
        if (url.match(/youtube/)) {
          this.loadYoutube(url);
        } else {
          this.loadVideo(url);
        } 
      }, this);
      el.on('mouseenter', function(e, t) {
        e.preventDefault();
        e.stopEvent();
        var el = (Ext.get(t).dom.tagName == "IMG") ? Ext.get(t).parent() : Ext.get(t);
        var x = el.getLeft();
        var y = el.getTop();
        var w = el.getWidth();
        var i = el.down('div').dom.innerHTML;
        var c = i.split("||");
        var s = String.format('<h1>{0}</h1><h2>{1}</h2>{2}', c[0], c[1], c[2]);
        Ext.get('salitos-tv-quicktip').down('div').update(s);
        Ext.get('salitos-tv-quicktip').setLocation(x, y-150);
        Ext.get('salitos-tv-quicktip').fadeIn({duration: .1});
      });
      el.on('mouseleave', function(e, t) {
        e.stopEvent();
        Ext.get('salitos-tv-quicktip').hide();
      });
    }, this);    
  },
  
  // load video
  loadVideo: function(file) {
    var flashvars = {
      file: file,
      autostart: false,
      //skin: 'media/player/playcasso/playcasso.swf',
      backcolor: '000000',
      frontcolor: 'ffffff',
      stretching: 'uniform',
      controlbar: 'over'
    };
    var params = {
      allowscriptaccess: 'always',
      allowfullscreen: true
    };
    var attributes = {};
    swfobject.embedSWF("media/player/player.swf", "salitos-tv-screen", "274", "170", "9.0.28", "media/swfobject/expressinstall.swf", flashvars, params, attributes);
    this.play.defer(500);
  },
  
  // load video
  loadYoutube: function(file) {
    var flashvars = {
      file: file, //'http://www.youtube.com/watch?v=iBGdr3wbfqk',
      autostart: false,
      //skin: 'media/player/playcasso/playcasso.swf',
      backcolor: '000000',
      frontcolor: 'ffffff',
      stretching: 'uniform',
      controlbar: 'over',
      'plugins': 'hd-2',
      'provider': 'youtube'
      //'hd.file': file+'&hd=1'
    };
    var params = {
      'allowfullscreen':   'true',
      'allowscriptaccess': 'always'
    };
    var attributes = {};
    swfobject.embedSWF("media/player/player.swf", "salitos-tv-screen", "274", "170", "9.0.28", "media/swfobject/expressinstall.swf", flashvars, params, attributes);
    this.play.defer(500);
    /*
    var params = {
      allowscriptaccess: 'always',
      allowfullscreen: true
    };
    var attributes = {};
    swfobject.embedSWF(file, "salitos-tv-screen", "214", "159", "9.0.28", "media/swfobject/expressinstall.swf", flashvars, params, attributes);
    */
  },
  
  play: function() {
    this.player = document.getElementById("salitos-tv-screen");
    if(this.player) {
      music.pause();
      this.player.sendEvent("PLAY", 'true');
    }
  },
  
  pause: function() {
    this.player = document.getElementById("salitos-tv-screen");
    if(this.player) {
      music.play();
      this.player.sendEvent("PLAY", 'false');
    }
  },
  
  fullscreen: function() {
    this.player = document.getElementById("salitos-tv-screen");
    if(this.player) {
      this.player.sendEvent("FULLSCREEN", 'true');
    }
  }
    
});


// salitos music player
Salitos.Music = Ext.extend(Ext.util.Observable, {
    
  movies: [],
  first: 1,
  max: 5,
  width: 135,
  el: '',
  orgPlst: false,
  curPlst: false,
  
  // constructor
  constructor: function(elId, config) {
    config = config || {};
    Ext.apply(this, config);
    //Ext.ux.Carousel.superclass.constructor.call(this, config);
    this.el = Ext.get(elId);
    // init player
    this.initPlayer();
  },
    
  // load player
  initPlayer: function() {
    // no cache
    var d = new Date();
    // flash
    var flashvars = {
      file: 'data/audio/playlist.xml?'+d.getTime(),
      autostart: true,
      repeat: 'single',
      backcolor: 'ffffff',
      stretching: 'uniform',
      controlbar: 'bottom'
    };
    var params = {
      allowscriptaccess: 'always'
    };
    var attributes = {
    };
    swfobject.embedSWF("media/player/player.swf", this.el.dom.id, "200", "20", "9.0.0", "media/swfobject/expressinstall.swf", flashvars, params, attributes);
  },
  
  // load player
  initControls: function() {
    this.player = document.getElementById(this.el.dom.id);
    // playlist
    this.getPlaylistData.defer(500, this);
    this.syncControls(this);
  },
  
  
  start: function(e) {
    if(this.checkPlayer()) {
      if (this.curPlaylist != this.orgPlaylist) {
        this.load(this.orgPlaylist);
      } else {
        this.player.sendEvent("PLAY");
      }
      this.syncControls(this);
    }      
  },
  
  item: function(i) {
    if(this.checkPlayer()) {
      this.player.sendEvent("ITEM", i);
      this.syncControls(this);
    }      
  },
  
  stop: function(e) {
    if(this.checkPlayer()) {
      this.player.sendEvent("STOP");
      this.syncControls(this);
    }      
  },
  
  next: function(e) {
    if(this.checkPlayer()) {
      this.player.sendEvent("NEXT");
      this.syncControls(this);
    }      
  },
  
  prev: function(e) {
    if(this.checkPlayer()) {
      this.player.sendEvent("PREV");
      this.syncControls(this);
    }      
  },
  
  mute: function(e) {
    if(this.checkPlayer()) {
      this.player.sendEvent("MUTE");
      this.syncControls(this);
    }      
  },
  
  play: function() {
    if(this.checkPlayer()) {
      this.player.sendEvent("PLAY", 'true');
    }
  },
  
  pause: function() {
    if(this.checkPlayer()) {
      this.player.sendEvent("PLAY", 'false');
    }
  },
  
  load: function(pl, el) {
    if(el) {
      Ext.select('a.audio').each(function(el) {
        el.removeClass('audio-active');
      });
      if (this.curPlst && this.curPlst == pl) {
        Ext.get(el).removeClass('audio-active');
      } else {
        Ext.get(el).addClass('audio-active');
      }
    }
    if(this.checkPlayer()) {
      if(!pl && (!this.curPlst || this.curPlst == this.orgPlst)) {
        return;
      } else if(!pl) {
        pl = this.orgPlst;
      } else if(this.curPlst && this.curPlst == pl) {
        pl = this.orgPlst
      }
      this.curPlst = pl;
      this.player.sendEvent("LOAD", pl);
      this.syncControls(this);
    }
  },
  
  checkPlayer: function() {
    if(!this.player) {
      alert('Es wurde kein Musikplayer gefunden:-(');
      return false;
    }
    return true;
  },
  
  getPlaylistData: function() {
    var plst = null;
    if (this.checkPlayer()) {
      plst = this.player.getPlaylist();
      if (!this.orgPlst) 
        this.orgPlst = plst;
      if (plst) {
        var txt = '';
        for (var itm in plst) {
          if (itm.length == 1) {
            var track = plst[itm];
            var itm = (itm * 1 + 1);
            //console.log(track);
            cls = (itm == this.player.getConfig().item + 1) ? 'plst-item-active' : 'plst-item';
            txt += '<a title="' + track.title + '" class="' + cls + '" href="javascript:void(0)" onclick="music.item(' + (itm - 1) + ')">' + itm + '</a>';
          }
        }
        var tmp = Ext.get('salitos-music-plst');
        if (tmp) {
          tmp.update(txt);
        }
      }
    }
  },
  
  syncControls: function(obj) {
    if(obj.player.getConfig().mute != true) {
      Ext.get('salitos-music-control-mute').removeClass('mute_on');
    } else {
      Ext.get('salitos-music-control-mute').addClass('mute_on');
    }
    obj.getPlaylistData();
  }
    
});


// shop
Salitos.Shop = Ext.extend(Ext.util.Observable, {
    
  // constructor
  constructor: function(config) {
    config = config || {};
    Ext.apply(this, config);
    this.basketInfo();
  },
  
  // add 2 basket
  addItem: function(form) {
    Ext.Ajax.request({
      url: 'shop/card/add-item',
      success: function(response, opts) {
        var res = Ext.decode(response.responseText);
        var div = Ext.get(form).child('div.shop-validation-error');
        if(res.success) {
          div.update('<br />');
          this.basketInfo();
        } else {
          div.update('<span style="font-weight:bold; color:#A42616">'+res.msg+'</span>');
        }
      },
      failure: function() {
        alert('Es ist ein Fehler aufgetreten!');
      },
      params: Ext.Ajax.serializeForm(form),
      scripts: true,
      scope: this
    });
  },
  
  // add 2 basket
  updateItem: function(id) {
    var v = Ext.get('count-'+id).dom.value;
    Ext.Ajax.request({
      url: 'shop/card/update-item',
      success: function(response, opts) {
        board.load('shop/card?step=1');
      },
      failure: function() {
        alert('Es ist ein Fehler aufgetreten!');
      },
      params: {id: id, count: v},
      scripts: true,
      scope: this
    });
  },
  
  // remove
  removeItem: function(id) {
    Ext.Ajax.request({
      url: 'shop/card/remove-item',
      success: function(response, opts) {
        board.load('shop/card');
      },
      failure: function() {
        alert('Es ist ein Fehler aufgetreten!');
      },
      params: {id: id},
      scripts: true,
      scope: this
    });
  },
  
  // remove
  card: function(step, f) {
    if (f) {
      board.load('shop/card?step=' + step, false, false, false, f);
    } else {
      board.load('shop/card?step=' + step);
    }
  },
  
  // order
  order: function(locale) {
    if(!Ext.get('accept-agb').dom.checked) {
      var msg = (locale=="en") 
        ? '<span style="font-weight:bold; color:#A42616">Please confirm that you have read and accepted the General Terms and Conditions in order to complete your order process!</span>'
        : '<span style="font-weight:bold; color:#A42616">Du musst die AGBs akzeptieren, um Deine Bestellung abzuschließen!</span>';
      Ext.get('accept-error').update(msg);
      return;
    }
    Ext.Ajax.request({
      url: 'shop/card/order',
      success: function(response, opts) {
        board.load('shop/card?step=5');
      },
      failure: function() {
        alert('Es ist ein Fehler aufgetreten!');
      },
      scripts: true,
      scope: this
    });
  },
  
  // add 2 basket
  basketInfo: function() {
    var info = Ext.get('shop-basket-info');
    if(!info) {
      return false;
    }
    Ext.Ajax.request({
      url: 'shop/card/basket-info',
      success: function(response, opts) {
        //console.log(response.responseText);
        info.update(response.responseText);
      },
      scripts: true,
      scope: this
    });
    return false;
  }
    
});


// island
Salitos.Island = Ext.extend(Ext.util.Observable, {
    
  // constructor
  constructor: function(elId, config) {
    config = config || {};
    Ext.apply(this, config);
    Ext.ux.Carousel.superclass.constructor.call(this, config);
    this.el = Ext.get(elId);
    this.initEvents();
  },
  
  initNavigation: function() {
    // update footer navigation
    Ext.select('#island-navigation li.item a').each(function(el) {
      el.on('click', function(e, t) {
        e.preventDefault();
        //var url = e.getAttribute('href');
        var url = Ext.get(t).getAttribute('href');
        this.board.load(url, e.getPageX(), e.getPageY()); 
      }, this);
    }, this);
  },
  
  // init events
  initEvents: function() {
    // resize
    this.on('resize', function() {
      this.resize();
    }, this, {delay: 10});
  },
  
  // ready
  ready: function() {
    Ext.get('island-flash').removeClass('hidden');
  },
  
  // specials
  toggleSpecials: function() {
    var el = Ext.get('specials-content');
    if (el.isVisible()) {
      el.slideOut('t', {
        easing: 'easeIn',
        duration: .3
      });
    }
    else {
      el.slideIn('t', {
        easing: 'bounceOut',
        duration: 1
      });
    }
  },
  
  // specials
  loadSpecials: function(url) {
    board.load(url);
    return;
    var el = Ext.get('specials-content');
    el.slideOut('t', {
      easing: 'easeIn',
      duration: .5,
      callback: function() {
        board.load(url);
      }
    });
  },
  
  // resize
  resize: function() {
    return;
    var left = (Ext.getBody().getWidth() - this.el.getWidth()) / 2;
    var top  = (Ext.getBody().getHeight() > this.el.getHeight()+20) ? (Ext.getBody().getHeight() - this.el.getHeight()) / 2 : 20;
    this.el.setLocation(left,top);
    var height = (Ext.getBody().getHeight() / 2)+15;
    Ext.get('horizon').setHeight((height < this.el.getHeight()/2+20) ? (this.el.getHeight()/2+35) : height);
  }
    
});


// board
Salitos.Board = Ext.extend(Ext.util.Observable, {
      
  isShown: false,
  hideFlash: true,
  disableSlider: false,

  // constructor
  constructor: function(elId, config) {
    
    config = config || {};
    
    Ext.apply(this, config);

    Salitos.Board.superclass.constructor.call(this, config);

    this.addEvents(
      'beforeshow',
      'prev',
      'beforenext',
      'next',
      'change',
      'play',
      'pause',
      'show',
      'resize'
    );
    
    this.url = document.location.href;
    
    // set elements
    this.el = Ext.get(elId);
    // init events
    this.initEvents();
    // init slider
    if(!this.disableSlider) this.initCarousel();
    // show directly
    if(this.showOnLoad) {
      this.show();
    }
  },
  
  // init events
  initEvents: function() {
    // beforeshow
    this.on('beforeshow', function(o, fx, fy) {
      this.show(fx, fy);
    }, this, {delay: 100});
    // show
    this.on('show', function() {
      this.showContent();
    }, this, {delay: 200});
    // resize
    this.on('resize', function() {
      this.resize();
    }, this, {delay: 10});
  },
  
  // init carousel
  initCarousel: function() {
    var transitionType = (this.transitionType) ? this.transitionType : 'slide';
    this.carousel = new Salitos.Carousel('slider-content', {
      itemSelector: 'div.article',
      transitionDuration: .8,
      transitionType: (Ext.isIE) ? 'slide' : transitionType,
      transitionEasing: 'easeOutStrong'
    });
    this.carousel.on('change', function() {
      this.adjustSize();
      this.carousel.updateNav();
    }, this);
  },
  
  // init tv
  initTV: function() {
    this.tv = new Salitos.TV();
    this.tv.init();
  },
  
  // init lytebox
  initLytebox: function() {
    initLytebox();
  },
  
  // show
  show: function(fx, fy) {
    // duration
    var duration  = .6;
    // calculate height
    var h = this.getHeight();
    var w = 834;
    // set animate from
    var from = {
      x: fx || 0,
      y: fy || 0,
      w: 0,
      h: 0
    };
    // set animate to
    var to   = {
      x: (Ext.getBody().getWidth() - w) / 2,
      y: ((Ext.getBody().getHeight() - h) / 2 >= 20) ? (Ext.getBody().getHeight() - h) / 2 : 20,
      w: w,
      h: h
    };
    // reset
    this.reset();
    // animate in
    this.hideBeach();
    this.animateIn(from, to, duration);
    this.isShown = true;
  },
  
  // reset
  reset: function() {
    this.el.setLocation(-1000,-1000);
    this.el.setWidth(0);
    this.el.setHeight(0);
    this.el.setStyle({margin:0});
    this.el.show();
    this.el.select('div.center').setHeight(0);
    this.el.select('div#board-content').hide();
    this.el.select('ul#board-navigation').hide();
  },
  
  // resize
  resize: function(e) {
    if(!this.isShown) return false;
    var left = (Ext.getBody().getWidth() - this.el.getWidth()) / 2;
    var top  = (Ext.getBody().getHeight() > this.el.getHeight()+20) ? (Ext.getBody().getHeight() - this.el.getHeight()) / 2 : 20;
    this.el.setLocation(left,top);
  },
  
  // adjustSize
  adjustSize: function(e) {
    var h = this.getHeight();
    this.el.scale(834, h);
    this.el.select('div.center').scale(834, h-210, {callback: function(){
      if(this.el.getTop() < 20) this.resize();
    }, scope: this});
  },
  
  // getHeight
  getHeight: function() {
    //console.log(this.carousel);
    if(this.carousel && this.carousel.isAvailable()) {
      var h = this.carousel.getTextHeight();
    } else {
      try {
        var h = Ext.get(this.el.select('div#board-content div').elements[0]).getHeight() + 34;
      } catch (e) {
        var h = 495;
      }
    }
    return h;
  },
  
  // animate in
  animateIn: function(from, to, d) {
    var obj = this;
    this.el.setLocation(to.x,to.y);
    this.el.setWidth(834);
    this.el.setHeight(to.h);
    this.el.select('div.center').setHeight(to.h-210);
    this.el.select('div.top').setHeight(130);
    this.el.select('div.bottom').setHeight(100);
    this.showContent();
    this.el.show();
    this.el.select('.button-close').focus(200);
  },
  
  // show content
  showContent: function() {
    this.resize();
    this.el.select('div#board-content').show(); //fadeIn({duration: .3});
    this.el.select('ul#board-navigation').show(); //fadeIn({duration: .3});
    //this.resize.defer(200, this);
  },
  
  // hide content
  hideContent: function() {
    this.el.select('div#board-content').hide();
    this.el.select('ul#board-navigation').hide();
    this.el.select('div#board-content').update();
    music.load();
    /*
    this.el.select('div#board-content').fadeOut({duration: .3, callback: function(e) {
      e.update();
    }});
    this.el.select('ul#board-navigation').fadeOut({duration: .3});
    */
  },
  
  // show beach
  showBeach: function() {
    //Ext.get('beach').setVisibilityMode(Ext.Element.DISPLAY);
    if(this.hideFlash) Ext.get('beach').show(); 
  },
  
  // hide beach
  hideBeach: function() {
    //Ext.get('beach').setVisibilityMode(Ext.Element.DISPLAY);
    if(this.hideFlash) Ext.get('beach').hide(); 
  },
  
  // hide
  hide: function(){
    this.isShown = false;
    this.hideContent();
    this.el.hide();
    this.showBeach();
    /*fadeOut({duration: .3, callback: function(){
      this.showBeach();
    }, scope: this});*/
  },
  
  // get layout of requested page
  getLayout: function(str) {
    if(str.match(/shopping\-card/)) {
      return 'card';
    }
    if(str.match(/shop\-basket/)) {
      return 'shop';
    }
    if(str.match(/slider\-content/)) {
      return 'slider';
    }
    if(str.match(/news\-board/)) {
      return 'news';
    }
    if(str.match(/salitos\-tv/)) {
      return 'video';
    }
    return 'raw';
  },
  
  // load: load content per xmlhttprequest
  load: function(url, fx, fy, p, f) {
    if (url) {
      this.url = url;
    }
    Ext.Ajax.request({
      url: this.url,
      success: function(response, opts) {
        // hide content
        if(this.isShown) {
          this.hideContent();
        }
        //console.log(this.carousel);
        if(this.carousel) {
          this.carousel.clear();
        }
        // update
        Ext.get('board-container').update(response.responseText);
        // init
        var layout = this.getLayout(response.responseText);
        if(layout == 'slider') {
          this.initCarousel();
        } else if(layout == 'video') {
          this.initTV();
        } else if(layout == 'card') {
          
        } else if(layout == 'shop') {
          this.initCarousel();
          shop.basketInfo();
        } else {
          
        }
        this.initLytebox.defer(500);
        //this.showContent();
        if(!this.isShown) {
          this.fireEvent('beforeshow', this, fx, fy);
        } else {
          // adjust board size
          this.adjustSize();
          this.fireEvent('show', this);
        }
      },
      failure: function() {
        alert('Es ist ein Fehler aufgetreten!');
      },
      params: (f) ? Ext.Ajax.serializeForm(f) : p,
      scripts: true,
      scope: this
    });
  },
  
  // reload
  reload: function() {
    this.load(this.url);
  },
  
  // show calendar
  showCalendar: function(id) {
    // show shader
    var shader  = Ext.get('shader');
    var height  = this.getWindowHeight();
    shader.setHeight(height).show();
    shader.on('click', this.hideCalendar, this, {
      single: true,
      delay: 100
    });
    // show video
    var calendar = Ext.get('calendar');
    // get code
    Ext.Ajax.request({
      url: 'plugin/salitos/calendar',
      success: function(o, s, r) {
        calendar.update(o.responseText);
        calendar.show();
      },
      failure: function() {
        this.hideCalendar();
        alert('Es ist ein Fehler aufgetreten!');
      },
      params: {id: id},
      scope: this
    });
  },
  
  // hide calendar
  hideCalendar: function() {
    var shader = Ext.get('shader');
    shader.hide();
    var calendar = Ext.get('calendar');
    calendar.update('');
    calendar.hide();
  },
  
  // get window height
  getWindowHeight: function() {  
    var yScroll;
    if (window.innerHeight && window.scrollMaxY) {
      yScroll = window.innerHeight + window.scrollMaxY + 1;
    } else if (document.body.scrollHeight > document.body.offsetHeight){
      yScroll = document.body.scrollHeight;
    } else {
      yScroll = document.getElementsByTagName("html").item(0).offsetHeight;
      yScroll = (yScroll < document.body.offsetHeight) ? document.body.offsetHeight : yScroll;
    }
    return yScroll;
  }
  
});

// analytics
Ext.Ajax.on('requestcomplete', function(conn, response, opts) {
  if(pageTracker) {
    pageTracker._trackPageview(opts.url);
  }
}, this);

