/***
 * Description: Interface enhancements for BCA
 * Created: 2009-07-28
 * Author: Fabrique.members['DRA'];
 */

/***
 * Load JS-enabled stylesheet
 */
new Asset.css('/media/presentation/js-enabled.css', {id: 'jsEnabledStyle', title: 'jsEnabledStyle'});
 
/***
 * Generic behaviour
 */
function App() {}
App.prototype = {
  init: function() {
    this.setupColumns();
    this.loadCarrousels();
    this.loadShowContainers();
    this.setupDatepickers();
    this.setupSearch();
    this.setupTabArticles();
    this.setupShowvisuals();
    this.setupApplinks();
    //this.setupMaps();
    this.setupLogin();
    this.setupBookingconditions();
    this.setupPricesLayout();
    this.setupMailafriend();
    this.setupAdduser();
  },


  setupColumns: function() {
    var primaryCol = $(document.body).getElement('div.primary-content');
    var secondaryCol = $(document.body).getElement('div.secondary-content');
    if(!primaryCol || !secondaryCol) {
      return false;
    }
  
    var primaryColSize = primaryCol.getSize();
    var secondaryColSize = secondaryCol.getSize();
  
    if(primaryColSize.y > secondaryColSize.y) {
      secondaryCol.setStyle('height', primaryColSize.y);
    }
    else if(secondaryColSize.y > primaryColSize.y) {
      primaryCol.setStyle('height', secondaryColSize.y);
    }
  },
  
  
  loadShowContainers: function() {
    $$('div.showitems-container').each(function(showContainer) {
      var showContainerObj = new ShowsContainer();
      showContainerObj.setup(showContainer);
    });
  },
  
  
  loadCarrousels: function() {
    $$(
      'body.page-home div.tertiary div.carrousel-container',
      'body.page-show #primary div.carrousel-container'
    ).each(function(carrouselEl) {
      var carrousel = new Carrousel();
      carrousel.init(carrouselEl);
    });
    
    $$(
      'body.page-home div.main-carrousel div.carrousel-container',
      'body.page-home-loggedin div.main-carrousel div.carrousel-container').each(function(carrouselEl) {
      var carrousel = new Carrousel();
      carrousel.setItemPerStep(true);
      carrousel.enableAutomaticSpin();
      carrousel.init(carrouselEl);
    });
  },
  
  
  setupDatepickers: function() {
    new DatePicker('#id_startdate', {
	  pickerClass: 'search-datepicker',
	  allowEmpty: true,
	  toggleElements: '.form-search-startdate-toggler',
      days: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
      months: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
      format: 'd-m-Y',
      inputOutputFormat: 'd-m-Y'
	});
	
    new DatePicker('#id_enddate', {
	  pickerClass: 'search-datepicker',
	  allowEmpty: true,
	  toggleElements: '.form-search-enddate-toggler',
      days: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
      months: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
      format: 'd-m-Y',
      inputOutputFormat: 'd-m-Y'
	});
  },
  
  
  setupSearch: function() {
    var searchPeriod = $('id_periods');
	if(!searchPeriod)
	  return false;
	
	function showDatefields() {
	  if(searchPeriod.value == 'other') {
	    $('form-search').addClass('show-dates');	  
	  }
	  else {
	    $('form-search').removeClass('show-dates');
	  }
	}
	searchPeriod.addEvent('change', showDatefields);
	showDatefields();
	/*
	var searchform = $('form-search');
    var startdate = $('id_startdate');
    var enddate = $('id_enddate');
    searchform.addEvent('submit', function() {
      var today = new Date();
      if(startdate.value == '') {
        startdate.value = today.getFullYear() + '-' + today.getMonth() + '-' + today.getDay();
      }
      if(enddate.value == '') {
        enddate.value = (today.getFullYear()+3) + '-' + today.getMonth() + '-' + today.getDay();
      }
    });*/
  },
  
  
  setupTabArticles: function() {
    $$('div.tabs-article').each(function(tabsArticleEl) {
      var tabsArticle = new TabsArticle(tabsArticleEl);
    });
  },
  
  
  setupShowvisuals: function() {
    var mainvisual = $('main-visual');
    if(!mainvisual || !$(document.body).hasClass('page-show')) {
      return false;
    }
      
    $$('body.page-show div#primary div.showitem a').each(function(showitem) {
      if(showitem.hasClass('showvideo')) {
        var youtubeId = showitem.href.split('?v=');
        showitem.href = 'http://www.youtube.com/v/' + youtubeId[1] + '?autoplay=1&keepThis=true&TB_iframe=true&width=560&height=340';
        showitem.addEvent('click', function(e) {
          e.stop();
        });
      }
      else {
        showitem.addEvent('click', function(e) {
          mainvisual.src = this.href;
          e.stop();
        });
      }
    });
  },
  
  
  setupApplinks: function() {
    $$('a.print').each(function(printlink) {
      printlink.addEvent('click', function(e) {
        print();
        e.stop();
      });
    });
    
    
    $$("a").each(function(hyperlink) {
      if(hyperlink.get('rel') == 'external' || hyperlink.get('href').contains('http://')) {
        hyperlink.target = '_blank';
      }
    });
  },
  
  
  setupMaps: function() {
    var mapEl = $('map');
    window['map'] = null;
    if(mapEl) {
      window['map'] = new Maps(mapEl);
    }
  },


  setupLogin: function() {
    $$('a.loginlink').each(function(loginlink) {
      loginlink.addEvent('click', function(e) {
        $('login-container').toggleClass('active');        
        e.stop();
      });
    });
  },

  setupBookingconditions: function() {
    if ($('bookingconditions')){
      // Show full-text on click
      $$('#bookingconditions .singular a').addEvent('click', function(el) {
        $$('#bookingconditions .bookingconditions-intro').addClass('invisible');
        $$('#bookingconditions .bookingconditions-full').addClass('visible');
        this.toggleClass('invisible');
        el.stop();
      });
    }
  },
  
  
  setupPricesLayout: function() {
    if (!$(document.body).hasClass('page-show')) {
      return false;
    }
    
    var normalPrices = $$('div#price-container  div.normal-price li');
    var bcaPrices = $$('div#price-container  div.bca-price li');
    for(var i=0, len=normalPrices.length; i < len; i++) {
      var normalPriceSize = $(normalPrices[i]).getSize();
      var bcaPricesSize = $(bcaPrices[i]).getSize();
  
      if(normalPriceSize.y > bcaPricesSize.y) {
        $(bcaPrices[i]).setStyle('height', (normalPriceSize.y - 3));
      }
      else if(bcaPricesSize.y > normalPriceSize.y) {
        $(normalPrices[i]).setStyle('height', (bcaPricesSize.y - 3));
      }
    }
  },
  
  
  setupMailafriend: function() {
    var hash = document.location.hash;
    var verhaal = $('verhaal');
    if(!hash || !verhaal) {
      return false;
    }
    
    var handle = verhaal.getElement('li.singular-mail-a-friend a');
    hashArr = hash.split('#');
    if(hashArr[1] !== 'tip-een-vriend') {
      return false;
    }
    
    $$("a.smoothbox").each(function(el){
      if(el.hasClass('tip-handle')) {
        TB_show(el.title, el.href, el.rel);
      }
    });
  },
  
  
  setupAdduser: function() {
    if($('add-user')) {
      TB_show('Maak een eigen account aan', '#TB_inline?width=500&height=350&inlineId=add-user', '');
    }
  }
};

 
 
