var Diapo = Class.create({
	initialize:function(element, options) {
		this.element = $(element);
		if(! element) {
			throw "Diapo#initizalize : given element does not exist";
		}
		this.options = Object.extend({
			autoChangeDelay: 4,
			maxMove : 10,
			frequency: 0.05
		},options || {});
		this.itemLink = new Element("a", {href: "#"});
		this.imageItem 	= new Element("img");
		this.itemLink.insert(this.imageItem);
		this.titleElem 	= this.element.down(".highLightItem .highLightItemTitle");
		this.authorElem = this.element.down(".highLightItem .highLightItemAuthor");
		this.dateElem 	= this.element.down(".highLightItem .highLightItemPublish");
		this.element.select(".highLightItem .hidable").invoke("hide");
		
		this.element.down(".highLightItem").insert({top: this.itemLink});
		this.nav	= this.element.down(".diapoNav ul");  
		this.items	= this.element.select(".diapoNav ul li");
		this.index	= 0;
		this.showCurrItem();
		this.bindEvents();
	},
	
	getNavMarginLeft : function() {
		return parseInt(this.nav.getStyle("marginLeft").replace(/px/, "") || "0");
	},
	
	showCurrItem : function() {
		this.nav.select(".current").invoke("removeClassName", "current");
		if(this.index < this.items.length) {
			this.items[this.index].addClassName("current");
			this.itemLink.href = this.items[this.index].down("a").href;
			this.imageItem.src = this.items[this.index].down("img").src;
			this.titleElem.update(this.items[this.index].down(".diapoNavItemTitle").innerHTML);
			this.authorElem.update(this.items[this.index].down(".diapoNavItemAuthor").innerHTML);
			this.dateElem.update(this.items[this.index].down(".diapoNavItemPublish").innerHTML);
		}
	},
	
	move : function(third, left, pos, minMarginLeft) {
		var currMarge = this.getNavMarginLeft();
		if(pos <= third) {
			if(currMarge < 0) {
				this.nav.setStyle({marginLeft: Math.min(0, Math.round(currMarge + this.options.maxMove * (third - pos) / third)) + "px"});
			}
		} else if(pos >= 2 * third) {
			if(currMarge > minMarginLeft) {
				this.nav.setStyle({marginLeft: Math.max(minMarginLeft, Math.round(currMarge - (this.options.maxMove * (pos - 2 * third) / third))) + "px"});
			}
		}		
	},
	
	runner : function(func) {
		func();
		this.timer = setTimeout(this.runner.curry(func).bind(this), 1000 * this.options.frequency);
	},
	
	bindEvents: function() {
		this.navContainer = this.element.down(".diapoNav");
		this.navContainer.observe("mousemove", function(e){
			e.stop();
			var navContainerWidth = this.navContainer.getWidth();
			var third = navContainerWidth / 3;
			var left = this.navContainer.viewportOffset().left;
			var pos = e.clientX - left;
			var lastItem = this.items.last();
			var minMarginLeft = -1*((lastItem.positionedOffset().left - navContainerWidth) + lastItem.getWidth()) ;
			if(this.timer) {
				clearTimeout(this.timer);
			}
			
			var func = this.move.curry(third, left, pos, minMarginLeft).bind(this);
			this.runner(func);
		}.bindAsEventListener(this));
		
		this.element.observe("mouseenter", function() {
			clearTimeout(this.timer);
			
		}.bindAsEventListener(this));

		this.element.observe("mouseleave", function() {
			this.timer = setTimeout(this.nextItem.bind(this), 1000 * this.options.autoChangeDelay);
		}.bindAsEventListener(this));
		
		this.navContainer.observe("mouseleave", function(e){
			if(this.timer) {
				clearTimeout(this.timer);
			}
			
		}.bindAsEventListener(this));
		
		
		this.items.each(function(item, index) {
			item.observe("mouseover", function(e) {
				this.index = index;
				this.showCurrItem();
			}.bindAsEventListener(this));
		}, this);
		
		this.element.down(".highLightItem").observe("mouseenter", function() {
			this.element.select(".highLightItem .hidable").invoke("show");
		}.bindAsEventListener(this));

		this.element.down(".highLightItem").observe("mouseleave", function() {
			this.element.select(".highLightItem .hidable").invoke("hide");
		}.bindAsEventListener(this));
		
		this.timer = setTimeout(this.nextItem.bind(this), 1000 * this.options.autoChangeDelay);
	},
	
	nextItem : function() {
		this.index++;
		if(this.index >= this.items.length) {
			this.index = 0;
		}
		this.showCurrItem();
		var lastItem = this.items.last();
		this.setBestMargin(this.items[this.index], lastItem)
		this.timer = setTimeout(this.nextItem.bind(this), 1000 * this.options.autoChangeDelay);
	},
	
	setBestMargin : function(item, lastItem) {
		var navContainerWidth = this.navContainer.getWidth();
		var minMarginLeft = -1*((lastItem.positionedOffset().left - navContainerWidth) + lastItem.getWidth()) ;
		var posL = item.positionedOffset().left;
		var halfContainerWidth = (navContainerWidth / 2);
		var halfItemWidth = item.getWidth()/2;
		var bestMargin = -posL + halfContainerWidth - halfItemWidth;
		this.nav.setStyle({marginLeft:Math.min(Math.max(minMarginLeft, bestMargin), 0) + "px"});
	}
});

