/**
 * default.js
 *
 * Version history (please keep backward compatible):
 * 1.0, 2009-02-26: Cornelius Hansjakob
 *
 * @author Cornelius Hansjakob <cha@massiveart.com>
 * @version 1.0
 */

Default = Class.create({

  initialize: function() {
    this.map = null;
    this.geocoder = null;
    this.marker = null;
    
    this.retValue = false;
    this.language = 'de';
    this.defSearchValue;
    
    this.currMonth;
    this.currYear;    
    this.newMonth;
    this.newYear;    
    this.currEventCalListId = '';
    this.newEventCalListId = '';
    
    this.formInputs = new Array();
  },  

  /**
   * initSearch
   */
  initSearch: function(){
    /**
     * search field
     */
    if($('searchfield')) {
      $('searchfield').setStyle({color: '#666'});

      // focus
      $('searchfield').observe('focus', function(){
        if($('searchfield').value != '' && ($('searchfield').value == this.defSearchValue)){
          $('searchfield').value = '';
          $('searchfield').setStyle({color: '#fff'});
        }
      }.bind(this));

      // blur
      $('searchfield').observe('blur', function(){
        if($('searchfield').value == ''){
          $('searchfield').setStyle({color: '#999'});
          $('searchfield').value = this.defSearchValue;
        }
      }.bind(this));
    }
  },

  /**
   * initGmap
   */
  initGmap: function(){
    if($('eventLocationMap')){
      if(GBrowserIsCompatible()) {
        this.map = new GMap2($('eventLocationMap'));
        var center = new GLatLng(47.22982711058905, 9.897308349609375);
        this.map.setCenter(center, 7);
        this.geocoder = new GClientGeocoder();
      }
    }
  },
  
  /**
   * updateLiveSearch
   */
  updateLiveSearch: function(selectedElement){
    if($('searchfield')){      
      var link = selectedElement.childNodes[0].getAttribute('href');
      if(link != ''){
        return self.location.href = link;  
  	  }
    }
  },
  
  /**
   * search
   */
  search: function(){
    if($('searchfield')){
  	  if(($('searchfield').value != '')){
          $('searchForm').submit();
  	  }
  	} 
  },
  
  /**
   * submitForm
   */
  submitForm: function(formId){
    if($(formId)){      
      /**
       * validation
       */
      this.retValue = true;
       
      this.validateInput('salutation');      
      this.validateInput('sname');
      this.validateInput('phone');
      this.validateInput('mail');
      this.validateInputEmail('mail');
      
      if(this.retValue == true) {        
	    this.addBusyClass('bttnSend');
	    if($('eventThxLoader')) $('eventThxLoader').show();
	    
	    var serializedForm = $(formId).serialize();
	      
	    new Ajax.Request($(formId).readAttribute('action'), {
	      parameters: serializedForm,
	      evalScripts: true,
	      onComplete: function(transport) {         
	        this.removeBusyClass('bttnSend');
	        if($('eventSumContainer')) $('eventSumContainer').hide();
	        if($('eventThxEmail')) $('eventThxEmail').innerHTML = $F('mail');	        
	        if($('eventThxContainer')) {
		      $('eventThxContainer').show();
		      if($('eventThxLoader')) $('eventThxLoader').fade();
		    }
	      }.bind(this)
	    });
	  }else{
	    this.removeBusyClass('bttnSend');        
	  }
    }
  },
  
  /**
   * submitFormGuidedTour
   */
  submitFormGuidedTour: function(formId){
    if($(formId)){      
      /**
       * validation
       */
      this.retValue = true;
//       
//      this.validateInput('salutation');      
//      this.validateInput('sname');
//      this.validateInput('phone');
//      this.validateInput('mail');
//      this.validateInputEmail('mail');
//      
      if(this.retValue == true) {        
	    this.addBusyClass('bttnSend');
	    if($('guideTourThxLoader')) $('guideTourThxLoader').show();
	    
	    var serializedForm = $(formId).serialize();
	      
	    new Ajax.Request($(formId).readAttribute('action'), {
	      parameters: serializedForm,
	      evalScripts: true,
	      onComplete: function(transport) {         
	        this.removeBusyClass('bttnSend');
	        if($('guidedTourSumContainer')) $('guidedTourSumContainer').hide();
	        if($('guidedTourThxEmail')) $('guidedTourThxEmail').innerHTML = $F('mail');	        
	        if($('guidedTourThxContainer')) {
		      $('guidedTourThxContainer').show();
		      if($('guidedTourThxLoader')) $('guidedTourThxLoader').fade();
		    }
	      }.bind(this)
	    });
	  }else{
	    this.removeBusyClass('bttnSend');        
	  }
    }
  },
  
  /**
   * nextStep
   */
  nextStep: function(formId){
    if($(formId)){      
      /**
       * validation
       */
      this.retValue = true;
   
	  this.validateInput('salutation');      
	  this.validateInput('sname');
	  this.validateInput('phone');
	  this.validateInput('mail');
	  this.validateInputEmail('mail');
	  
	  if(this.retValue == true) {
        if($('noticebox')) $('noticebox').hide();
        if($('eventSumLoader')) $('eventSumLoader').show();
        	
        var serializedForm = $(formId).serialize();
  
	    new Ajax.Updater('eventSumContent', $(formId).readAttribute('action')+'/summary', {
	      parameters: serializedForm,
	      evalScripts: true,
	      onComplete: function() {
	    	if($('eventFormContainer')) $('eventFormContainer').hide();
	        if($('eventSumContainer')) {
	          $('eventSumContainer').show();
	          if($('eventSumLoader')) $('eventSumLoader').fade();
	          Effect.ScrollTo('eventSumContainer', { duration: 0.5, offset: -157});	          
	        }
	      }.bind(this)
	    });
	  }else{        
        if($('noticebox')) $('noticebox').show();
      }
    }	  
  },
  
  /**
   * nextStep
   */
  nextStepGuidedTour: function(formId){
    if($(formId)){      
      /**
       * validation
       */
      this.retValue = true;
   
	  this.validateInput('sname');
	  this.validateInput('phone');
	  this.validateInput('mail');
	  this.validateInputEmail('mail');
	  this.validateInput('guidedTourDate');
	  this.validateInputNumber('guidedTourMembers');
	  
	  if(this.retValue == true) {
        if($('noticebox')) $('noticebox').hide();
        if($('guidedTourSumLoader')) $('guidedTourSumLoader').show();
        	
        var serializedForm = $(formId).serialize();
  
	    new Ajax.Updater('guidedTourSumContent', $(formId).readAttribute('action')+'summary', {
	      parameters: serializedForm,
	      evalScripts: true,
	      onComplete: function() {
	    	if($('guidedTourFormContainer')) $('guidedTourFormContainer').hide();
	        if($('guidedTourSumContainer')) {
	          $('guidedTourSumContainer').show();
	          if($('guidedTourSumLoader')) $('guidedTourSumLoader').fade();
	          Effect.ScrollTo('guidedTourSumContainer', { duration: 0.5, offset: -157});	          
	        }
	      }.bind(this)
	    });
	  }else{        
        if($('noticebox')) $('noticebox').show();
      }
    }	  
  },
  
  /**
   * backStep
   */
  backStep: function(){	
	this.addBusyClass('bttnBack');	  
	if($('eventFormLoader')) $('eventFormLoader').show();
	if($('eventSumContainer')) $('eventSumContainer').hide();
    if($('eventSumContent')) $('eventSumContent').innerHTML = '';
    if($('eventFormContainer')) {
      $('eventFormContainer').show();
      if($('eventFormLoader')) $('eventFormLoader').fade();
      Effect.ScrollTo('eventFormContainer', { duration: 0.5, offset: -157});	
    }
    this.removeBusyClass('bttnBack');
  },
  
  /**
   * backStepGuidedTour
   */
  backStepGuidedTour: function(){	
	this.addBusyClass('bttnBack');	  
	if($('guidedTourFormLoader')) $('guidedTourFormLoader').show();
	if($('guidedTourSumContainer')) $('guidedTourSumContainer').hide();
    if($('guidedTourSumContent')) $('guidedTourSumContent').innerHTML = '';
    if($('guidedTourFormContainer')) {
      $('guidedTourFormContainer').show();
      if($('guidedTourFormLoader')) $('guidedTourFormLoader').fade();
      Effect.ScrollTo('guidedTourFormContainer', { duration: 0.5, offset: -157});	
    }
    this.removeBusyClass('bttnBack');
  },
  
  /**
   * listSlideRight
   */
  listSlideRight: function(currElement, newElement){
    if($(newElement)){
      if(parseInt($(newElement).style.left) <= 610 && parseInt($(newElement).style.left) > 0){
        new Effect.Move(newElement, { x: 0, y: 0, mode: 'absolute', duration: 0.6 });
        new Effect.Move(currElement, { x: -610, y: 0, mode: 'absolute', duration: 0.6 });
      }
    }
  },
  
  /**
   * listSlideLeft
   */
  listSlideLeft: function(currElement, newElement){
    if($(newElement)){
      if(parseInt($(newElement).style.left) >= -610 && parseInt($(newElement).style.left) < 0){
        new Effect.Move(newElement, { x: 0, y: 0, mode: 'absolute', duration: 0.6 });
        new Effect.Move(currElement, { x: 610, y: 0, mode: 'absolute', duration: 0.6 });
      }
    }
  },
  
  /**
   * imgGalleryShowAll
   */
  imgGalleryShowAll: function(elementHide){
    if($('divImageGallery')){
      var images = $('divImageGallery').innerHTML;
      $('divImageGallery').remove();
      if($(elementHide)) $(elementHide).hide();
      new Insertion.After($(elementHide), images);
    }
  },
  
  /**
   * login
   */
  login: function(){
    if($('loginForm')){
      /**
       * validation
       */
      this.retValue = true;

      this.validateInput('fname');
      this.validateInput('sname');
      this.validateInput('company');
      this.validateInput('mail');
      this.validateInputEmail('mail');

      if(this.retValue == true) {
   	    if($('noticebox')) $('noticebox').hide();
   	    this.addBusyClass('bttnLogin');

        /**
  	     * serialize form
  	     */
  	    var serializedForm = $('loginForm').serialize();

        new Ajax.Request($('loginForm').readAttribute('action'), {
          parameters: serializedForm,
    		  evalScripts: true,
    		  onComplete: function(transport) {
        	  if(transport.responseText == true || transport.responseText == 'true'){
        	    return window.location.reload();
        	  }
          }.bind(this)
        });
      }else{
        this.removeBusyClass('bttnLogin');
        if($('noticebox')) $('noticebox').show();
      }
    }
  },

  /**
   * download
   */
  download: function(fileId){
    if(typeof(fileId) == 'undefined'){
      return false;
    }

    new Ajax.Request('/zoolu-website/download', {
      parameters: {
        fileId: fileId
      },
      evalScripts: true,
      onComplete: function(transport) {

      }.bind(this)
    });

    return true;
  },

  /**
   * toggleElement
   */
  toggleElement: function(elementId, dblDuration){
    if(typeof(dblDuration) == 'undefined'){
      dblDuration = 0.2;   
    }
    if($(elementId)){
      if($(elementId).style.display == 'none'){
        Effect.SlideDown(elementId, {duration: dblDuration});
      }else{
        Effect.SlideUp(elementId, {duration: dblDuration});
      }
    }
  },
  
  /**
   * togglePastEvents
   */
  togglePastEvents: function(elementId, currEventListId, dblDuration){
    if(typeof(dblDuration) == 'undefined'){
      dblDuration = 0.2;   
    }
    if($(elementId)){
      if($(elementId).style.display == 'none'){
        $(elementId).show();
        if($('linkPastEvents')) $('linkPastEvents').innerHTML = 'ausblenden'; 
      }else{
    	$(elementId).hide();
    	if($('linkPastEvents')) $('linkPastEvents').innerHTML = 'anzeigen';
      }
    }
    if($(currEventListId)){
      this.getCurrEventListHeight(currEventListId);
    }
  },  
  
  /**
   * showAddress
   */
  showAddress: function(address) {
    if(typeof(address) != 'undefined') {
      if (this.geocoder) {
        var myMap = this.map;
        var myMaker = this.marker;
        this.geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              //alert(address + " not found");
            } else {
              myMap.setCenter(point, 14);
              myMaker = new GMarker(point);
              myMap.addOverlay(myMaker);
            }
          }
        );
      }
    }
  },

  /**
   * searchByPeriod
   */
  searchByPeriod: function(fromElementId, toElementId){
    if($(fromElementId) && $F(fromElementId) != ''){
      if($(toElementId) && $F(toElementId) != ''){
      	if($('eventsContainer')){
      	  $('eventsContainer').innerHTML = '';
      	  //this.addBusyClass('eventsContainer');
          new Ajax.Updater('eventsContainer', '/zoolu-website/event/search', {
      		  parameters: {
      	      from: $F(fromElementId),
      	      to: $F(toElementId)
      		  },
      		  asynchronous: false,
      		  evalScripts: true,
      		  onComplete: function() {
      		    //this.removeBusyClass('eventsContainer');
      	      this.getCurrEventListHeight('divEventCalListSearch');
      		  }.bind(this)
          });
      	}
      }
    }
  },

  /**
   * searchByDatePeriod
   */
  searchByDatePeriod: function(from, to){
    if($('eventsContainer')){
      $('eventsContainer').innerHTML = '';
      new Ajax.Updater('eventsContainer', '/zoolu-website/event/search', {
        parameters: {
          from: from,
          to: to
        },
        asynchronous: false,
        evalScripts: true,
        onComplete: function() {
          this.getCurrEventListHeight('divEventCalListSearch');
        }.bind(this)
      });
    }
  },

  /**
   * loadNextEvents
   */
  loadNextEvents: function(){
    if(typeof(this.newMonth) != 'undefined') this.currMonth = this.newMonth;
    if(typeof(this.newYear) != 'undefined') this.currYear = this.newYear;    
    this.currEventCalListId = 'divEventCalList_' + this.currMonth + '_' + this.currYear;
    
    if($(this.currEventCalListId)){
      this.newMonth = parseInt(this.currMonth) + 1;
      this.newYear = parseInt(this.currYear);
      if(this.newMonth > 12){
        this.newMonth = 1;
        this.newYear = this.newYear + 1; 
      }
      this.newEventCalListId = 'divEventCalList_' + this.newMonth + '_' + this.newYear;
      
      // if $(newElementId) exists and isn't empty, don't reload - else ajax update
      if($(this.newEventCalListId) && $(this.newEventCalListId).innerHTML != ''){
        new Ajax.Request('/zoolu-website/event/session', {
          parameters: { 
    	      month: this.newMonth,
            year: this.newYear
          },
          asynchronous: false,
          evalScripts: true,
          onComplete: function(transport) { 
        	this.getCurrEventListHeadline();
            this.listSlideRight(this.currEventCalListId, this.newEventCalListId);
            this.getCurrEventListHeight(this.newEventCalListId);	  
          }.bind(this)
        });
      }else{
        var newElementContainer = '<div id="'+this.newEventCalListId+'" style="position:absolute; z-index:10; top:0; left:610px; width:590px;"></div>';
        new Insertion.After(this.currEventCalListId, newElementContainer);
        
        // ajax load events
        if($(this.newEventCalListId)){
          var newLoader = '<div id="divLoader_' + this.newMonth + '_' + this.newYear + '" style="display:none; position: absolute; top:0; left:0; width:590px; height:100%; background-color:#333;"></div>';
          $(this.newEventCalListId).innerHTML = newLoader; 
          
          this.addBusyClass('divLoader_'+this.currMonth+'_'+this.currYear, true);
          new Ajax.Updater(this.newEventCalListId, '/zoolu-website/event/list', {
	          parameters: { 
        	    month: this.newMonth,
                year: this.newYear
	          },
	          asynchronous: false,
	          insertion: Insertion.Bottom,
	          evalScripts: true,
	          onComplete: function() {         
	            this.removeBusyClass('divLoader_'+this.currMonth+'_'+this.currYear, true);
	            this.getCurrEventListHeadline();
	            this.listSlideRight(this.currEventCalListId, this.newEventCalListId);
	            this.getCurrEventListHeight(this.newEventCalListId);    
	          }.bind(this)
	        });
        }
      }
    }    
  },
  
  /**
   * loadPrevEvents
   */
  loadPrevEvents: function(){    
    if(typeof(this.newMonth) != 'undefined') this.currMonth = this.newMonth;
    if(typeof(this.newYear) != 'undefined') this.currYear = this.newYear;
    this.currEventCalListId = 'divEventCalList_' + this.currMonth + '_' + this.currYear;
     
    if($(this.currEventCalListId)){
      this.newMonth = parseInt(this.currMonth) - 1;
      this.newYear = parseInt(this.currYear);
      if(this.newMonth < 1){
        this.newMonth = 12;
        this.newYear = this.newYear - 1; 
      }
      this.newEventCalListId = 'divEventCalList_' + this.newMonth + '_' + this.newYear;
      
      // if $(newElementId) exists and isn't empty, don't reload - else ajax update
      if($(this.newEventCalListId) && $(this.newEventCalListId).innerHTML != ''){
    	  new Ajax.Request('/zoolu-website/event/session', {
              parameters: { 
        	      month: this.newMonth,
                year: this.newYear
              },
              asynchronous: false,
              evalScripts: true,
              onComplete: function(transport) { 
            	  this.getCurrEventListHeadline();
                  this.listSlideLeft(this.currEventCalListId, this.newEventCalListId);
                  this.getCurrEventListHeight(this.newEventCalListId);	  
              }.bind(this)
          });
    	
      }else{
        var newElementContainer = '<div id="'+this.newEventCalListId+'" style="position:absolute; z-index:10; top:0; left:-610px; width:590px;"></div>';
        new Insertion.Before(this.currEventCalListId, newElementContainer);
        
        // ajax load events
        if($(this.newEventCalListId)){
          var newLoader = '<div id="divLoader_' + this.newMonth + '_' + this.newYear + '" style="display:none; position: absolute; top:0; left:0; width:590px; height:100%; background-color:#333;"></div>';
          $(this.newEventCalListId).innerHTML = newLoader;
          
          this.addBusyClass('divLoader_' + this.currMonth + '_' + this.currYear, true);
          new Ajax.Updater(this.newEventCalListId, '/zoolu-website/event/list', {
            parameters: { 
              month: this.newMonth,
              year: this.newYear
            },
            asynchronous: false,
            insertion: Insertion.Bottom,
            evalScripts: true,
            onComplete: function() {         
              this.removeBusyClass('divLoader_' + this.currMonth + '_' + this.currYear, true);
              this.getCurrEventListHeadline();
              this.listSlideLeft(this.currEventCalListId, this.newEventCalListId);
              this.getCurrEventListHeight(this.newEventCalListId);    
            }.bind(this)
          });
        }
      }
    }
  },
  
  /**
   * getCurrEventListHeight
   */
  getCurrEventListHeight: function(elementId){
    if($(elementId)){
      var newHeight = $(elementId).getHeight(); 
      if($('divEventCalContainer')) $('divEventCalContainer').style.height = newHeight + 'px';
    }
  },
  
  /**
   * getCurrEventListHeadline
   */
  getCurrEventListHeadline: function(){
    if($('divMonthHeadline_' + this.newMonth + '_' + this.newYear)){
      if($('divEventHeaderText')) $('divEventHeaderText').innerHTML = $('divMonthHeadline_' + this.newMonth + '_' + this.newYear).innerHTML;
    }
  },
  
  /**
   * changeTestMode
   */
  changeTestMode: function(status){
    new Ajax.Request('/zoolu-website/testmode/change', {
      parameters: { TestMode: status },
      evalScripts: true,
      onComplete: function(transport) {         
        window.location.href = window.location.href;
      }.bind(this)
    });
  },
  
  /**
   * validateInput
   */
  validateInput: function(element, baseValue) {
    if(($(element) && $F(element).blank()) || $F(element) == baseValue){
      $(element).addClassName('missinginput');
      this.retValue = false;
    }else{
      $(element).removeClassName('missinginput');
    }
  },
  
  /**
   * validateInputEmail
   */
  validateInputEmail: function(element){
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if($(element)){
      if(!filter.test($F(element))){
    	$(element).addClassName('missinginput');
    	this.retValue = false;
      }else{
    	$(element).removeClassName('missinginput');
      }
    }
  },
  
  /**
   * validateInputNumber
   */
  validateInputNumber: function(element){
	var val = $F(element);  
	if ( isNaN( parseFloat(val) ) ) {
	  $(element).addClassName('missinginput');
      this.retValue = false;
	} else if (val != parseInt(val)) {
      $(element).addClassName('missinginput');
	  this.retValue = false;
	} else {
	  $(element).removeClassName('missinginput');
	}
  },
  
  /**
   * inputFormat
   */
  inputFormat: function(inputElement) {
    if(this.formInputs[inputElement.id] == null) {
      this.formInputs[inputElement.id] = inputElement.value;
      inputElement.value=''; 
      inputElement.style.color='#000'; 
    } 
  },
  
  /**
   * addBusyClass
   */
  addBusyClass: function(busyElement, blnDisplay) {
    if($(busyElement)){
      $(busyElement).addClassName('busy');
      if(blnDisplay) $(busyElement).show();
    }
  },

  /**
   * removeBusyClass
   */
  removeBusyClass: function(busyElement, blnDisplay) {
    if($(busyElement)){
      $(busyElement).removeClassName('busy');
      if(blnDisplay) $(busyElement).hide();
    }
  },

  /**
   * emptyInput
   */
  emptyInput: function(input, value){
    if(input.value == value) {
      input.value = '';
    }
  }
  
});
