
window.addEvent("domready", function() {
	var page;
	
	switch($("container").className) {
		case "press-page":
			page = new ListingPage("press-page");
			break;
		case "people-page":
			page = new ListingPage("people-page");
			break;
		case "home-page":
			page = new HomePage();
			break;
		case "clientbrands-page":
			page = new ClientBrandsPage(); //--- Located in ClientBrands.js
			break;
	}
});

var HomePage = new Class({
	"_fx" : [],
	"rotation" : null,
	"initialize": function() {
		var that = this;
		this.rotation = window.rotation = new RotateClass($$(".content-body")[0]);
		this.rotation.start();
		
		this.rotation.slideItems
			.addEvent("mouseenter", function() {
				
				that.rotation.stop();
			})
			.addEvent("mouseleave", function() {
				that.rotation.start();
			})
		
		//--- Attach On Hover Script
		/*
		$$(".cell-wrapper")
			.addEvent("mouseenter", function() {
				var cellWrapper = this;
					cellWrapper.addClass("hover");
				
				//--- Expand Black Area
				var cellContent = this.getElement(".cell-content");
				var tile = cellContent.getElement(".tile");	
					tile.setStyle("opacity", 0);
					
				//--- Wasn't doing it all the time in the mouseleave.
				var fadeCell = this.getElement(".cell-wrapper-fade");
				
				page._fx.push( 
					Fade( fadeCell, .85, 0, { 
					 "onComplete" : function() {
						 	
							if(!cellWrapper.hasClass("hover")) {
								fadeCell.setStyle("opacitity", .85);
								return;	
							}
			
						},
					"onCancel" : function() {
						fadeCell.setStyle("opacitity", .85);
					},
					duration:200})
				);
				
				//--- On Complete, Fade in Tile (Tile should be hidden by default)
				page._fx.push(
					Expand(cellContent, 0, 124, function() {
						tile.setStyles({"display":"block", "opacity":0});
						page._fx.push( Fade(tile, 0, 1) );
					})
				);				
			})
			.addEvent("mouseleave", function() {
				this.removeClass("hover");
				
				page.stopEffects();
				
				var cellContent = this.getElement(".cell-content");
					cellContent.setStyle( "height", "0px");
				
				//--- This isn't reliable enough. Adding it to the mouse enter as well.
				var fader = this.getElement(".cell-wrapper-fade");
					fader.setStyle("opacity", ".85");
				
				var tile = cellContent.getElement(".tile");	
					tile.setStyles( {"display":"none", "opacity":0} );

			})
			.forEach(function(item, index) {
				var el = new Element("DIV", { "class": "cell-wrapper-fade" } );
					el.injectInside(item);
			});;
		
		$$(".internal").addEvent("click", function() {
			this.setProperty("href", "clientbrands/index.html#" + this.getProperty("href"));
		});
		
		//--- A Psuedo Cache. Apply the hover class, computer the styles by doing the getStyle call, then remove the hover class.
		$$(".cell-wrapper")
			.addClass("hover")
			.forEach(function(item, index) {
				//--- Don't remove this line, its needed to re-compute the styles and actually make the download call for the background images.
				//var background = item.getStyle("background-image");
				item.removeClass("hover");
			})
		*/
	},
	"stopEffects" : function() {
		this._fx.each(function(item,index,arry) {
			if(item && item.stop) {
				item.stop();	 
			} 
		});
		
		this._fx = [];
	}
});

var ListingPage = new Class({ 
	"initialize" : function (pageType) {
		//--- If this is not the press page, stop.
		if( !$("container").hasClass(pageType) ) {
			return null;
		}
		
		//--- Attach List Events
		var listCtrl = new List();
		
		SWFAddress.onInit = function() {
			//--- Specify in-page linking
			SWFAddress.onChange = function() {
				//--- Get Hash From Querystring
				var hashVal = SWFAddress.getValue(); 
				
				listCtrl.expand(hashVal);
			}
			
			//--- Now that I've initialized the list, bind its events.
			listCtrl.bind( $E(".list") );
		}	
		
			
	}	
});

