/**
 * @fileOverview A collection of classes and functions for this project.
 * @name Project name
 * @author Tobias Kreß, kress@kupferwerk.com
 * @version 1.0
 */



/**
 * @class Description for this application class
*/
var Brandl = Class.create(KWStandard, {
	/**
	 * @constructor
	 */
	initialize: function() {
	  document.observe('dom:loaded', function(e) {
	    this.initializeForms();
  	  this.initializeVideos();
  	  //this.initSwitchStatements();
      this.html5Check();
	  }.bind(this));

	},
	
	html5Check: function() {
    if (BrowserDetect.version == 2 && BrowserDetect.browser == 'Firefox') {
      template = '<div id="html5invalid"><div>';
      template+= '<p>Diese Seite wird nicht von Ihrem Browser unterstützt. Sie verwenden eine veralteten Browser (Firefox 2) mit Sicherheitsschwachstellen. Wir empfehlen Ihnen Ihren Browser kostenlos zu <a href="http://www.mozilla.com/firefox/">aktualisieren</a>.</p>';
      template+= '<a class="close" href="#"><img src="/images/browsercheck/cancel_16.png" /></a>';
      template+= '</div></div>';
      $('body').insert({'top': template});
      $('html5invalid').down('a.close').observe('click', function(e) {
        Event.stop(e);
        $('html5invalid').remove();
      });
    };
  },
	
	/**
	 * Initializes Ajax-Pagination Functionality for will_paginate Pagination
	 */
	initializeAjaxPagination: function() {
	  Event.addBehavior.reassignAfterAjax = true;
    Event.addBehavior({
      'div.pagination a': Remote.Link
    });
	},
	
	initializeForms: function() {
	  var labels = $$('.hide_label');
    labels.each(function(label){
      label.hide();
      var label_text = label.innerHTML;
      var input = label.next('input.text') || label.next('textarea');
      if(input.value == '') {
        input.value = label_text;
      }
      input.observe('focus', function(e){
        if (input.value == '' || input.value == label_text) {
          input.value = '';
        };
      });
      input.observe('blur', function(e){
        if(input.value == '') {
          input.value = label_text;
        }
      });
    });
	},
	
	/**
	 * Looks up for Lists with toggle_list class and initializes toggling functioanlity
	 */
  initializeToggleList: function(list) {
    list.childElements().each(function(li){
      var show_link = li.down('div.preview a.show_details');
      var hide_link = li.down('div.details a.hide_details');
      
      if (hide_link) {
        hide_link.observe('click', function(e){
          e.stop();
          this.hideListDetail(e.element());
        }.bind(this));
      };
      
      if (show_link) {
        show_link.observe('click', function(e){
          e.stop();
          this.showListDetail(e.element());
        }.bind(this));
      };

    }.bind(this));
  },
  
  showListDetail: function(trigger) {
    var preview = trigger.up('div.preview');
    var details = preview.next('div.details');
    preview.blindUp({
      duration: 0.3,
      afterFinish: function() {
        details.blindDown({
          duration: 0.3
        });
      }
    });
  },
  
  hideListDetail: function(trigger) {
    var details = trigger.up('div.details');
    var preview = details.previous('div.preview');
    details.blindUp({
      duration: 0.3,
      afterFinish: function() {
        preview.blindDown({
          duration: 0.3
        });
      }
    });
  },
	
	/**
	 * Looks for Links with class show_video and initializes Ajax Stuff
	*/
	initializeVideos: function() {
    var links = $$('a.show_video');	  
    links.invoke('observe', 'click', function(e) {
      e.stop();
      link = e.element();
      this.openVideo(link);
    }.bind(this));
    
    // links.each(function(link) {
    //       link.observe('click', function(e) {
    //         
    //       });
    //     });
	},
	
	/*
   * Opens Youtube Video in Overlay
   */
  openVideo: function(trigger) {
    var instance = this;
    var link = trigger.up('a');
    var video_id = link.id.replace(/video_/, '');
    new Ajax.Request('/videos', {
      method: 'get',
      parameters: {
        id: video_id
      },
      onLoading: function(response) {
        instance.startOverlay();
      },
      onSuccess: function(response) {
        instance.openOverlay(response.responseText);
      },
      onFailure: function(response) {
      }
    }); 
  },
  
  /*
   * Shows Overlay with spinner
   */
  startOverlay: function() {
    var overlay = $('overlay');
    var D = document;
    var height = Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
    overlay.setStyle({height: height + 'px'});
    overlay.show();
  },
  
  /*
   * Opens Overlay with given content in params
   */
  openOverlay: function(content, width, height) {
    var overlay = $('overlay');
    var container = $('overlay_content');
    container.update(content);
    
    var viewport_height = document.viewport.getHeight();
    var viewport_width = document.viewport.getWidth();
    if (viewport_height == 0 || viewport_width == 0) {
      viewport_height = document.body.clientHeight;
      viewport_width = document.body.clientWidth;
    };    
    
    
    var top_pos = (document.viewport.getScrollOffsets().top + (viewport_height / 2) - container.getHeight() / 2);
    var left_pos = (viewport_width / 2 - container.getWidth() / 2);
    
    container.setStyle({
  		top: top_pos + 'px',
  		left: left_pos + 'px'
  	});
  	
    overlay.observe('click', function(e){
      if (e.element() == container) {
        this.closeOverlay();
      };
    }.bind(this));
    
  },
  
  /*
   * Close Overlay and removes its content
   */
  closeOverlay: function() {
    $('overlay_content').update('');
    $('overlay').hide();
  },
  
  /**
   * Inits detail toggling for event list
   * 
   * @return false
  */
  initEventList: function() {
    var toggle_links = $$('.toggle_detail');
    var default_text = toggle_links.first().innerHTML;
    toggle_links.each(function(link) {
      link.observe('click', function(e) {
        Event.stop(e);
        toggle_div = link.next('.event_detail');
        if (!link.hasClassName('is_animating')) {
          if (toggle_div.getStyle('display') == 'none') {
            Effect.BlindDown(toggle_div, { 
                                          duration: 0.5, 
                                          beforeStart: function(){
                                            link.addClassName('is_animating');
                                            link.addClassName('opened_detail');
                                          },
                                          afterFinish: function(){
                                            link.update('schließen');
                                            link.removeClassName('is_animating');
                                          }
                                          });
          } else {
            Effect.BlindUp(toggle_div, { 
                                        duration: 0.5, 
                                        beforeStart: function(){
                                          link.addClassName('is_animating');
                                          link.removeClassName('opened_detail');
                                        },
                                        afterFinish: function(){
                                          link.update(default_text);
                                          link.removeClassName('is_animating');
                                        }
                                        });
          }
        };
      });
    });
  },
  
  
  /**
   * Inits news switching
   * 
  */
  initSwitchNews: function() {
    var instance = this;
    $$('.top_article_link').each(function(link) {
      link.observe('click', function(e) {
        Event.stop(e);
        return instance.switchNews(link);
      });
    }).first().addClassName('active');

    
    this.hideTopArticles().first().show();
    new PeriodicalExecuter(function() {
      instance.startSlide();
    }, 30);
            
    return false;
  },
  
  deactivateTopArticleLinks: function(links) {
    return $$('.top_article_link').invoke('removeClassName', 'active');
  },
  
  hideTopArticles: function() {
    return $$('.top_article').invoke('hide');
  },
  
	switchNews: function(trigger) {
	  this.deactivateTopArticleLinks();
	  trigger.addClassName('active');
	  
	  this.hideTopArticles();
	  $(trigger.id.gsub('_link', '')).show();
	  
	  return false;
	},
	
	startSlide: function() {
	  trigger = $$('.top_article_link.active').first().nextSiblings().first();
    if(!trigger)
      trigger = $$('.top_article_link').first();
	  this.switchNews(trigger);
	},
	
	/**
   * Inits statements switching
   * 
  */
  initSwitchStatements: function() {
    var instance = this;
    new PeriodicalExecuter(function() {
      instance.startStatements();
    }, 10);
    return false;
  },
  
  hideStatements: function() {
    return $$('.statement_item').invoke('hide');
  },
  
	switchStatement: function(trigger) {	  
	  this.hideStatements();
	  $(trigger).show();
	  return false;
	},
	
	startStatements: function() {
    // trigger = $$('.top_article_link.active').first().nextSiblings().first();
    var trigger;
    $$('.statement_item').each(function(item) {
      if (item.visible()) {
        trigger = item.nextSiblings().first();
      };
    });
    if(!trigger)
      trigger = $$('.statement_item').first();
    this.switchStatement(trigger);
	}
});

var brandl = new Brandl();