var Site = {
  emptyImageURL : "/static/project/unimaaspresentation/images/empty.gif",
	init: function(){
		this.togglerStates = {};
		var _this = this;
		
		// Add hover to all tables with class "listing"
		$$("table.listing").each(function(table){
			_this.addTableHover(table);
		});
		
		
		$$("ul.faq li.selected ul").each(function(ul){
			_this.enableFaq(ul);
		});

		$$(".tooltip").each(function(el){
			_this.t = _this.enableToolTip(el);
		});

    $$("a.play").each(function(el){
     _this.enablePlayButton(el); 
    })
		
	},
	// Toggle all checkboxes within an element
	toggleAll : function(wrapper_id){
	  var setTo = true;
	  if(this.togglerStates[wrapper_id]){
	    setTo = false;
	  }
    this.togglerStates[wrapper_id] = setTo	  
	  
    $(wrapper_id).getElements("input[type=checkbox]").each(function(el){
      el.checked = setTo;
    });	  
    return false;
	},
	enablePlayButton : function(el_id){
	  var el = $(el_id);
	  var img = el.getElement("img");
	  if(!img){ return; }
    var caption = el.getElement(".caption");	  
    el.setStyle("position","relative");

	  // Strange thing: Only an image seems to pass-through the
	  // click event in IE...
    var playButton = new Element("img",{"src" : Site.emptyImageURL, "class": "play"});
    playButton.injectBefore(img);
  
    if(caption){
      var captionBg = new Element("img");
      var captionWrapper = new Element("span", {"class" : "caption-wrapper"});
      captionWrapper.setStyle("opacity",0.8)
      captionWrapper.injectAfter(img);
    }
  
    
      
    var setSize = function(o){
      var iSize = img.getCoordinates();
      var pSize = el.getCoordinates();
      playButton.setStyles({width : iSize.width, height : iSize.height, position: "absolute"});
      if(caption){
        var c = caption.getCoordinates();
        captionWrapper.setStyles({height: c.height });        
      }
      // el.setStyles({width : iSize.width, height : iSize.height});
    };

    // We have to set it twice because the image may not have been loaded yet.
    img.addEvent("load", setSize);	  
	  setSize();
	},
	enableToolTip: function(el){
		return new ToolTip(el);
	},
	enableFaq: function(ul){
		ul.getChildren("li").each(function(question){
			question.addEvent("click",function(){
				question.toggleClass("selected");
			});
			// Prevent link following within the header	
			if(question.getElement("h4 a")){
				question.getElement("h4 a").addEvent("click",function(e){var ev = new Event(e).preventDefault();});
			}
		});
	},
	// Add hover and open/close behaviour to table rows
	addTableHover: function(table){
		var toggleHover = function (row, type){
			var func = type + "Class";
			// set mouse cursor to pointer style when applicable
			if (row.hasClass("description") || (row.getNext() && row.getNext().hasClass("description"))) {
				row.setStyle("cursor", "pointer");
			}
			
			// add hover class to applicable rows
			row[func]("hover");
			if (row.hasClass("description") && row.getPrevious()){
				row.getPrevious()[func]("hover");
			}	else {
				if (row.getNext() && row.getNext().hasClass("description")){
					row.getNext()[func]("hover");
				}
			}			
		};
		
		table.getElements("tr").each(function(row){
			row.addEvent("mouseover",function(){ toggleHover(row, "add");	});
			row.addEvent("mouseout",function(){ toggleHover(row, "remove"); });
			
			if(row.getNext() && row.getNext().hasClass("description")){
				row.addEvent("click",function(ev){
					ev = new Event(ev);
					// Allow input fields to work
				  if($(ev.target).getTag() == "input" || $(ev.target).getTag() == "a"){ return; }	
				  
					// open & close on toprow
					if(row.hasClass("open")){
						row.removeClass("open");
						row.getNext().removeClass("show");						
					} else {
						row.addClass("open");
						row.getNext().addClass("show");
					}
				});				
			} else {
				if(row.hasClass("description") && row.getPrevious()){
					row.addEvent("click",function(ev){
						ev = new Event(ev);
						// Allow linsk to work
						if($(ev.target).getTag() == "a"){ return; }
						// close on descriptionrow
						if(row.hasClass("show")){
							row.removeClass("show");
							row.getPrevious().removeClass("open");						
						} 
					});				
				}
			}
		});
	}
};