var MyLibrary = {
		curSize : 62.5,
		minSize : 50,
		maxSize : 100,
		
		initialize : function() {
			MyLibrary.initFont();
			MyLibrary.initCommentFormView();
			if ($$('.fontGrow').length > 0 && $$('.fontShrink').length > 0) {
				$$('.fontGrow').invoke( 'observe', 'click', function( event ) { 
					Event.stop(event);
					MyLibrary.growFont();
				});
				$$('.fontShrink').invoke( 'observe', 'click', function( event ) { 
					Event.stop(event);
					MyLibrary.shrinkFont();
				});
				$$('.fontGrow, .fontShrink').each( function( item ) {
					item.style.display = 'block';
				});
			}
			MyLibrary.initDiapo();
		},
		
		initDiapo : function() {
			$$(".diapoMain").each(function(diapo) {
				new Diapo(diapo);
			});
		},
		
		initFont : function() {
			if ( typeof ( CookieMama ) == 'undefined') {return;}
			var tmp = CookieMama.readCookie('app-font-size');
			try {
				if (tmp.length > 0 && !isNaN( tmp )) {
					 MyLibrary.curSize = parseFloat(tmp);
				}
			} catch (e) { }
			MyLibrary.applyFont();
		},
		
		initCommentFormView: function() {
			if ($$('#comment_form_elem form').length > 0) {
				$$('#commentDetails a.link, #comment_form_title a, #detail_actions a.comment_add').invoke( 'observe', 'click', function( event ) {
					Event.stop(event);
					$('comment_form_elem').show();
					try {
						document.location.hash = 'comments';
					} catch(e) {}
				});
				$('comment_form_elem').hide();
				$$('#detail_actions a.comment_add').each( function( item ) {
					item.style.display = 'block';
				});
			}
		},
		
		growFont : function() {
			if (MyLibrary.curSize >= MyLibrary.maxSize) {return ;}
			MyLibrary.curSize += 5;
			MyLibrary.applyFont();
		},
		
		shrinkFont: function() {
			if (MyLibrary.curSize <= MyLibrary.minSize) {return ;}
			MyLibrary.curSize -= 5;
			MyLibrary.applyFont();
		},
		
		applyFont: function() {
			document.body.style.fontSize = MyLibrary.curSize + '%';
			if (typeof ( CookieMama ) != 'undefined') {
				CookieMama.writeCookie('app-font-size', MyLibrary.curSize, '365');
			}
		}
};

