/**
  *
  * Large Envelope
  * @version 1.0
  * @author pclancy
  *
  */

  // onLoad event
  var MainMenu;
	Event.observe( window, 'load',
	  function() {
	  	if ($('tab_container')) {
	  		MainMenu = new TabNavagation('tab_container');
	  	}
	  }
	);


 /**
 * Navagation Tabs
 * Combo buttons and menu element.
 * @param	{String||Obj}	elem	A tag element
 */
var TabNavagation = Class.create();

TabNavagation.prototype = {
	initialize:function(elem) {
		this.tabComponent =  $(elem);
		this.componetWidth = this.tabComponent.getDimensions().width - 100;
		this.first=0; // first visible tab - start first tab flush left
		this.viewRange=0; // how many tabs are in view
		this.tabs = $A(this.tabComponent.getElementsBySelector('table.tab'));
		// determine how many tabs to display
		this.computeWidth = 0;
		$(this.tabs).each(function(item) {
			item.tabWidth = item.getDimensions().width;
			//console.log('item width plus component width = ' + (item.tabWidth + this.computeWidth));
			if ((item.tabWidth + this.computeWidth) <= this.componetWidth) {
				this.computeWidth = item.tabWidth + this.computeWidth;
				this.viewRange = ++this.viewRange;
				item.show();
			}
		}.bind(this));
		if (this.tabs.length > this.viewRange) {
			this.leftArrow = $('leftScrollLink');
			this.leftArrowDisabled = $('scrollLeftDisabled');
			this.rightArrow = $('rightScrollLink');
			this.rightArrowDisabled = $('scrollRightDisabled');
			Event.observe(this.leftArrow, "click", this.scroll.bindAsEventListener(this));
			Event.observe(this.rightArrow, "click", this.scroll.bindAsEventListener(this));
			this.displayButtons();
		}
	},
	scroll:function(event) {
		var aLink = Event.element(event).parentNode.id;
		if (this.leftArrow.id == aLink) {
		  	if (this.first + this.viewRange < this.tabs.length) {
		  		this.tabs[this.first].hide();
		  		this.tabs[this.first + this.viewRange].show();
		  		//new Effect.Fade(this.tabs[this.first], {duration:0.0});
		  		//new Effect.Appear(this.tabs[this.first + this.viewRange], {duration:0.5});
				this.first++;
		  	}
		  } else {
		  	if (this.first > 0) {
		  		this.tabs[this.first + (this.viewRange - 1)].hide();
		  		this.tabs[this.first - 1].show();
		  		//new Effect.Fade(this.tabs[this.first + (this.viewRange - 1)], {duration:0.0});
		  		//new Effect.Appear(this.tabs[this.first - 1], {duration:0.5});
		  		this.first--;
		  	}
		  }
		  // adjust the scroll buttons
		  this.displayButtons();
	},
	displayButtons:function(event) {
		if (this.first > 0) {
	  		// enable scroll right
	  		this.rightArrowDisabled.hide();
	  		this.rightArrow.show();
	  	} else {
	  		// disable scroll right
	  		this.rightArrow.hide();
	  		this.rightArrowDisabled.show();
	  	}


	  	if (this.first + this.viewRange < this.tabs.length) {
	  		// enable scroll left
	  		this.leftArrowDisabled.hide();
	  		this.leftArrow.show();

	  	} else {
	  		// disable scroll left
	  		this.leftArrow.hide();
	  		this.leftArrowDisabled.show();
	  	}
	}
};

/**
 * ResizeWindow adjustments
 * @param	{obj}	hash object with the setup params
 */
var ResizeWindow = Class.create();

ResizeWindow.prototype = {
	initialize:function(hashObj) {
		this.c1 = $(hashObj.essayPanel);
		this.c2 = $(hashObj.mentorPanel);
		this.handle = $(hashObj.handle);
		this.container = getMatchingAncestors(this.c1, 'div').getWidth();

		var values = new Array();
		for (var n = 1; n <= 100; n++) {
                values.push(n);
              }
		new Control.Slider(this.handle,'track1',{ range: $R(1, 100), values: values, sliderValue: 50, onSlide: this.sliding.bind(this), onChange: this.changePosition.bind(this) });
		// TODO - set up the start off layout

	},
	changePosition:function(sliderValue) {
		blockEvents.stopEventCapture();
	},
	sliding:function(sliderValue) {
		blockEvents.startEventCapture();
		var newWidth = 170 + parseInt(this.handle.getStyle('left')) ;
		this.c1.setStyle({ width: newWidth + 'px' });
	}
};

