/*------------------------------------------------------------------------------
    JS Document (https://developer.mozilla.org/en/JavaScript)

    project:    STPo - Demain j'arrête v3
    created:    2009-09-01
    author:     Christophe ANDRIEU

    summary:    CONSTANTES
                UTILITIES
				FUNCTIONS
                WINDOW.ONLOAD

----------------------------------------------------------------------------- */

/*  =CONSTANTES
----------------------------------------------------------------------------- */
var d = document;
var w = window;
var debug = null;
window.config = {
    debug : false
}


/*  =UTILITIES
----------------------------------------------------------------------------- */
/* getElementsByClassName when not supported */
var matchAll = function() {
    var node = arguments[1] || document;
    var elms = node.getElementsByTagName('*');
    var className = arguments[0];
    if (d.getElementsByClassName) {
        return node.getElementsByClassName(className);
    }
    else {
        var regExp = new RegExp('\\b'+className+'\\b');
        var array = [];
        for (var i = 0; i < elms.length; i++) {
            var current = elms[i];
            if (current.className.match(regExp)) {
                array.push(current);
            }
        }
        return array;
    }
};

/* logs into a textarea for IE and in the console for others */
var debuger = function() {
    if (window.config.debug && !debug && typeof console == 'undefined') {
        var parent = d.getElementsByTagName('div')[0];
        var body   = d.getElementsByTagName('body')[0];
        var debug  = d.createElement('textarea');
        debug.setAttribute('rows', 10);
        debug.setAttribute('cols', 80);
        debug.setAttribute('name', 'debug');
        body.insertBefore(debug, parent);
        window.debug = debug;
    }
    else if (window.config.debug && console) {
        log('Debug mode : on');        
    }
};
var log = function(x) {
    if (typeof console != 'undefined')
        console.log(x);
    else if (debug) {
        debug.value += x + '\n';
        debug.scrollTop = debug.scrollHeight;
    }
};

/*  =FUNCTIONS
----------------------------------------------------------------------------- */
var commentsPanel = function(){
	
	var myCommentLink = jQuery('#commentLink');
	var myCommentsArea = jQuery('#commentsArea');
	
	if ((myCommentLink) && (myCommentLink.length != 0)){
	
		// adds the link on the commentLink
		myCommentLink.html(
			'<a href="#">commentaires (' +
			myCommentLink.html().toLowerCase().split('commentaires (')[1].split(')')[0] +
			')</a>'
		);
		
		var myCommentLinkA = myCommentLink.children('a:first');
		
		// comments panel open or not
		if (window.location.toString().indexOf('comments') != -1){
			
			myCommentLinkA.addClass('on');
			myCommentsArea.show();
			
		}
		else {
			
			myCommentsArea.hide();
			
		}
		
		// onclick
		myCommentLinkA.bind('click', function(){
			
			if (myCommentLinkA.hasClass('on')){
				
				myCommentLinkA.removeClass('on')
				myCommentsArea.hide();
				window.location.hash = '#nocom';
				
			}
			else{
				
				myCommentLinkA.addClass('on')
				myCommentsArea.slideDown('slow');
				window.location.hash = '#comments';
				
			}
			
			myCommentLinkA.blur();
			return false;
			
		});
	}
}

var closePopin = function(){
	
	// close button
	jQuery('#closeButton, #mask').bind('click', function(){
		
		jQuery('#popinContainer, #konamiContainer, #mask').remove();
		return false;
		
	});
	
}

