// accordion.js v2.0
//
// Copyright (c) 2007 stickmanlabs
// Author: Kevin P Miller | http://www.stickmanlabs.com
// 
// Accordion is freely distributable under the terms of an MIT-style license.
//
// I don't care what you think about the file size...
//   Be a pro: 
//	    http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
//      http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files
//

/*-----------------------------------------------------------------------------------------------*/

//if (typeof Effect == 'undefined') {
//	throw("accordion.js requires including script.aculo.us' effects.js library!"); }

var accordion = Class.create();
accordion.prototype = {

	//
	//  Setup the Variables
	//
	showAccordion : null,
	currentAccordion : null,
	duration : null,
	effects : [],
	animating : false,
	
	//  
	//  Initialize the accordions
	//
	initialize: function(container, options) {
	  if (!$(container)) {
	    throw(container+" doesn't exist!");
	    return false;
	  }
	  
		this.options = Object.extend({
			resizeSpeed : 8,
			classNames : {
				toggle : 'acc_toggle',
				toggleActive : 'acc_toggle_active',
				content : 'acc_content'
			},
			defaultSize : {
				height : null,
				width : null
			},
			direction : 'vertical',
			onEvent : 'click'
		}, options || {});
		
		this.duration = ((11-this.options.resizeSpeed)*0.15);

		var accordions = $$('#'+container+' .'+this.options.classNames.toggle);
		accordions.each(function(accordion) {
			Event.observe(accordion, this.options.onEvent, this.activate.bind(this, accordion), false);
			if (this.options.onEvent == 'click') {
			  accordion.onclick = function() {return false;};
			}
			
			if (this.options.direction == 'horizontal') {
				var options = {width: '0px'};
			} else {
				var options = {height: '0px'};			
			}
			Object.extend(options, {display: 'none'});			
			
			this.currentAccordion = $(accordion.next(0)).setStyle(options);			
		}.bind(this));
	},
	
	//
	//  Activate an accordion
	//
	activate : function(accordion) {
		if (this.animating) {
			return false;
		}
		
		this.effects = [];
	
		this.currentAccordion = $(accordion.next(0));
		this.currentAccordion.setStyle({
			display: 'block'
		});		
		
		this.currentAccordion.previous(0).addClassName(this.options.classNames.toggleActive);

		if (this.options.direction == 'horizontal') {
			this.scaling = {
				scaleX: true,
				scaleY: false
			};
		} else {
			this.scaling = {
				scaleX: false,
				scaleY: true
			};			
		}
			
		if (this.currentAccordion == this.showAccordion) {
		  this.deactivate();
		} else {
		  this._handleAccordion();
		}
	},
	// 
	// Deactivate an active accordion
	//
	deactivate : function() {
		var options = {
		  duration: this.duration,
			scaleContent: false,
			transition: Effect.Transitions.sinoidal,
			queue: {
				position: 'end', 
				scope: 'accordionAnimation'
			},
			scaleMode: { 
				originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : this.currentAccordion.scrollHeight,
				originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : this.currentAccordion.scrollWidth
			},
			afterFinish: function() {
				this.showAccordion.setStyle({
          height: 'auto',
					display: 'none'
				});				
				this.showAccordion = null;
				this.animating = false;
			}.bind(this)
		};    
    Object.extend(options, this.scaling);

    this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
    
		new Effect.Scale(this.showAccordion, 0, options);
	},

  //
  // Handle the open/close actions of the accordion
  //
	_handleAccordion : function() {
		var options = {
			sync: true,
			scaleFrom: 0,
			scaleContent: false,
			transition: Effect.Transitions.sinoidal,
			scaleMode: { 
				originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : this.currentAccordion.scrollHeight,
				originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : this.currentAccordion.scrollWidth
			}
		};
		Object.extend(options, this.scaling);
		
		this.effects.push(
			new Effect.Scale(this.currentAccordion, 100, options)
		);

		if (this.showAccordion) {
			this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
			
			options = {
				sync: true,
				scaleContent: false,
				transition: Effect.Transitions.sinoidal
			};
			Object.extend(options, this.scaling);
			
			this.effects.push(
				new Effect.Scale(this.showAccordion, 0, options)
			);				
		}
		
    new Effect.Parallel(this.effects, {
			duration: this.duration, 
			queue: {
				position: 'end', 
				scope: 'accordionAnimation'
			},
			beforeStart: function() {
				this.animating = true;
			}.bind(this),
			afterFinish: function() {
				if (this.showAccordion) {
					this.showAccordion.setStyle({
						display: 'none'
					});				
				}
				$(this.currentAccordion).setStyle({
				  height: 'auto'
				});
				this.showAccordion = this.currentAccordion;
				this.animating = false;
			}.bind(this)
		});
	}
}


