/**
 * @author Janar Todesk, Mekaia http://mekaia.com/
 */

/*
 * Rightside sliding trays
 */

jQuery(window).load(function(){
	/* Setup hidden trays */
	$('.closed .tray-placer').each(function(){
		$(this).css('margin-top',-($(this).height()+30));
	});
})

jQuery(function($){

	var cookie = new Cookie();
	
	/* Set cookies of element states */
	$('.with-tray').each(function(){
		cookie.write($(this).attr('id'),$(this).hasClass('closed') ? 'closed' : 'open');
	})

	/* Bind animation to trays */
	$('.with-tray').each(function(){
		var _tray = $('.tray-placer',this);
		var $this = this;
		$('img.icon, h1', this).bind('click',function(event){
			

			if(_tray.parents('.with-tray').hasClass('closed')){
				_tray.animate({marginTop:0},300,function(){
					var _widget = $(this).parents('.with-tray');
					_widget.removeClass('closed');
					cookie.write(_widget.attr('id'),'open');
				})
			}else{
				_tray.animate({marginTop:-$($this).height()},300,function(){
					var _widget = $(this).parents('.with-tray');
					_widget.addClass('closed');
					cookie.write(_widget.attr('id'),'closed');
				})
			}

			return false;
		});
	});

})

function Cookie(){
	this.write = function(_name,_value){
		document.cookie = _name+"="+_value+"; path=/";
	}

	this.read = function(_name){
		var nameMatch = _name+"=";
		var crumbs = document.cookie.split(';');

		for(var i=0;i<crumbs.length;i++){
			var crumb=crumbs[i];

			while(crumb.charAt(0)==' '){
				crumb=crumb.substring(1,crumb.length);
			}

			if(crumb.indexOf(nameMatch)==0){
				return crumb.substring(nameMatch.length,crumb.length);
			}
		}
		return null;
	}

	this.erase = function(_name){
		this.create(_name,'',-1);
	}
}

jQuery( document ).ready( function ( $ ) {
	// Add first and last menu item classes
	$('.menu li:last-child, .menu li:last-child').addClass( 'last' );
});