/***
 * Show behaviour
 */
function ShowsContainer() {}
ShowsContainer.prototype = {
  el: null,
  items: [],


  setup: function(el) {
    if(!el)
	  return false;
    
	this.el = el;
	this.items = this.el.getElements('div.showitem');
	this.setupShowitems();
  },
  
  
  setupShowitems: function() {
    var that = this;
    var items = this.items;
    items.each(function(showitem) {
	  //Setup mouseovers
	  showitem.addEvent('mouseenter', function(e) {
	    this.addClass('showitem-hover');
	    if(!Browser.Engine.trident) {
		  that.setShowInSpotlight();
		}
	    e.stop();
	  });
	  showitem.addEvent('mouseleave', function(e) {
	    this.removeClass('showitem-hover');
	    if(!Browser.Engine.trident) {
		  var checkHover = function() {
		    var showitems = that.el.getElements('div.showitem-hover');
		    if(showitems.length == 0) {
		      this.setLightsOn();
		    }
		  };
		  checkHover.delay(50, that);
		}
		e.stop();
	  });
	  
	  showitem.addEvent('click', function(e) {
	    var showitemlink = this.getElement('a');
	    if(showitemlink) {
	      document.location.href = showitemlink.href;
	    }
	    e.stop();
	  });
	});
  },
  
  
  setShowInSpotlight: function() {
	var items = this.items;
    items.each(function(showitem) {
	  var fx = new Fx.Morph(showitem, {duration: 'short', transition: Fx.Transitions.Sine.easeOut});
	  showitem.hasClass('showitem-hover') ?
	    fx.start({'opacity': 1}) :
		fx.start({'opacity': 0.6});
	});
  },
  
  
  setLightsOn: function() {
	var items = this.items;
    items.each(function(showitem) {
	  var fx = new Fx.Morph(showitem, {duration: 'short', transition: Fx.Transitions.Sine.easeOut});
	  fx.start({'opacity': 1});
	});
  }
};

 
 