// Tooltip Object
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(el, options) {
		this.el = $(el);
		this.initialized = false;
		this.setOptions(options);
		
		// Event handlers
		this.showEvent = this.show.bindAsEventListener(this);
		this.hideEvent = this.hide.bindAsEventListener(this);
		this.updateEvent = this.update.bindAsEventListener(this);
		Event.observe(this.el, "mouseover", this.showEvent );
		Event.observe(this.el, "mouseout", this.hideEvent );
		
		// Removing title from DOM element to avoid showing it
		this.content = this.el.title;
		this.el.title = "";

		// If descendant elements has 'alt' attribute defined, clear it
		this.el.descendants().each(function(el){
			if(Element.readAttribute(el, 'alt'))
				el.alt = "";
		});
	},
	setOptions: function(options) {
		this.options = {
			backgroundColor: '#999', // Default background color
			borderColor: '#666', // Default border color
			textColor: '', // Default text color (use CSS value)
			textShadowColor: '', // Default text shadow color (use CSS value)
			maxWidth: 250,	// Default tooltip width
			align: "left", // Default align
			delay: 250, // Default delay before tooltip appears in ms
			mouseFollow: true, // Tooltips follows the mouse moving
			opacity: .75, // Default tooltips opacity
			appearDuration: .25, // Default appear duration in sec
			hideDuration: .25 // Default disappear duration in sec
		};
		Object.extend(this.options, options || {});
	},
	show: function(e) {
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		if(!this.initialized)
			this.timeout = window.setTimeout(this.appear.bind(this), this.options.delay);
	},
	hide: function(e) {
		if(this.initialized) {
			this.appearingFX.cancel();
			if(this.options.mouseFollow)
				Event.stopObserving(this.el, "mousemove", this.updateEvent);
			new Effect.Fade(this.tooltip, {duration: this.options.hideDuration, afterFinish: function() { Element.remove(this.tooltip) }.bind(this) });
		}
		this._clearTimeout(this.timeout);
		
		this.initialized = false;
	},
	update: function(e){
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		this.setup();
	},
	appear: function() {
		// Building tooltip container
		this.tooltip = Builder.node("div", {className: "tooltip", style: "display: none;" }, [
			Builder.node("div", {className:"xtop"}, [
				Builder.node("div", {className:"xb1", style:"background-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"})
			]),
			Builder.node("div", {className: "xboxcontent", style: "background-color:" + this.options.backgroundColor + 
				"; border-color:" + this.options.borderColor + 
				((this.options.textColor != '') ? "; color:" + this.options.textColor : "") + 
				((this.options.textShadowColor != '') ? "; text-shadow:2px 2px 0" + this.options.textShadowColor + ";" : "")}, this.content), 
			Builder.node("div", {className:"xbottom"}, [
				Builder.node("div", {className:"xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb1", style:"background-color:" + this.options.borderColor + ";"})
			]),
		]);
		document.body.insertBefore(this.tooltip, document.body.childNodes[0]);
		
		Element.extend(this.tooltip); // IE needs element to be manually extended
		this.options.width = this.tooltip.getWidth();
		this.tooltip.style.width = this.options.width + 'px'; // IE7 needs width to be defined
		
		this.setup();
		
		if(this.options.mouseFollow)
			Event.observe(this.el, "mousemove", this.updateEvent);
			
		this.initialized = true;
		this.appearingFX = new Effect.Appear(this.tooltip, {duration: this.options.appearDuration, to: this.options.opacity });
	},
	setup: function(){
		// If content width is more then allowed max width, set width to max
		if(this.options.width > this.options.maxWidth) {
			this.options.width = this.options.maxWidth;
			this.tooltip.style.width = this.options.width + 'px';
		}
			
		// Tooltip doesn't fit the current document dimensions
		if(this.xCord + this.options.width >= Element.getWidth(document.body)) {
			this.options.align = "right";
			this.xCord = this.xCord - this.options.width + 20;
		}
		
		this.tooltip.style.left = this.xCord - 7 + "px";
		this.tooltip.style.top = this.yCord + 12 + "px";
	},
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};


function showHide(elementId, clickEl){
  var el = $$('.hide'+elementId);
  el.each(function(h) {
    if (h.style.display == 'none') {
      if ($(clickEl).match('input')) {
        if (clickEl.checked) {
          if(h.nodeName == "span" || h.nodeName == "SPAN"){
        		h.style.display = 'inline';
        	} else {
        		h.style.display = 'block';
        	}
        };
      } else {
        if(h.nodeName == "span" || h.nodeName == "SPAN"){
      		h.style.display = 'inline';
      	} else {
      		h.style.display = 'block';
      	}
      }
    } else if ($(clickEl).match('input')) {
      if (!clickEl.checked) {
        h.style.display = 'none';
      };
    } else {
      h.style.display = 'none';
    }
  });
}

