/*------------------------------------------------------------------------------
    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="#"> (' +
			myCommentLink.html().toLowerCase().split('(')[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, #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('#allEpisodes li a').each(function(){
		
		if (jQuery(this).hasClass('on')) var myOn = ' selected="selected"';
		else var myOn = '';
		jQuery('#allEpisodesSelect').append('<option value="' + jQuery(this).attr('href') + '"'+ myOn +'>' + jQuery(this).text() + '</option>');
	
	});
	
	jQuery('#allEpisodes ul').remove();
	
	// click
	jQuery('#dateStuff a').bind('click', function(){
		
		jQuery('body').prepend('<div id="mask"></div><div id="popinContainer"><div id="popinContent" class="episodes"><a href="#" id="closeButton" title="fermer"></a></div></div>');
		
		closePopin();
				
		jQuery('#allEpisodesSelect').clone().prependTo("#popinContent");
		jQuery('#allEpisodesSelect').bind('change', function(){
			
			window.location = jQuery(this).attr('value');
			
		});
		
		jQuery(this).blur();
		return false;
		
	});
	
}

/*  =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
	
});