/***
 * Carrousel behaviour
 */
function Carrousel() {}
Carrousel.prototype = {
  el: null,
  width: 0,
  showsContainer: null,
  totalSteps: 1,
  currentStep: 1,
  items: [],
  enableAutomaticSpin: false,
  itemPerStep: false,
  timer: null,


  init: function(el) {
    this.el = el;
    this.showsContainer = el.getElement('div.carrousel-shows-container');
    this.items = el.getElements('div.showitem');
    var that = this;
    var w = 0;
    this.items.each(function(showitem) {
      w += showitem.getSize().x;
    });

    this.showsContainer.setStyle('width', (w + 1) + 'px');
    
    //var ua = navigator.userAgent;
    //if(ua.indexOf("MSIE 6") == -1) {
      this.width = this.el.getSize().x;
    //}
    
    this.totalSteps = Math.ceil(w / this.width);
    //alert(w + ': ' + this.width);
    
    // Setup handles
    var nextHandle = el.getElement('a.paginator-next');
    nextHandle.addEvent('click', function(e) {
      that.showNext();
      e.stop();
    });
    
    var prevHandle = el.getElement('a.paginator-previous');
    prevHandle.addEvent('click', function(e) {
      that.showPrevious();
      e.stop();
    });
  },


  showPrevious: function() {
    if(this.itemPerStep) {
      this.totalSteps = this.items.length;
    }
    if(this.currentStep == 1) {
      this.currentStep = this.totalSteps;
    }
    else {
      this.currentStep--;
    }
    this.toStep(this.currentStep);
  },


  showNext: function() {
    if(this.itemPerStep) {
      this.totalSteps = this.items.length;
    }
    if(this.currentStep == this.totalSteps) {
      this.currentStep = 1;
    }
    else {
      this.currentStep++;
    }
    this.toStep(this.currentStep);
  },


  toStep: function(stepnr) {
    if(this.itemPerStep) {
      var itemwidth = 602;
      /*
      if($(document.body).hasClass('page-home-loggedin')) {
        itemwidth = 670;
      }
      */
      
      var slideFx = new Fx.Morph(this.showsContainer, {
        'duration': 'long',
        transition: Fx.Transitions.Sine.easeOut
      });
      slideFx.start({
        'margin-left': '-' + ((stepnr - 1) * itemwidth) + 'px'
      });
    }
    else {

      var slideFx = new Fx.Morph(this.showsContainer, {
        transition: Fx.Transitions.Sine.easeOut
      });
      
      if(Browser.Engine.trident) {
        var leftmargin = ((stepnr - 1) * this.width);
        if(leftmargin > 0) {
          leftmargin = '-' + leftmargin;
        }
        leftmargin = leftmargin + 'px';
        slideFx.start({
          'margin-left': leftmargin
        });
      }
      else {
        slideFx.start({
          'margin-left': '-' + ((stepnr - 1) * this.width) + 'px'
        });
      }
    }
  },
  
  
  enableAutomaticSpin: function() {
    this.automaticSpin = true;
    this.timer = this.showNext.periodical(5000, this);
  },
  
  
  disableAutomaticSpin: function() {
    this.automaticSpin = false;
    $clear(this.timer);
  },
  
  
  setItemPerStep: function(spin) {
    this.itemPerStep = spin;
    this.totalSteps = this.items.length;
    //console.log('total: ' + this.totalSteps);
  }
};



 
 