var ToolTip = new Class({
	options : {
		offsets : {"x" : 16, "y" : 16}
	},
	initialize : function(element){
		this.element = $(element);
		this.toolTip = new Element('div', {
			'class': 'tooltip',
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'display': 'none'
			}
		}).inject(document.body);		
		
		this.build();
	},
	// Extract title from element and add events
	build : function(){
		this.title = this.element.getAttribute("title");
		this.element.removeAttribute("title");
		this.toolTip.setText(this.title);
		
		this.element.addEvent("mouseenter",function(ev){this.locate(ev); this.show();}.bindWithEvent(this));
		this.element.addEvent("mousemove",this.locate.bindWithEvent(this));
		var hide = this.hide.bind(this);
		this.element.addEvent("mouseleave",hide);
		this.element.addEvent("trash",hide);
	},
	locate: function(event){
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		for (var z in prop){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > win[z]){ pos = event.page[z] - this.options.offsets[z] - tip[z];}
			this.toolTip.setStyle(prop[z], pos);
		}
	},	
	show : function(){
		this.toolTip.setStyle("display","block");
	},
	hide : function(){
		this.toolTip.setStyle("display","none");	
	}
	
});

// =====================================
// = OverlayWindow : AJAX ` window =
// =====================================
var OverlayWindow = {
	visible : false,
	element : null,
	open : function(url){
		Overlay.show();
		
		this.create();		
		var request = new Ajax(url,{method:'get',update:this.element, onComplete:this.loaded.bind(this), evalScripts: true}).request();
	},
	// Method to use as an eventhandler for links in an overlay window
	// usage: $('<link id>').addEvent('click',OverlayWindow.onNavigate);
	onNavigate : function(event){
		var ev = new Event(event).preventDefault();

		var aj = new Ajax(this.getProperty("href"), {
			method: 'get',
			update: OverlayWindow.element,
			evalScripts: true,
			onComplete: OverlayWindow.loaded.bind(OverlayWindow)			
		}).request();		
	},
	// Method to use as a form submit handler in overlay windows
	onSubmit : function(event){
		var ev = new Event(event).preventDefault();
		
		this.send({
			update: OverlayWindow.element,
			evalScripts: true,
			onComplete: OverlayWindow.loaded.bind(OverlayWindow)			
		});		
	},
	close : function(){
		this.element.setStyles({display : "none"});		
		window.removeEvents({scroll: this.setPositionEvent, resize: this.setPositionEvent});		
		this.visible = false;
		Overlay.hide();
	},
	show : function(){
		if(this.visible){ return; }
		
		this.element.setStyles({display : "block"});
		this.setPosition();	
		window.addEvents({scroll: this.setPositionEvent, resize: this.setPositionEvent});
		this.visible = true;		
	},
	// Window loaded eventhandler
	loaded : function(){
		this.element.getElements("a.close").each(function(el){
			el.addEvent("click",this.close.bind(this));
		}.bind(this)
		);
		this.show();		
	},
	// Set position to screen vertical center, do horizontal centering in CSS
	setPosition : function(){
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		this.element.setStyle("height", Math.round(wh*0.8)+10);
		this.element.getElement("div[class=overlay-content]").setStyle("height", Math.round(wh*0.8));
		this.element.setStyle("top",window.getScrollTop() + (window.getHeight() - this.element.getSize().size.y)/2);
	},
	create : function(){
		if(!this.element){
		  document.addEvent("keydown",(function(ev){if (ev.key == "esc"){OverlayWindow.close();}}).bindWithEvent(document));
			this.element = new Element("div").setProperty("id","overlaywindow").injectInside(document.body);
			this.element.setStyles({display : "none"});
			// Pre-bind the function so we can use it as eventhandler
			this.setPositionEvent = this.setPosition.bind(this);						
		}
	}
};