var commentSubmit = function(){

	jQuery('#errorMsg').hide();
	
	jQuery('#commentForm').submit(function(){
		
		var hasError = false;
		jQuery('.required, #spam1').parent('p').removeClass('error');
		jQuery('#errorMsg').hide();
		
		jQuery('.required').each(function(){
			
			var myVal = jQuery(this).val();
			
			if (!/[a-zA-Z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöùúûüýÿ]/.test(myVal)){ 
				
				jQuery(this).parent('p').addClass('error');
				hasError = true;
				
			}
		});
		
		log(jQuery('#spam1').attr('checked'))
		
		// spam filter à l'arrache
		if (jQuery('#spam1').attr('checked') == true){
			
			jQuery('#spam1').parent('p').addClass('error');
			hasError = true;
			
		}
		
		if (hasError) {
			
			jQuery('#errorMsg').show();
			return false;
		}
		
		else{

			//if (document.getElementsByTagName('html')[0].className.indexOf('msie6') == -1){
			
				// Loader
				jQuery('body').prepend('<div id="mask"></div><div id="popinContainer"><div id="popinContent"><a href="#" id="closeButton" title="fermer"></a><img src="img/skin/ajax-loader.gif" alt="postage en cours..." id="ajaxLoad" /></div></div>');
				
				closePopin();
				
				// AJAX send
				s = jQuery(this).serialize();
				myAction = jQuery(this).attr("action");
				
				jQuery.ajax({ 
					type: "POST", 
					data: s, 
					url: myAction, 
					error: function(myObject, textStatus, errorThrown){
						//alert('Ca a foiré. Pour la peine tu te tapes une sale alerte Javascript du siècle dernier !')
					},
					success: function(retour){
						jQuery('#ajaxLoad').remove();
						jQuery('#popinContent').addClass('merci');
						jQuery('#popinContent').append('<p>Ton commentaire a bien été posté.</p>');
						jQuery('#commentsArea').load(window.location.href.toString().split('#comments')[0] + " #commentsArea", function(){ 
							
							commentSubmit(); 
							
						});
					}
				});
				
				return false;
				
			//}
		
		}
		
	});
	
}

var allEpisodes = function(){
	
	// ul >> select
	jQuery('#allEpisodes ul').after('<form action="#"><select id="allEpisodesSelect"></select></form>');
	
	jQuery('#allEpisodesSelect').prepend('<option value="0" selected="selected">- Accès direct à la planche... -</option>');
	
	jQuery('#allEpisodes li a').each(function(){
		
		if (jQuery(this).hasClass('on')) var myOn = ' class="current"';
		else var myOn = '';
		jQuery('#allEpisodesSelect').append('<option value="' + jQuery(this).attr('href') + '"'+ myOn +'>' + jQuery(this).text() + '</option>');
	
	});
	
	jQuery('#allEpisodes ul, #allEpisodesLink').remove();
		
	jQuery('#allEpisodesSelect').clone().prependTo("#episodesStuff");
	
	jQuery('#allEpisodesSelect').bind('change', function(){
		
		if (jQuery(this).attr('value') != 0) window.location = jQuery(this).attr('value');
		
	});
	
}

var konami = function(){
	
    var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";  
    
	// Konami call
	if ( window.addEventListener ) {
            window.addEventListener("keydown", function(e){  
                kkeys.push( e.keyCode );  
            if ( kkeys.toString().indexOf( konami ) >= 0 )  
                konamiMe();
        }, true);
    }
    
    // Konami funk!
	var konamiMe = function(){
		
	    if (jQuery('#konamiContainer').length == 0){
	    
    	    jQuery("html,body").animate({ scrollTop: 0 }, 1000, 'swing');
    	    
    		// Loader
    		jQuery('body').prepend('<div id="mask"></div><div id="konamiContainer"><div id="konamiContent"><a href="#" id="closeButton" title="fermer"></a><p>Une casserole honteuse de Demain J’arrête dans la Konami Zone, ça vous dit ? </p><p>À la fin du millénaire dernier, j’improvisai sur le dos d’une liste de courses cette planche de BD hommage aux excès de jeunesse d’alors… Bien des années (et bien des planches) plus tard, de ce terreau ingrat naissait <strong>Demain J’arrête</strong> sous la forme que vous connaissez aujourd’hui. Vous avez sous les yeux le paléo-Poutcham, soyez gentils avec lui !</p><img src="img/data/konami/tarlouzes.jpg" alt="" height="902" width="650" /></div><div id="konamiFoot"></div></div>');
    		
    		var showMask = function(mask){
    		    mask.animate({ opacity: 1 }, duration, 'linear', function(){ hideMask(mask); });
    		}
    		
    		var hideMask = function(){
    		    mask.animate({ opacity: 0.5 }, duration, 'linear', function(){ showMask(mask); });
    		}
    		
    		var mask = jQuery('#mask'),
    		    duration = 1000;
    		
    		hideMask(mask);
    		
    		closePopin();
    		kkeys = [];
    		
    	}
		
	}
	
}

/*  =WINDOW.ONLOAD
----------------------------------------------------------------------------- */
jQuery(document).ready(function(){
    
    // Functions
	commentsPanel();			// replier/déplier le panneau de commentaires
	commentSubmit();			// vérif du formulaire de commentaires
	allEpisodes();				// popin épisodes
	konami();                   // muhuhu
	
});
