/**
 * @author arian
 */

(function(){
	
	var storage = [];
	
	Element.implement({
	
	    slideCat: function(how){
			var id = this.getProperty('id'),
				cookieName = 'closedCat',
				fx;

			if (!id) return this;
			id = id.replace('CatToggle','');

			if (storage[id] && storage[id]['slideCat:fx']){
				fx = storage[id]['slideCat:fx'];
			} else {
				fx = new Fx.Slide('Links'+id, {transition:Fx.Transitions.Expo.easeOut, duration: 1000});
				storage[id] = {'slideCat:fx': fx};
			}
			fx.stop();

			switch(how){
				case 'init': 
					if(Cookie.contains(cookieName,'C'+id+'-') ){
						fx.hide();
						$('img'+id).setProperty('src','images/open.gif');
						Cookie.add(cookieName,'C'+id+'-',true);
					}
				break;
				case 'toggle':
					if(Cookie.contains(cookieName,'C'+id+'-')){
						Cookie.replace(cookieName,new RegExp('C'+id+'\-','gi'),'');
						fx.slideIn();
						$('img'+id).setProperty('src','images/close.gif');
					}else{
						Cookie.add(cookieName,'C'+id+'-');
						fx.slideOut();
						$('img'+id).setProperty('src','images/open.gif');
					}
				break;
			}
			return this;
	    }
		
	});
	
	Cookie.extend({
		
		replace: function(name,search,replace){
			this.write(name, this.read(name).replace(search, replace));
		},

		contains: function(name,search){
			var str = this.read(name);
			if(!str){return false;}
			return str.contains(search);
		},
			
		add: function(name,str,noDuplicate){
			if (!(noDuplicate && this.contains(name, str))){
				this.write(name,this.read(name) + str);
			}
		},
				
		clear: function(name){
			this.write(name,'');
		}
		
	});
	
})();


window.addEvent('domready', function(){

	$$('.closeButton')
		.slideCat('init')
		.addEvent('click', function(e){
			new Event(e).stop();
			this.slideCat('toggle');
		});		

	var request = new Request({
		'url': 'dochters/update_clicks.php',
		//'X-Request': 'XMLHttpRequest',
		'method': 'get'
	});

	// Link clicks teller
	$$('.link').addEvent('click', function(){
		var link_id = this.getProperty('id').replace('link_','');
		request.send({data: {
			link_id: link_id,
			time: Date.now()
		}});
	});

});