var WediaPopin = (function(){
	
	var protectDiv = null;
	var contentDiv = null;
	var closeDivLink = null
	var initProtectDiv = function() {
		protectDiv = new Element("div", {className: "protectDivPopin", style:"display:none"});
		contentDiv = new Element("div", {className: "contentDiv"});
		protectDiv.insert(contentDiv);
		closeDivLink = new Element("a", {href: "#", className: "close"}).update("X");
		contentDiv.insert(closeDivLink);
		$(document.body).insert({bottom: protectDiv});
	};

	var maximizeProtectDiv = function(options) {
		options.afterFinish = options.afterFinish || Prototype.emptyFunction;
		options.afterFinish = options.afterFinish.wrap(function(original){
			original();
			adaptContentDiv();
		});
		if(protectDiv == null) {
			initProtectDiv();
		}
		var vpDim = document.viewport.getDimensions();
		var bodyDim = $(document.body).getDimensions();

		protectDiv.setStyle( {
			width: Math.max(vpDim.width, bodyDim.width) + "px",
			height: Math.max(vpDim.height, bodyDim.height) + "px"
		} );
		
		if(options.useEffect) {
			protectDiv[options.useEffect.dasherize().camelize()]( options );
		} else {
			protectDiv.show();
			options.afterFinish();
		}
	};

	var hideProtectDiv = function(options) {
		if(options.useEffect) {
			switch(options.useEffect.dasherize().camelize()) {
				case 'appear' :
					options.useEffect = 'fade';
					break;
				case 'blindDown' :
					options.useEffect = 'blindUp';
					break;
				case 'slideDown' :
					options.useEffect = 'slideUp';
					break;
			}
			protectDiv[options.useEffect.dasherize().camelize()]( options );
		} else {
			protectDiv.hide();
			options.afterFinish();
		}

	};

	var runAjax = function(href) {
		new Ajax.Updater(contentDiv, href, {
			method: "get",
			onComplete: adaptContentDiv
		});
	};

	var adaptContentDiv = function() {
		contentDiv.removeClassName("waiting");
		var vpDim = document.viewport.getDimensions();
		var contentDim = contentDiv.getDimensions();
		var scrolls = document.viewport.getScrollOffsets();
		contentDiv.setStyle( {
			top: (scrolls.top + (vpDim.height - contentDim.height) / 2) + "px",
			left: (scrolls.left + (vpDim.width - contentDim.width) / 2) + "px"
		} );
	};

	return {
		openDiv : function(a, options) {
			if(contentDiv == null) {
				initProtectDiv();
			}
			protectDiv.insert(closeDivLink);
			contentDiv.addClassName("waiting").childElements().invoke("remove");
			contentDiv.insert(closeDivLink);
			var key = a.href.substr(a.href.lastIndexOf("#") + 1);
			if($(key)) {
				var move = $(key);
				move.store("__old_parent__", $(move.parentNode).identify());
				options.afterFinish = Element.insert.curry(contentDiv, {bottom: move});
				WediaPopin.keyPressCache = function(e) {
					if(e.element().identify() == closeDivLink.identify() || e.keyCode == Event.KEY_ESC) {
						if(e.element().identify() == closeDivLink.identify()) {
							e.element().blur();
						}
						e.stop();
						WediaPopin.closeDiv(closeOptions);
						$(move.retrieve("__old_parent__")).insert(move);
					}
				}
			} else {
				options.afterFinish = runAjax.curry(a.href);
				WediaPopin.keyPressCache = function(e) {
					if(e.element().identify() == closeDivLink.identify() || e.keyCode == Event.KEY_ESC) {
						if(e.element().identify() == closeDivLink.identify()) {
							e.element().blur();
						}
						e.stop();
						WediaPopin.closeDiv(closeOptions);
					}
				}
			}
			
			maximizeProtectDiv(options);
			var closeOptions = {
				useEffect: options.useEffect,
				afterFinish: Prototype.emptyFunction
			};
			$(document).observe("keyup", WediaPopin.keyPressCache);
			closeDivLink.observe("click", WediaPopin.keyPressCache);
		},
		closeDiv: function(options) {
			$(document).stopObserving("keyup", WediaPopin.keyPressCache);
			closeDivLink.stopObserving("click", WediaPopin.keyPressCache);
			hideProtectDiv(options);
		}
	}
})();

document.observe("dom:loaded", function () {
	MyLibrary.initialize();
	$$('a[rel="external"]').invoke( 'writeAttribute', {target : '_blank'} );
	$$("a.popin").invoke("observe", "click", function(e){
		e.stop();
		WediaPopin.openDiv(e.element(), {useEffect: "appear"});
	});
	$$('a[rel=userconnect], a[rel=usercreate]').invoke( 'observe', 'click', function( event ) {
		Event.stop(event);
		$$('form input[type=text], form input[type=password]').invoke('setValue', '');
		$$('form input[type=radio]').each( function( elem ) { elem.checked = false; } );
		$$('form select').each( function( elem ) { elem.selectedIndex = 0; } );
		$$('form#connectuser, form#createuser').invoke('toggle');
		return false;
	});
});