/**
 * Resize Up Down Window adjustments
 * @param	{obj}	hash object with the setup params
 */
var ResizeUpDownWindow = Class.create();

ResizeUpDownWindow.prototype = {
	initialize:function(hashObj) {
		this.eID = $('CE_' + hashObj.editorID + '_ID');
		this.fID = $('CE_' + hashObj.editorID + '_ID_Frame');
		this.readOnlyID = $(hashObj.readOnlyID);
		this.chatContainer = $(hashObj.chatContainer);
		this.handle = $(hashObj.handle);
		this.track = $(hashObj.track);
		this.pageBkg = $(hashObj.pageBkg);

		var values = new Array();
		for (var n = 1; n <= 150; n++) {
                values.push(n);
              }
		new Control.Slider(this.handle, this.track, { range: $R(0, 150), values: values, axis: 'vertical', sliderValue: 85, onSlide: this.sliding.bind(this), onChange: this.changePosition.bind(this) });

		Position.clone(this.handle, this.chatContainer, { setHeight: false, setWidth: false, offsetTop: 10, offsetLeft: -300 });
		Position.clone(this.chatContainer, 'bottomPull', { setHeight: false, setWidth: false, offsetTop: 0, offsetLeft: -5000 });
	},
	changePosition:function(sliderValue) {
		blockEvents.stopEventCapture();
	},
	sliding:function(sliderValue) {
		blockEvents.startEventCapture();

		Position.clone(this.handle, this.chatContainer, { setHeight: false, setWidth: false, offsetTop: 10, offsetLeft: -300 });
		Position.clone(this.chatContainer, 'bottomPull', { setHeight: false, setWidth: false, offsetTop: 0, offsetLeft: -5000 });

		var newHeight = parseInt(this.handle.getStyle('top'));
		newHeight = newHeight +132;
		this.eID.setAttribute("height", newHeight + 'px');
		this.eID.setStyle({ height: newHeight + 'px' });
		this.fID.setStyle({ height: (newHeight - 2) + 'px' });
		this.readOnlyID.setStyle({ height: newHeight + 'px' });

		newHeight = newHeight + this.chatContainer.getHeight() + 80;
		this.pageBkg.setStyle({ height: newHeight + 'px' });
	}
};

/**
 * Resize Up Down Window adjustments for the bottom of the chat window
 * @param	{obj}	hash object with the setup params
 */
var ResizeBottomChatWindow = Class.create();

ResizeBottomChatWindow.prototype = {
	initialize:function(hashObj) {
		this.messagePanel = $(hashObj.messagePanel);
		this.handle = $(hashObj.handle);
		this.track = $(hashObj.track);
		this.pageBkg = $(hashObj.pageBkg);

		var values = new Array();
		for (var n = 1; n <= 150; n++) {
         	values.push(n);
         }
		new Control.Slider(this.handle, this.track, { range: $R(0, 150), values: values, axis: 'vertical', sliderValue: 75, onSlide: this.sliding.bind(this), onChange: this.changePosition.bind(this) });

		newHeight = parseInt(this.handle.getStyle('top')) - 2;
		this.messagePanel.setStyle({ height: newHeight + 'px' });
		this.pageBkg.setStyle({ height: Position.cumulativeOffset(this.handle)[1] - 100 + 'px' });
	},
	changePosition:function(sliderValue) {
		blockEvents.stopEventCapture();
	},
	sliding:function(sliderValue) {
		blockEvents.startEventCapture();

		newHeight = parseInt(this.handle.getStyle('top')) - 2;
		this.messagePanel.setStyle({ height: newHeight + 'px' });
		this.pageBkg.setStyle({ height: Position.cumulativeOffset(this.handle)[1] - 100 + 'px' });
	}
};

/**
 * A DIV to block mouse events while dragging.
 * @param	{elem}	The DIV element
 */
var BlockEvents = Class.create();

BlockEvents.prototype = {
	initialize:function(elem) {
		this.div = $(elem);

		Event.observe(this.div, "mouseover", this.eventTrap.bindAsEventListener.bind(this));
		Event.observe(this.div, "mouseout", this.eventTrap.bindAsEventListener.bind(this));
		Event.observe(this.div, "click", this.eventTrap.bindAsEventListener.bind(this));
	},
	stopEventCapture:function(sliderValue) {
		this.div.hide();
	},
	startEventCapture:function(event) {
		if (!this.div.visible()) {
			this.div.show();
		}
	},
	eventTrap:function(event) {
		Event.stop(event); // eat all mouse events;
	}
};

