/*
 * JS CHOIX-MORTEL
 * 
 * Need : Mootools 1.2 & CNET String Ext
 * 
 */

var $E = function(str){
	return document.getElement(str);
};

if (typeof console != "object") {
	var console = {
		'log':function(){}
	};
}		

var choixMortel = {

	'init': function(){
		
		$$('textarea.count').addEvents({
			'keydown':choixMortel.nbCharsRestants,
			'keypress':choixMortel.nbCharsRestants,
			'keyup':choixMortel.nbCharsRestants,
			'change':choixMortel.nbCharsRestants,
			'click':choixMortel.nbCharsRestants,
			'blur':choixMortel.nbCharsRestants
		});
		
		$$('a.confirm').addEvent(
			'click',function(event){
				if (confirm('Es tu sûr ?')) { return true; }
				else { event.stop(); return false; }
			}
		);
		
		if($$('a.choixLink')) {
			$$('div.choixTop').set('tween', {duration: 'normal',transition: 'cubic:out'});
			$$('a.choixLink').addEvent('click',choixMortel.choixValid);
		}
		
		if ($('message')) {
			
			var nbCharsRestants = function(event){
				var nb = 1000-$('message').value.length;
				nb = nb>0?nb:0;
				$('nbCharsRestants').set('html',nb);
				if (!nb) {
					$('message').value=$('message').value.substring(0,1000);
					if (typeof event.key != 'undefined') {
						if (['up', 'down', 'left', 'right', 'backspace', 'delete', 'esc', 'tab'].indexOf(event.key) == -1) {
							return false;
						}
					}
				}
			};
			
			$('message').addEvents({
				'keydown':nbCharsRestants,
				'keypress':nbCharsRestants,
				'keyup':nbCharsRestants,
				'change':nbCharsRestants,
				'click':nbCharsRestants,
				'blur':nbCharsRestants
			});
			
		}
		
		if ($$('.targetBlank')) {
			$$('.targetBlank').addEvent('click',function(event){
				event.stop();
				window.open(this.href);
			});
		}
		
		if ($$('a.boxed').length) {
			SqueezeBox.assign($$('a.boxed'), {
				parse: 'rel'
			});
		}
		
		if ($('boutonPublic') && $('boutonPrive')) {
			choixMortel.boutonCreer();
		}
		
		if ($$('div.shareJS').length) {
			choixMortel.shareJSinit();
		}
		
		var resizeInputText = function(){
			var l = (this.value.length<5)?5:this.value.length;
			this.setStyle('width',l*12);
			if (Browser.Engine.trident) this.getParent().getParent().rounded();
			return true;
		};

		if ($$('input.ch1,input.ch2').length) {
			$$('input.ch1,input.ch2').addEvent('keyup',resizeInputText);
			$$('input.ch1,input.ch2').each(function(el){ resizeInputText.bind(el).run(); });
		}
		
	},
	
	'choixValid':function(){
				
		var handlerFunc = function(r){
			if (r!='NOK') {
				var p = this.getParent();
				p.set('opacity',0);
				p.set('html',r);
				if (typeof Element.rounded == "function") { p.getParent().rounded(); }
				p.fade('in');
				spanNbVotes = p.getParent().getElement('span.nbVotes');
				spanNbVotes.set('html',parseInt(spanNbVotes.get('html'))+1);
				if (!Browser.Engine.trident) { p.getParent().highlight('#ffffd5'); }
			}
		};
		
		new Request({
			url: '/ajax/',
			data: 'action=choixLink&data='+this.rel,
			onComplete: handlerFunc.bind(this),
			evalScripts: true
		}).send();
	},
	
	'addMsgAutres':function(el){
			var cont = el.getParent();
			var link = cont.getElement('div.choixBottom a').href;
			new Element('div',{'class':'msgGroupe'}).inject(cont).set('html','<a href="'+link+'">Voir les réponses des membres du groupe !</a>');
	},
	
	'proposer':function(){
		
		var done = false;
		
		var showBlock = function(){
			if (!done && ($('choix1').value || $('choix2').value) ) {
				$('choixPreview').setStyles({
					'display':'block',
					'visibility':'visible'
				});
				done = true;
			}
		};
		
		var updateChoix1 = function(){
			showBlock();
			$('choix1preview').set('html',$('choix1').value.stripTags().tidy());
			if (typeof Element.rounded == "function") $('choixPreview').rounded();
		};
		
		var updateChoix2 = function(){
			showBlock();
			$('choix2preview').set('html',$('choix2').value.stripTags().tidy());
			if (typeof Element.rounded == "function") $('choixPreview').rounded();
		};
		
		var cleanChoix = function(event){
			$('choix1').set('value',$('choix1').value.stripTags().tidy());
			$('choix2').set('value',$('choix2').value.stripTags().tidy());
		};
		
		updateChoix1();
		updateChoix2();
					
		$('choix1').addEvents({
			'keydown':updateChoix1,
			'keypress':updateChoix1,
			'keyup':updateChoix1,
			'change':updateChoix1,
			'click':updateChoix1,
			'blur':updateChoix1
		});
		
		$('choix2').addEvents({
			'keydown':updateChoix2,
			'keypress':updateChoix2,
			'keyup':updateChoix2,
			'change':updateChoix2,
			'click':updateChoix2,
			'blur':updateChoix2
		});
		
		
		$('proposerValider').addEvent({
			'click':cleanChoix
		});
		
		$('formProposer').addEvent({
			'submit':cleanChoix
		});
	},
	
	'nbCharsRestants':function(event){
		
		var nbMax = (this.title);
		var nb = nbMax-this.value.length;
		nb = nb>0?nb:0;
		this.getParent().getElement('div.nbChar').set('html',nb);
		if (!nb) {
			this.value=this.value.substring(0,nbMax);
			if (typeof event.key != 'undefined') {
				if (['up', 'down', 'left', 'right', 'backspace', 'delete', 'esc', 'tab'].indexOf(event.key) == -1) {
					return false;
				}
			}
		}
	},
	
	'injectRoundedBox': function(html,el,where) {
		return new Element('div',{
			'class':'roundedBox createdThruAjax'
		}).inject(el,where).setStyle('opacity',0).set('html',html).fade('in');
		
		
	},

	'choixValidOnLoad': function(rel) {
		var tmp = $$('a[rel='+rel+']');
		
		if (tmp.length) {
			var el = tmp[0];
			window.scrollTo(0,el.getCoordinates().top-(window.getHeight()/2));
			choixMortel.choixValid.bind(el).delay(500);
		}		
	},
	
	'boutonCreer': function(){
	
		$$('div.boutonCreer').addEvent('click', function(){
			$$('div.creerGroupe input[type=text] , div.creerGroupe textarea').set('disabled', false);
			$$('div.creerGroupe input[type=text] , div.creerGroupe textarea').removeClass('disabled');
			$$('div.boutonCreer').removeClass('selected');
			this.addClass('selected');
		});
		

		$('boutonPublic').store('tip:title', 'Un groupe public est un groupe accessible par tout le monde');
		$('boutonPublic').addEvent('click', function(){
			$('inputPublic').set('value', 1);
		});
		
		

		$('boutonPrive').store('tip:title', 'Un groupe privé est un groupe accessible seulement aux gens qui connaissent l\'adresse de ton groupe');		
		$('boutonPrive').addEvent('click', function(){
			$('inputPublic').set('value', 0);
		});
		
		var myTips = new Tips('.boutonCreer',{'className':'tipContainer'});

	},
	
	'clearChoixValidOnLoad':function(){
		new Request({
			url: '/ajax/',
			data: 'action=clearChoixValidOnLoad',
			evalScripts: true
		}).send();
	},

	'shareJSinit':function(){
		$$('div.shareJS select').addEvents({
			'change':choixMortel.shareJSEvent
		});
		choixMortel.shareJSEvent();
		
		$('shareJSCSSHelp').store('tip:title', 'Choisis l\'apparence d\'affichage des Choix Mortels sur ton site, tu peux, sois utiliser les couleurs de Choix Mortel ou bien ne pas choisir de thème et eventuellement le personnaliser toi même');
		$('shareJSCadreHelp').store('tip:title', 'Afficher Oui ou Non le cadre autour d\'un Choix Mortel');
		$('shareJSHTMLHelp').store('tip:title', 'Copie ce code à l\'endroit où tu veux que le ou les Choix Mortels apparaissent.');
		var myTips = new Tips('.tips',{'className':'tipContainer'});
		
		if ($('shareGroupeLibelle')) {
			if ($('shareGroupeLibelle').value) {
				choixMortel.shareGetGroupePermalink();
			}
		}
		
	},
	
	'shareJSEvent':function(){
		var groupeStr = $('shareGroupePermalink')?'&groupe='+$('shareGroupePermalink').value:'';
		var JSstr = 'fortunes.php?css='+$('shareCSS').value+'&box='+$('shareBox').value+'&nb='+$('shareNb').value+groupeStr;
		$('shareHTML').value='<script type="text/javascript" src="http://www.choix-mortel.com/'+JSstr+'"></script>';
		$('sharePreview').src='/php/fortunes-preview.php?JSstr='+escape(JSstr);
		if (typeof Element.rounded == "function") { $$('div.shareJS')[0].rounded(); }
	},
	
	'shareGetGroupePermalink':function(){
		new Request.HTML({
			url: '/ajax/',
			data: {
				'action':'shareGetGroupePermalink',
				'data':$('shareGroupeLibelle').value
			},
			update: $('shareGroupePermalinkContainer')
		}).send();
	},
	
	'validerChoix':function(id,rel){
		var tmpObject = JSON.decode(rel);
		var ch1 = $E('div.choix-'+id+' input.ch1').value;
		var ch2 = $E('div.choix-'+id+' input.ch2').value;
		console.log(ch1);
		console.log(ch2);

		new Request.HTML({
			url: '/ajax/',
			data: {
				'action':'validerChoix',
				'idGroupe':tmpObject.idGroupe,
				'idChoix':tmpObject.idChoix,
				'flag':tmpObject.flag,
				'ch1':ch1,
				'ch2':ch2
			},
			update:$E('div.choix-'+id+' span.validerChoixLinksContainer')
		}).send();		
		
	}

};

window.addEvent('domready',choixMortel.init);