var List = new Class( {
	"_list"			: null,
	"_defaultVisible"	: null,
	"initialize" 	: function() {
		//--- Support Default visible entries
		var lnk = $E(".list .visible a.internal");
		this._defaultVisible = (lnk) ? lnk.getProperty("href") : null;
	},
	//--- Attach Onclick events
	"bind" 			: function(el) {
		var ctrl = this;
		
		this._list = el;
		
		//--- Look for the internal link within a list item.
		var links = $$("a.internal");
			links.forEach(function(item,index) {
				var infoRow = item.getParent().getParent();
				//--- Binds events to the list item rows.
				ctrl.BindListItem(infoRow, item.getProperty("href"));
					
				//--- Link should do nothing.
				item.removeProperty("href");				
				
				//--- Wire up the more / hide button
				var moreHide = $$( infoRow.getElement(".r"), infoRow.getElements("A") );
					moreHide.addEvent("click", function(e) {
						if(infoRow.getParent().hasClass("visible")) {
							SWFAddress.setValue( "" );
							new Event(e).stop();
						}
					});
			});
		
		if(this._defaultVisible) {
			SWFAddress.setValue( this._defaultVisible );
		}		
		
		//--- Add the first class
		var kids = el.getChildren();
		if(kids.length > 0) {
			kids[0].addClass("first");	
		}
	},
	"BindListItem": function(el, key) {
		el.setProperty("rel", key);
		el.addEvent("click", function(ev) {
			var hash = $(this).getProperty("rel");
			
			SWFAddress.setValue( hash );
			
			var e = new Event(ev);
				e.stop();
		}).addEvent("mouseover", function() {
			var listItem = this.getParent();
			//--- If the item is visible, don't apply the hover class.
			if(listItem.hasClass("visible")) {
				return;
			}
			this.addClass("hover");
		}).addEvent("mouseout", function() {
			this.removeClass("hover");
		});
	},
	"expand"		: function(key) {
		//--- Shrink everything to expand just the one selected.
		this.shrinkAll(key);
		
		var selected = $E("div.multi-col[rel='" + key + "']");
		
		if(selected) {
			selected.removeClass("hover");
			
			var moreHelp = selected.getElement(".r");
				moreHelp.setText("Hide");
				
			var expandItem = selected.getParent();
				expandItem.addClass("visible");
			
			var m = expandItem.getElement(".press-info .m");
				
			Expand(expandItem, 0, (m) ? m.getSize().size.y+10 : 338);
		}
	},
	"shrinkAll"		: function(ignoreKey) {
		this._list
			.getElements(".visible")
			.forEach(function(item, index) {
				//--- Don't close the one we are about to expand.
				//--- We could get a race condition where we expand it, then the transition for the Shrink happens and removes the visible class causing problems.
				if(item.getFirst().getProperty("rel") == ignoreKey){
					return;
				}
				
				Shrink(item, 19, function() {
					item.removeClass("visible");
				});
			});

		this._list
			.getElements("div[rel] .r")
			.setText("More");
	}, 
	"hover" 		: function() {
		
	}
});

function AddToCurrentHash(newHash) {
	//--- Should either add it to the existing hash or override the value already in the hash.
	var newHashVals = ParseHash(SWFAddress.getValue() + newHash);
	
	var vals = [""];
	for(var key in newHashVals) {
		vals.push(key);
		vals.push(newHashVals[key]);
	}
	
	SWFAddress.setValue(vals.join("/"));
}


function ParseHash(hash) {
	var allVals = hash.split("/");
	var ret = {};
	for(var c=0;c<allVals.length;c++) {
		if(allVals[c] == "") continue;
		ret[allVals[c++].toLowerCase()] = (allVals[c]) ? allVals[c].toLowerCase() : "";
	}
	
	if(ret.industry == null) ret.industry = "";
	if(ret.service == null) ret.service = "";
	
	return ret;
}

function Expand(element, from, to, onComplete, onStart, onCancel) {
	var prev = null;
	
	//--- Redefine the function but this time it will have the prev closure property.
	Expand = function(element, from, to, onComplete, onStart, onCancel) {
		if(prev) {
			prev.stop();
		}
		
		var style = new Fx.Style(element, "height", {duration: 400, "onComplete" : (onComplete || function() {}), "onStart" : (onStart || function() {}), "onCancel" : (onCancel || function() {})   });
			style.start(from, to);
		
		prev = style;
		return style;
	}
	
	//--- Call it, this will only be hit the first time this function is run, as it gets re-defined without this line.
	Expand(element, from, to, onComplete);
}