/**
 * Quick Links Menu Singleton
 * Singleton gateway for creating the menu object.
 * @param	{String||Obj}	elem A tag element
 * @param	{String}		align (left or right)
 */
function startQuickLinks(elem, align) {
var el = $(elem);
	if (!el.quickLinks) {
	 	el.quickLinks = new QuickLinks(el, align);
	}
}
/**
 * Menu Object inside an IFrame element
 * @param	{String||Obj}	elem	A tag element
 * @param	{String}		align (left or right)
 */
var QuickLinks = Class.create();

QuickLinks.prototype = {
	initialize:function(elem, align) {
		this.a = $(elem);
		this.offsetTop = this.a.getHeight();
		this.menu;
		this.iframe;
		this.timeOut;
		Event.observe(this.a, 'click', this.open.bindAsEventListener(this));
		Event.observe(this.a, 'mouseout', this.requestOff.bindAsEventListener(this));

		/* Create a new DIV to hold the menu UL and append it to the DIV#topNav.
		 * We do this to overcome z-index problems. We need to append the menus
		 * higher up on the DOM. This will force the menus to always appear on top of the modules.
		 */
		var tempDiv = document.createElement('div');
		Element.setStyle(tempDiv, { position: 'absolute', zIndex: 10 });
		$('content').appendChild(tempDiv); // add new empty DIV
		tempDiv.hide();
		tempDiv.appendChild($(this.a.next())); // move our menu into the new DIV
		tempDiv.firstDescendant().show();
		this.menu = $(tempDiv);

		Event.observe(this.menu, 'click', this.close.bindAsEventListener(this));
		Event.observe(this.menu, 'mouseover', this.open.bindAsEventListener(this));
		Event.observe(this.menu, 'mouseout', this.requestOff.bindAsEventListener(this));
		// now we can set the left offset
		this.offsetLeft = (align == 'right') ? (this.a.getWidth() - this.menu.getWidth()) : 0;
	},
	requestOff:function(event) {
		if (Event.element(event).tagName == undefined) { return; }
		this.timeOut = setTimeout(function() { this.close(); }.bind(this), 200);
	},
	open:function(event) {
		clearTimeout(this.timeOut);
		Event.stop(event);
		var delta = Position.cumulativeOffset(this.a);
		this.menu.setStyle({ left: delta[0] + this.offsetLeft + 'px', top: delta[1] + this.offsetTop + 'px' });
		this.menu.show();
	},
	close:function(event) {
		this.menu.hide();
	}
};

/**
 * Sticky Notes
 * Note Object
 * @param	{String||Obj}	noteId	The ID for the note
 */
var StickyNotes = Class.create();

StickyNotes.prototype = {
	initialize:function(noteId) {
		if ($('note_' + noteId) != null) { return; }
		this.iFrame;
		this.noteId = 'note_' + noteId;
		this.iFrameTemplate;

		//Event.observe(this.closeLink, 'click', this.close.bindAsEventListener(this));
		this.create(this.noteId);
	},
	create:function(event) {
		this.iFrameTemplate = new Template('<iframe src="#{href}" width="200" height="200" frameborder="0" name="#{id}" id="#{id}" class="stickyNote"></iframe>');
		var data = { href:'http://www.largeenvelope.com/requestNote.php?id='+this.noteId, id: this.noteId };
		new Insertion.Top('bodyTag', this.iFrameTemplate.evaluate(data));
	},
	open:function(event) {
		this.iFrame.show();
	},
	close:function(event) {
		this.iFrame.hide();
	}
};

/**
 * Info Box Singleton
 * Singleton gateway for creating the info box object.
 * @param	{String||Obj}	elem A tag element
 */
function startInfoBox(elem) {
var el = $(elem);
	if (!el.infoBox) {
	 	el.infoBox = new InfoBox(el);
	}
}
/**
 * Info Box Obj
 * Infomation Box that displays on rollover a link
 * @param	{String||Obj}	elem	A tag element
 */
var InfoBox = Class.create();