/***
 * TabsArticle behaviour
 */
function TabsArticle(el) {
  this.setup(el);
}
TabsArticle.prototype = {
  el: null,
  headers: [],
  contentblocks: [],


  setup: function(el) {
    this.el = el;
    this.headers = this.el.getElements('ul.tab-headers li');
    this.contentblocks = this.el.getElements('div.tab-content-container div.tab');
    var that = this;
    this.headers.each(function(tabheader) {
      tabheader.addEvent('click', function(e) {
        that.openItem(this);
        e.stop();
      });
    });
    
    if(this.headers.length < 1) {
      return false;
    }
    
    var hashStr = document.location.hash;
    if(hashStr) {
      var currentTab = null;
      this.headers.each(function(tabheader) {
        var tabheaderAnchor = tabheader.getElement('a');
        if(!tabheaderAnchor) {
          return;
        }
        var tabheaderAnchorHash = tabheaderAnchor.href.substr(tabheaderAnchor.href.indexOf('#'), tabheaderAnchor.href.length);
        if(hashStr == tabheaderAnchorHash) {
          currentTab = tabheader;
        }
      });
      
      if(!currentTab) {
        // Open first at startup
        this.openItem(this.headers[0]);      
      }
      else {
        this.openItem(currentTab);
      }
    }
    else {
      // Open first at startup
      this.openItem(this.headers[0]);
    }    
  },


  openItem: function(el) {
    var tabAnchor = el.getElement('a');
    if(!tabAnchor)
      return false;

    arrayHref = tabAnchor.getAttribute('href').split('#');
    var tabId = arrayHref[1];
    this.headers.each(function(tabheader) {
      if(el == tabheader) {
        tabheader.addClass('current');      
      }
      else {
        tabheader.removeClass('current');      
      }
    });
    
    this.contentblocks.each(function(contentblock) {
      if(contentblock.id == tabId) {
        contentblock.removeClass('tab-hidden');
      }
      else {
        contentblock.addClass('tab-hidden');
      }      
    });
  }
};

 
 
/***
 * Maps class
 */
function Maps(el) {
  this.container = el;
  this.setup();
}
Maps.prototype = {
  geocoder: null,
  locations: [],

   setup: function() {
     this.map = new google.maps.Map2(this.container);
     this.map.setCenter(new google.maps.LatLng(51.921508, 4.472122), 14);
     //this.geocoder = new google.maps.Geocoder();
     //this.setCenter('Beatrix theater, Utrecht');
   },
   
   setCenter: function(geoLocation) {
     alert(': ' + geoLocation);
   },
   
   geolocate: function(locationname) {
     var that = this;
     geocoder.geocode(
       { address: locationname },
       function(results, status) {
       if (status == google.maps.GeocoderStatus.OK && results.length) {
         if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
           that.setCenter(results[0].geometry.location);
         }
       } else {
         alert("Geocode was unsuccessful due to: " + status);
       }
     });
     
   },
   
   addLocation: function(location) {
     this.locations.push(location);
   },
   
   renderLocations: function() {
     this.locations.each(function(location) {
       
     });
   }
};
/* end - Maps class */

/***
 * loaders
 */
window.addEvent('load', function() {
  var app = new App();
  app.init();
});