document.observe("dom:loaded", function(e) {
  // zebra stripe tables
  if (tbls = $$('.zebra')) {
    tbls.each(function(t){
      for (var i=2; i < t.rows.length; i+=2) {
        t.rows[i].className = "even";
      };
    });
  };
  
  // check for show/hide and check all
  var showEls = [];
  var checkEls = [];
  var gshowEls = [];
  $$("*").each(function(el){
    if (el.className.startsWith('show')) {showEls.push(el)};
    if (el.id.startsWith('check')) {checkEls.push(el)};
    if (el.className.startsWith('gshow')) {gshowEls.push(el)};
  })
  
  // set up show/hide
  if (showEls[0]) {
    showEls.each(function(showEl){
      showEl.i = showEl.className.slice(4);
      if (!showEl.checked) { $$('.hide'+showEl.i).each(function(h){ h.style.display = "none"; });};
      if (showEl.type == "radio") {
        var rads = document.getElementsByName(showEl.name);
        for (var i=0; i < rads.length; i++) {
          rads[i].onclick = function() {
            for (var j=0; j < rads.length; j++) {
              if (rads[j].i) {showHide(rads[j].i, rads[j])};
            };
          };
        };
      } else {
        showEl.onclick = function() {
          showHide(this.i, this);
          if (this.type == "") {
            return false;
          }
        }
      }
    })
  }
  
  var curg;
  // set up group dependent show/hide
  if (gshowEls[0] && gshowEls[1]) {
    gshowEls.each(function(gshowEl){
      gshowEl.i = gshowEl.className.slice(5);
      if (!gshowEl.checked) { $$('.hide'+gshowEl.i).each(function(h){ h.style.display = "none"; });};
      gshowEl.onclick = function() {
        var el = $$('.hide'+this.i);
        var t = this;
        el.each(function(e){
          if (e.style.display == 'none') {
            if (curg) {showHide(curg.i, curg)};
            curg = t;
            showHide(curg.i, curg);
          };
        })
        if (this.type == "") {
          return false;
        }
      }
    })
  }
  
  // set up check all
  if (checkEls[0]) {
    checkEls.each(function(checkEl){
      checkEl.i = checkEl.id.slice(5);
      checkEl.style.display = 'inline';
      checkEl.onclick = function() { 
        if (this.innerHTML == "Check All") {
          $$('.cbx'+this.i).each(function(c){ c.checked = true; });
          this.update('Uncheck All');
        } else {
          $$('.cbx'+this.i).each(function(c){ c.checked = false; });
          this.update('Check All');
        }
        return false; 
      };
      $$('.cbx'+checkEl.i).each(function(c){
        c.i = checkEl.i;
        c.onclick = function(){
          var checkEl = $('check'+this.i);
          var falseCount = 0;
          $$('.cbx'+this.i).each(function(cb){ if (!cb.checked) {falseCount++};});
          (falseCount > 0) ? checkEl.update('Check All') : checkEl.update('Uncheck All');
        };
      });
    })
  };
  
  // set up popups
  if (pop = $$('.pop')) {
    pop.each(function(p){
      p.title = "This link opens a new browser window."
  		p.onclick = function(){
  		  var popup = window.open(p.href, 'popup', 'resizable=yes,scrollbars=yes,toolbar=no,location=no,width=500,height=500');
  		  popup.focus();
  		  return false;
		  }
  	});
  };
  if (navpop = $$('.navpop')) {
    navpop.each(function(np){
      np.title = "This link opens a new browser window."
			np.onclick = function(){
				var navpopup = window.open(np.href, 'navpopup', 'resizable=yes,scrollbars=yes,toolbar=yes,location=yes,menubar=yes,width=700,height=500');
				navpopup.focus();
				return false;
			}
		});
  };
  
  // set up calendar
  var cals = $$(".cal")
  if (cals[0]) {
    var calOut = new Element('div', {id:'calendar-container', style:'width: 227px; position:absolute; display:none;'});
    $('content').insert({'bottom':calOut});
    calOut.insert({'top':'<b class="rtop"><b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b></b>'});
    var calIn = new Element('div', {'class':'floating', id:'calendar'});
    calOut.insert({'bottom':calIn});
    
    var calImgs = [];
    cals.each(function(c){
      calImgs.push(new Element('img', {src:'/apps/images/icoCalendar.gif', alt:'calendar', 'class':'calImg', title:'Open calendar to select date.'}));
      c.insert({'after':calImgs.last()});
      Event.observe(calImgs.last(), "click", imgCalendar_Click.bindAsEventListener(this, c, calOut, calIn));
    });
  };
  
  // set up accordion
  if ($('acc')) {
    var a = new accordion('acc');
    a.activate($$('#acc .acc_toggle')[0]);
  };
  
  // set up smooth scrolling
  var smooth_anchors = [];
  var smooth_links = [];
  var smooth_count = 0;
  $$('a').each(function(l) {
    if (link = l.href.split("#")[1]) {l.i = smooth_count; smooth_anchors.push(l); smooth_links.push(link); smooth_count++;};
  })
  if (smooth_anchors[0]) {
    smooth_anchors.each(function(s){s.onclick = function(){Effect.ScrollTo(smooth_links[s.i]); return false;}})
  };
  
  // set up tool tips

  if (ts = $$('.tip')) {
    ts.each(function(t){
      new Tooltip(t, {backgroundColor:'#F7F5EA', borderColor:'#EBE7CB', opacity:.9});
    });
  };
  
});