// ==========================================================
// = Overlay : Display semi-transparent window-wide overlay =
// ==========================================================
// Example : Overlay.show(0.5)
//
// Only one instance of Overlay will ever be created, calling another show()
// will not do anything. 
var Overlay = {
	visible : false,
	// Pas in an opacity value for the background.
	show : function(opacity){
		if(this.visible){ return false; }
		
		this.create();
		this.element.setStyles({opacity: (opacity ? opacity : 0.8), display: "block"});
		this.setup(true);
		this.setPosition();
		this.visible = true;
	},
	hide : function(){
		if(!this.element){return false;}
		this.element.setStyles({display: "none"});
		this.setup(false);
		this.visible = false;
	},
	// Set position and size to full window
	setPosition : function(){
		var ww = (window.getWidth() === 0) ? window.getScrollWidth()-22 : window.getWidth();
		var wh = (window.getHeight() === 0) ? window.getScrollHeight() : window.getHeight();
		this.element.setStyles({top: window.getScrollTop(), height: wh , width:ww});
	},
	create : function(){
		if(!this.element){
			this.element = new Element("div").setProperty('id', 'overlay').injectInside(document.body);
			// Pre-bind the function so we can use it as eventhandler
			this.setPositionEvent = this.setPosition.bind(this); 
		}
	},
	setup : function(open){
		var elements = $A(document.getElementsByTagName('object'));
		if (window.ie){ elements.extend(document.getElementsByTagName('select')); }
		elements.each(function(el){ el.style.visibility = open ? 'hidden' : ''; });
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.setPositionEvent);
		window[fn]('resize', this.setPositionEvent);
	}
};

var ThumbnailGallery = new Class({
  // Pass a second argument with the ID/element of the image part to replace.
  initialize : function(containerId){
    this.containerEl = $(containerId);
    this.navPreviousEl = this.containerEl.getElement("div.prev a");
    this.navNextEl = this.containerEl.getElement("div.next a");
    this.scrollEl = this.containerEl.getElement(".items");
    this.scroller = new Fx.Scroll(this.scrollEl,{wait: false});
    this.position = 0;
    this.origPosition = 0;
    
    this._attachNavigationEvents();
    this._constrainScrollEl();

    if(arguments.length > 1){
      this.imageEl = $(arguments[1]);
      this._attachThumbnailClickEvents();
    }
    
    this.scrollIncrement = this.scrollEl.getSize().size.x / 2;
    this.scrollEl.scrollTo(0,0);
  },
  scrollToPrevious : function(){
    this.origPosition = this.position;    
    this.position = this.position - this.scrollIncrement;
    if(this.position <= 0){ this.position = 0; }
    this._scrollToPosition();
  },
  scrollToNext : function(){
    this.origPosition = this.position;
    this.position = this.position + this.scrollIncrement;
    if(this.position >= this.maxScroll ){ this.position = this.maxScroll; }
    
    this._scrollToPosition();
  },
  // Private
  _scrollToPosition : function(){
    if(this.origPosition != this.position){
      this.scroller.scrollTo(this.position,0);
    }
  },
  _constrainScrollEl : function(){
    this.scrollEl.setStyles({
      overflow: "hidden"
    });
    
    // Fix the scrollEl width
    var scrollerWidth = this.scrollEl.getSize().size.x;
    this.scrollEl.setStyle("width",scrollerWidth);
    
    var ul = this.scrollEl.getElement("ul");
    
    // Insert an element in the scroller
    var measure = new Element("div",{styles :{width: 100000}});
    this.scrollEl.adopt(measure);
    
    // Insert the UL into the new element
    measure.adopt(ul);
    
    var ulSize = ul.getSize().size;
    ul.setStyle("width", ulSize.x);
    this.maxScroll = ulSize.x - scrollerWidth;
    
    // Cleanup
    this.scrollEl.adopt(ul);
    measure.remove();
    
  },
  _attachNavigationEvents : function(){
    $A(["Next","Previous"]).each(function(l){
      this["nav"+l+"El"].addEvent("click",function(e){
        var ev = new Event(e);
        this["scrollTo" + l]();
        ev.preventDefault();        
      }.bindWithEvent(this));
    }.bind(this));
  },
  _attachThumbnailClickEvents : function(){
    this.scrollEl.getElements("li a").each(function(el){
      el.addEvent("click",this._thumbnailClick.bindWithEvent(this,el.getProperty("href")));
    }.bind(this));
  },
  _thumbnailClick : function(e,url){
    var ev = new Event(e);
    ev.preventDefault();
    if(url != "#"){
      var ajax = new Ajax(url, {method: 'get', update: this.imageEl});
      ajax.request();
    }
  }
});


// Global Site initialization
window.addEvent("domready", Site.init.bind(Site));