function Shrink(element, to, onComplete) {
	var style = new Fx.Style(element, "height", {duration: 400, "onComplete" : (onComplete || function() {})});
		style.start(to);
	return style;
}

function Fade(element, from, to, args) {
	var onComplete = $type(args) == "object" ? args.onComplete : args;
	var onCancel = $type(args) == "object" ? args.onCancel : null;
	var duration = $type(args) == "object" ? args.duration : 400;

	
	var style = new Fx.Style(element, "opacity", {duration: (duration || 400), "onComplete" : (onComplete || function() {}), "onCancel" : (onCancel || function() {}) });
		style.start(from, to);
	return style;
}

function HorizontalSlide(element, from, to, onComplete) { 
	var style = new Fx.Style(element, "left", {duration: 400, "onComplete" : (onComplete || function() {}) });
		style.start(from, to);
	return style;
}



var RotateClass = new Class({
	container : null,
	slideItems : $$(),
	timerID : null,
	first: null,
	padding: 76,
	stickingOut : 116,
	speed : 5000,
	initialize: function(container, items) {
			this.container = container;
			this.slideItems = items || container.getChildren();
			this.first = this.slideItems[0];
		},
	start : function() {
			this.timerID = this.rotate.periodical(this.speed, this);
		},
	stop: function() {
			this.timerID = $clear(this.timerID);
		},
	_clean: function() {
		var that = this;
		var maxWidth = this.container.getSize().size.x;
		
		this.slideItems.forEach(function(item, index) {
			item.Show();
			if(item.offsetLeft > maxWidth || item.offsetLeft == 0) {
				item.setStyle('left', (item.getSize().size.x * -2 + (that.stickingOut-that.padding)) + "px");
			}
		});
	},
	rotate: function() {
		var that = this;
		this._clean();
		/*
		var firstItem = this.first.getPrevious() || this.first.getParent().getLast();
		var newFirstItem = firstItem.getPrevious() || this.first.getParent().getLast();
		var middleItem = this.first;
		var lastItem = this.first.getNext() || this.first.getParent().getFirst();
		*/
		this.first = $$(this.getPanelsInOrder()).map(function(item, index) {
			//item.effect('left').start( item.offsetLeft + item.getSize().size.x + that.padding );
			item.SlideTo( item.offsetLeft + item.getSize().size.x + that.padding );
			return item;
		})[0];
		
		//this.first = firstItem;
	},
	/*
	Brings a panel to the middle
		panel: which panel to center
		direction: (1, -1, null) to determine which direction to slide the panels to the center.
	*/
	center : function(panel, direction){
		//--- If we want to center the centered panel, do nothing.
		if(panel == this.first) { return; }
		
		//--- Direction, is it greater or less then the position of the currently centered positioned panel?
		direction = direction || ((panel.offsetLeft < this.first.offsetLeft) ? 1 : -1);
		
		//--- Figure out where they are, where they should go, and which direction.
		
		//--- Get the panel information
		var panels = this.getPanelsInOrder(panel);
		
		//--- Calculate new end points
		
		
		//--- Start the tweens to move the panels from where they are to where they should go.
	},
	getPanelsInOrder : function(centerPanel, dir){
		centerPanel = centerPanel ||  this.first;
		var f = centerPanel.getPrevious() || centerPanel.getParent().getLast();
		return [
			f.getPrevious() || centerPanel.getParent().getLast(),
			f,
			centerPanel,
			centerPanel.getNext() || centerPanel.getParent().getFirst()
		];
	},
	calculateEndpoints : function(center, panels, dir) {
		var offset = (center.offsetLeft - this.first.offsetLeft) * dir; 
	}
	
});

Element.extend({
	Show : function() {
		return this.setStyles({visibility: 'visible', display: 'block'});
	},
	SlideTo: function(from, to) {
		this.effect('left').start( from, to );
		return this;
	},
	getLoopNext: function() {
		return this.getNext() || this.getParent().getFirst();
	},
	createIndicators: function() {
		alert(hello);
	}
});