InfoBox.prototype = {
	initialize:function(elem) {
		this.a = $(elem);
		this.data;
		if (jData.length) {
			for (var i = 0; i < jData.length; i++) {
				var j = this.a.id;
				var index = j.lastIndexOf("_");
				if (j.substr(index+1) == jData[i].id) {
					this.data = jData[i];
				}
			}
		}
		this.offsetTop = -1 * (this.a.getHeight() + 15);
		this.offsetLeft = this.a.getWidth() - 3;
		this.menuId = 'infoBox_' + Math.floor(Math.random() * (10000 - 1 + 1)) + 1;
		this.infoBoxTemplate;
		this.timeOut;
		Event.observe(this.a, 'mouseout', this.requestOff.bindAsEventListener(this));
		Event.observe(this.a, 'mouseover', this.open.bindAsEventListener(this));

		/* Create a new info box from a template */
		this.create();
		this.menu = $(this.menuId);
		//Event.observe(this.menu, 'click', this.close.bindAsEventListener(this));
		Event.observe(this.menu, 'mouseover', this.open.bindAsEventListener(this));
		Event.observe(this.menu, 'mouseout', this.requestOff.bindAsEventListener(this));

		// now we can set the left offset
		Element.setStyle(this.menu, { position: 'absolute', zIndex: 10 });
		this.open();
	},
	create:function(event) {
		this.infoBoxTemplate = new Template($('infoTemplate').innerHTML);
		this.data.essay = (this.data.essay == 1) ? '<a target="_blank" href="display_essay.php?mid=' + this.data.id + '">essay</a>' : '';
		var data = { id: this.menuId, name: this.data.name, username: this.data.username, school_year: this.data.school_year,
		sex: this.data.sex, gpa: this.data.gpa, major: this.data.major, sat: this.data.sat, act: this.data.act, essay: this.data.essay,
		attending: this.data.attending };
		new Insertion.Top($$('body').first(), this.infoBoxTemplate.evaluate(data));
	},
	requestOff:function(event) {
		this.timeOut = setTimeout(function() { this.close(); }.bind(this), 100);
	},
	open:function(event) {
		clearTimeout(this.timeOut);
		var delta = Position.cumulativeOffset(this.a);
		this.menu.setStyle({ left: delta[0] + this.offsetLeft + 'px', top: delta[1] + this.offsetTop + 'px' });
		//Position.clone(this.a, this.menu, { setHeight: false, setWidth: false, offsetTop: this.offsetTop, offsetLeft: this.offsetLeft });
		this.menu.show();
	},
	close:function(event) {
		this.menu.hide();
	}
};

// put together
function initInfoBox() {

}

// SHARED FUNCTIONS

/**
 * Generic rollover script for all icons or buttons. Requires specific graphic file namiing.
 * @param {String || Object} 	id 		The the element object or element id.
 * @param {String} 				state 	The required state. (on = highlight state, off = standard state, undefined = toggle (on, off) state)
 */
function setImageState(id, state) {
var img_tag = $(id);
var onState = (img_tag.src.search(/_o./) == -1) ? false : true;
	if ((state == "on" && arguments.length > 1) || (!onState && arguments.length < 2)) {
		if (onState) { return; }
		img_tag.src = img_tag.src.replace(/(\.[^.]+)$/, '_o$1');
	} else if ((state == "off" && arguments.length >1) || (onState && arguments.length < 2)) {
		if (!onState) { return; }
		img_tag.src = img_tag.src.replace(/_o(\.[^.]+)$/, '$1');
	}
}
/**
 * Return the first sibling that matches the passed in selector.
 * @param {String}	elem		starting element (searching siblings only)
 * @param {String}	selector	CSS selector to find
 */
function getMatchingSibling(elem, selector) {
return $(elem).siblings().find(function(el) {
	return el.match(selector);
});
}
/**
 * Return the first Ancestors that matches the passed in selector.
 * @param {String}	elem		starting element (searching ancestors element nodes only)
 * @param {String}	selector	CSS selector to find
 */
function getMatchingAncestors(elem, selector) {
return $(elem).ancestors().find(function(el) {
	return el.match(selector);
});
}
/**
 * Return the first Descendants that matches the passed in selector.
 * @param {String}	elem		starting element (searching descendants element nodes only)
 * @param {String}	selector	CSS selector to find
 */
function getMatchingDescendants(elem, selector) {
	el = $(elem).getElementsBySelector(selector);
	return el[0];
}

// Toggle the display via a CSS class on the next row <tr>
function toggleRowDisplay(obj) {
 var parentTable = $(obj.parentNode);
 var nextRowId = obj.rowIndex + 1;
 if (nextRowId < parentTable.rows.length) {
 	if ($(parentTable.rows[nextRowId]).visible()) {;
		$(parentTable.rows[nextRowId]).hide();
		$(parentTable.rows[obj.rowIndex]).removeClassName('row_dots_false');
	} else {
		$(parentTable.rows[nextRowId]).show();
		$(parentTable.rows[obj.rowIndex]).addClassName('row_dots_false');
	}
 }
}









