// Define page here
popups = {
	alertes: '/nc/alertes.html',
	newsletters: '/nc/newsletters.html',
	compte: '/nc/compte.html',
	rdv: '/nc/rdv.html',
	rdvSchedule: '/nc/rdv-horaires.html',
	personalInformations: '/nc/infos.html',
	faq: '/nc/faq.html',
	customFaq: '/nc/faq_question.html',
	agendaInscription: '/nc/agenda_inscription.html',
	agendaAccompagnateur: '/nc/agenda_accompagnateur.html'
};

// Define Form Validation Rules here
var createAccountRules = {
	rules: {
		lastName: 'required',
		firstName: 'required',
		emailAddress: {
			required: true,
			email: true
		},
		mobile: 'mobilePhoneNumber',
		mdp: 'required',
		new_mdp: 'required',
		conf_mdp: {
			equalTo: "#new_mdp"
		},
		conditions: 'required',
		description: 'required',
		question: 'required',
        "tx_pitatelieres_pi1[email]": {
			required: true,
			email: true
		},
        "tx_pitatelieres_pi1[prenom]": 'required',
        "tx_pitatelieres_pi1[nom]": 'required',
        "tx_pitatelieres_pi1[telephone]": 'mobilePhoneNumber',
        "tx_pitatelieres_pi1[plage]": 'required',
        "tx_pitatelieres_pi1[client]": 'required',
        "tx_pitatelieres_pi1[code]": 'required',
		"FE[fe_users][first_name]": 'required',
		"FE[fe_users][last_name]": 'required',
		"FE[fe_users][email]": 'required',
		"FE[fe_users][telephone]": 'required',
		"FE[fe_users][password]": 'required',
		"FE[fe_users][password_again]": {
			equalTo: "#tx-srfeuserregister-pi1-password_again"
		}
	},
	messages: {
		lastName: "Veuillez entrer votre nom",
		firstName: "Veuillez entrer votre prénom",
		emailAddress: "E-mail non valide",
		mobile: "Numéro de téléphone invalide",
		conditions: "Vous devez acceptez les conditions générales d'utilisation du studio SFR",
		mdp: "Invalide",
		new_mdp: "Mot de passe non valide",
		conf_mdp: "Confirmation non valide",
		description: "Veuillez saisir une description",
		question: "Veuillez saisir une question",
		"FE[fe_users][first_name]": "Veuillez entrer votre nom",
		"FE[fe_users][last_name]": "Veuillez entrer votre prénom",
		"FE[fe_users][email]": "E-mail non valide",
		"FE[fe_users][telephone]": "Numéro de téléphone invalide",
		"FE[fe_users][password]": "Invalide",
		"FE[fe_users][password_again]": "Confirmation non valide",
        "tx_pitatelieres_pi1[email]": "E-mail non valide",
        "tx_pitatelieres_pi1[prenom]": "Veuillez entrer votre prénom",
        "tx_pitatelieres_pi1[nom]": "Veuillez entrer votre nom",
        "tx_pitatelieres_pi1[telephone]": "Numéro de téléphone invalide",
        "tx_pitatelieres_pi1[plage]": "Choisissez une plage horaire",
        "tx_pitatelieres_pi1[client]": "Choisissez votre statut client",
        "tx_pitatelieres_pi1[code]": "Veuillez entrer le code de la soirée"
	}
};

var formInsAgendaData = {
    memorize : []
};


var connected = false;
function connecter(type) {
	if(type == "yes")
		connected = true;
	else
		connected = false;
}

// PRELOAD FORM DEPENDENCIES
function handleLoader(){
	var loader = jQuery('<div id="loader"><img src="/fileadmin/www.lestudiosfr.fr/templates/img/ajax-loader.gif" alt="Loading" /></div>').hide().appendTo('body');
	jQuery().ajaxStart(function() { loader.show(); }).ajaxStop(function() { loader.hide(); });
}


// REQUIRED VALIDATION RULES
jQuery.validator.methods.mobilePhoneNumber = function(value) {
	var mobileNumber = new RegExp("^[0]{1}[6]{1}[0-9]{8}$", "i");
	if (value.match(mobileNumber))
		return true;
	else
		return false;
};

jQuery.validator.methods.pwdStr = function(value, element) {
	var passWordExp = new RegExp("^[A-Za-z0-9]{" + (element.value.length || 1) + "}$", "i");
	if (value.match(passWordExp)) {
		if ((element.id || element.name) == 'mdp') {
			return true;
		}
		else {
			if (jQuery('#mdp').val() == jQuery('#conf_mdp').val()) {
				return true;
			}
			else {
				return false;
			}
		}
	}
	else
		return false;
};

/* JQUERY SPLIT LINKS PLUGIN
 * @desc: Split the url to get the page name. Page name = Section classname
 * @type: string
 * @param str - {String} : href string to split
 * @returns: target string or FALSE
 */
jQuery.splitLink = function(str) {
	if (!str) return false;
	var dir = str.split('/');
	return dir[dir.length-1].split('.')[0];
};

/* JQUERY POPUP BINDERS
* @desc: Binders to set to the popup. Use it with the ajaxx callback
* @param bg - {String} : background id selector
* @type: void
*/
jQuery.fn.setPopupBinders = function(bg, callback) {
	var curSection = jQuery(this);

	// Thickbox
	tb_init('a.thickbox');
	
	// Close Link
	jQuery('.close a', curSection).click(
		function() {
			curSection.setPopup(0, '#background');
			return false;
		}
	);
	jQuery("#backfull").click(
		function() {
			curSection.setPopup(0, '#background');
		}
	);

	// Tabs Links
	jQuery('.nav a', curSection).click(
		function() {
			var newPopup = curSection.setPopup(0, '#background', jQuery(this).attr('href'));
			return false;
		}
	);

	// Alertes Template
	var alertForm = jQuery('.alertesForm', curSection);
	if (alertForm.size() > 0) {
		if(jQuery('form:eq(0)', alertForm).size() > 0){
			createAccountRules.submitHandler = function(form) {
				jQuery(form).ajaxSubmit({ target:'.rod' });
			};
			jQuery('form:eq(0)', alertForm).validate(createAccountRules);
		}
	}
	
	
	// Account Template
	var accountForm = jQuery('.compteForm', curSection);
	if (accountForm.size() > 0 && jQuery('.submitNewsletters', curSection).size() == 0 && jQuery('.creer_compte', curSection).size() == 0 && jQuery('.agenda_inscription_intro', curSection).size() == 0) {
		//console.log("mod account");
		if(jQuery('form:eq(0)', accountForm).size() > 0){
			createAccountRules.submitHandler = function(form) {
				jQuery(form).ajaxSubmit({
					success:function(data){
						jQuery('#result .rod p').addClass("confirm").html( jQuery(data) );
					}
				});
			};
			jQuery('form:eq(0)', accountForm).validate(createAccountRules);
		}
		
		if(jQuery('form:eq(1)', accountForm).size() > 0){
			createAccountRules.submitHandler = function(form) {
				jQuery(form).ajaxSubmit({
					success:function(data){
						jQuery('#result .rod p').addClass("confirm").html( jQuery(data) );
					}
				});
			};
			jQuery('form:eq(1)', accountForm).validate(createAccountRules);
		}
	// Create Account Template
	} else if (accountForm.size() > 0 && jQuery('.creer_compte', curSection).size() == 1) {
		if(jQuery('form:eq(0)', accountForm).size() > 0){
			createAccountRules.submitHandler = function(form) {
				jQuery(form).ajaxSubmit({
					beforeSubmit: function(formData, jqForm, options){
						// Add button for post submit > php
						formData.push({ name: "tx_srfeuserregister_pi1[submit].x", value: 77 });
						formData.push({ name: "tx_srfeuserregister_pi1[submit].y", value: 15 });
						
						var queryString = $.param(formData);
						
						return true;
					},
					success:function(data){
						jQuery('.rod').addClass("confirm").html( jQuery('.rod', data).html() );
						jQuery('.compteForm').html( jQuery('.compteForm', data).html() );
					}
				});
				
				return false;
			};
			jQuery('form:eq(0)', accountForm).validate(createAccountRules);
		}
	// Agenda inscription Template
	} else if (accountForm.size() > 0 && jQuery('.agenda_inscription_intro', curSection).size() == 1) {
		if(jQuery('form:eq(0)', accountForm).size() > 0){
		    
		    var formsInsAgendaEvent = function() {
                jQuery('#dynId input[type=image]').bind('click',function(e){
                    formInsAgendaData.memorize = [];
                    formInsAgendaData.memorize.push({ name: this.name+".x", value: 77 });
                    formInsAgendaData.memorize.push({ name: this.name+".y", value: 15 });
                });
            }();
            
            var callbackForSecondForm = function(newForm) {
                jQuery('form:eq(0)', accountForm).validate(createAccountRules);
                var newForm = $('.compteForm form');
				if (newForm.length > 0) {
				    newForm.find('input[type=image]').unbind('click');
				    newForm.find('input[type=image]').bind('click',function(e){
                        var sentData = '';
                        var blockExec = false;
                        $(newForm).find(':text').each(function(){
                            if (this.value == '') {
                                document.getElementById('error').style.display = 'block';
                                blockExec = true;
                                e.preventDefault();
                                return false;
                            }
                        });
                        
                        if (blockExec) {
                            e.preventDefault();
                            return false;
                        }
                        else {
                            $(newForm).find('input:not([type=image]), select, textarea').each(function(){
                                var current = $(this);
                                var val  = encodeURIComponent(current.val());
                                var name = current.attr('name');
                                if (this.type == 'radio' || this.type == 'checkbox') {
                                    if (this.checked) {
                                        sentData += name+'='+val+'&';
                                    }
                                } 
                                else if (this.type != 'radio' || this.type != 'checkbox') {
                                    sentData += name+'='+val+'&';
                                }
                                else {
                                    sentData = '';
                                }
                            });
                            sentData += 'tx_pitatelieres_pi1[valider].x=77&tx_pitatelieres_pi1[valider].y=15'
    				        $.ajax({
    				            type: 'POST',
    				            url : newForm[0].action,
    				            data : sentData,
    				            cache: false,
    				            success: function(data){
                                    // console.log(data);
                                    jQuery('.rod').addClass("confirm").html( jQuery('.rod', data).html() );
                                    jQuery('.compteForm').html( jQuery('.compteForm', data).html() );
    				            }
    				        });
                        }
                        

                        e.preventDefault();
                        return false;
				    });
				}
            }
            
			createAccountRules.errorContainer = "#error";
			createAccountRules.submitHandler  = function(form) {
				jQuery(form).ajaxSubmit({
					beforeSubmit: function(formData, jqForm, options){
						// Add button for post submit > php
                        formData.push(formInsAgendaData.memorize[0]);
                        formData.push(formInsAgendaData.memorize[1]);
						var queryString = $.param(formData);
						return true;
					},
					success:function(data){
						jQuery('.rod').addClass("confirm").html( jQuery('.rod', data).html() );
						jQuery('.compteForm').html( jQuery('.compteForm', data).html() );
						var newForm = jQuery('.compteForm form');
                        setTimeout(function(){
                            callbackForSecondForm(newForm);
                        },500);
					}
				});

				return false;
			};
			
			jQuery('form:eq(0)', accountForm).validate(createAccountRules);
		}
	// Newsletters Template
	} else if (accountForm.size() > 0 && jQuery('.submitNewsletters', curSection).size() == 1) {
		//console.log("newsletters");
		if(jQuery('form:eq(0)', accountForm).size() > 0){
			jQuery('form:eq(0)', accountForm).ajaxForm();
			
			jQuery('form:eq(0)', accountForm).submit(function(){
				jQuery(this).ajaxSubmit({
					success:function(data){
						jQuery('#result .rod').addClass("confirm").html( jQuery('.rod', data).html() );
					}
				});
				return false; 
			});
		}
	}
	
	// RDV Template
	var rdvContent = jQuery('.formulaireRDV', curSection);
	if (rdvContent.size() > 0) {
		if(jQuery('form:eq(0)', rdvContent).size() > 0){
			createAccountRules.submitHandler = function(form) {
				jQuery(form).ajaxSubmit({
					target:'#content',
					success:function(){
						jQuery("#background").removeClass().addClass("rdv2");
						jQuery("#content").setPopupBinders('#background');
					}
				});
			};
			jQuery('form:eq(0)', rdvContent).validate(createAccountRules);
		}
		
		
	}
	
	// RDV de base
	var rdvContentBase = jQuery('.rod', curSection);
	if(rdvContentBase.size() > 0) {
		jQuery(".rod .calendar a, .rod .listRDV a").click(function(){
			var newPopup = curSection.setPopup(popups.rdv, '#background', jQuery(this).attr('href'));
			return false;
		});
	}
	
	// RDV list
	var rdvList = jQuery('.listRDV', curSection);
	if (rdvList.size() > 0) {
		jQuery(".listRDV").jScrollPane({ scrollbarWidth: 9, scrollbarMargin: 0, dragMinHeight: 16, dragMaxHeight: 16 });
	}
	
	// FAQ Template
	var faqContent = jQuery('.faqList', curSection);
	if (faqContent.size() > 0) {
		var current;
		
		jQuery(".faqList").jScrollPane({ scrollbarWidth: 9, scrollbarMargin: 0, dragMinHeight: 16, dragMaxHeight: 16 });
		
		jQuery(".item").click(function(e){
			currentElt = this;
			
			jQuery(".item").removeClass("itemOn");
			
			if( jQuery(this).next("p").is(":visible") )
				jQuery(this).removeClass("itemOn");

			else
				jQuery(this).addClass("itemOn");
			
			jQuery(current).animate({ height: "toggle" });
			
			current = jQuery(this).next("p");
			
			jQuery(this).next("p").animate({ height: "toggle" }, function(){
				jQuery(".faqList").jScrollPane({ scrollbarWidth: 9, scrollbarMargin: 0, dragMinHeight: 16, dragMaxHeight: 16, animateTo: true });
				
				if( jQuery(".faqList .wrap").height() > 188 ){
					linkTopY = jQuery(currentElt)[0].offsetTop;
					jQuery(".faqList")[0].scrollTo(linkTopY-2, 0);
				}
			});
			
			return false;
		});
		
		jQuery(".buttonQuestion a").click(function(){
			jQuery('#content').setPopup(popups.customFaq, '#background');
			return false;
		});
	}
	
	// FAQ Template Question
	var faqQuestion = jQuery('.question', curSection);
	if (faqQuestion.size() > 0) {
		if(jQuery('form:eq(0)', faqQuestion).size() > 0){
			
			createAccountRules.submitHandler = function(form) {
				jQuery(form).ajaxSubmit({
					target:'#result',
					success:function(){
						jQuery("#content").setPopupBinders('#background');
					}
				});
			};
			jQuery('form:eq(0)', faqQuestion).validate(createAccountRules);
		}
	}
	// **** SET ADDITIONAL TEMPLATES RULES HERE ****

	if(callback)
		callback();
};

/* JQUERY LOAD POPUP PAGE
* @desc: Ajaxx Popup loader / unloader
* @param page {String} - page location to load or set to 0 to unload the current
* @param bg {String} - background id selector
* @param newPage {String} - page location to load
* @type: void
*/
jQuery.fn.loadPopupPage = function(page, bg, callback) {
    var curSection = jQuery(this);
    var theData = {};
    if (typeof page == 'object') {
        var pageURL = page.url;
        delete page.url;
        if (page.data) {
            theData[page.data.split('=')[0]] = page.data.split('=')[1];
        } 
    }
    else {
        pageURL = page;
    }
    if (typeof theData == 'undefined') {
        theData = null;
    }
    
    var checkURLObject = function() {
        var size = 0, key;
        for (key in theData) {
            if (theData.hasOwnProperty(key) && key.slice(-5) == '.html' ) {
                pageURL = key;
            }
        }
        return size;
    }();
    
    
    Object.size = function(obj) {
        var size = 0, key;
        for (key in obj) {
            if (obj.hasOwnProperty(key) && typeof key != 'undefined') {
                size++;
            }
        }
        return size;
    };

    var execOnLoad = function(current){
		jQuery(curSection).show();
		jQuery("#backfull").click(
			function() {
				curSection.setPopup(0, '#background');
			}
		);
	
    	//test connect
    	if((page == popups.faq) && (!connected)) {
    		jQuery('.buttonQuestion').hide();
    	}

    	// center divs
    	var marginLeft = parseInt(jQuery(bg).css("width")) / 2;
    	jQuery(bg).css("margin-left","-"+marginLeft+"px");
    	jQuery(current).css("margin-left","-"+marginLeft+"px");

    	var marginTop = parseInt(jQuery(bg).css("height")) / 2;
        if(page == popups.compte)
            marginTop = (marginTop - 40);
    	jQuery(bg).css("margin-top","-"+marginTop+"px");
    	jQuery(current).css("margin-top","-"+marginTop+"px");

    	// center divs
    	if(jQuery(".listRDVContainer").size() > 0) jQuery(bg).removeClass().addClass("rdv2"); // Special case list RDV

    	jQuery(bg).show();
    	jQuery(current).fadeIn(function(){
			jQuery(current).setPopupBinders(bg, callback);
		});
    };

    if (Object.size(theData) > 0 ) {
        // POST
        jQuery(this).load(
            pageURL,
            theData,
            function(){
                var current = this;
                execOnLoad(current);
            }
        );
    } else {
        // GET
        jQuery(this).load(
            pageURL,
            function(){
                var current = this;
                execOnLoad(current);
            }
        );
    }
};

/* JQUERY POPUP
* @desc: Ajaxx Popup initializer
* @param page {String} - page location to load or set to 0 to unload the current
* @param bg {String} - background id selector
* @param newPage {String} - page location to load
* @type: void
*/
jQuery.fn.setPopup = function(page, bg, newPage, callback) {
    var pageObj =  {};
	switch (page) {
		case 0: // Unload popup and load the new one if need be
		    var curSection = jQuery(this);
			if (!newPage) jQuery('a', curSection).unbind('click');
			
			jQuery(this).fadeOut(function() {
				if (newPage && typeof newPage == 'string') {
						jQuery(this).html('');
						jQuery(this).setPopup(newPage, '#background');
				}
			});
			
			jQuery(bg).hide();
			
			if (!newPage) {
				jQuery("#backfull").hide();
				if (jQuery('.resolution1').size() > 0)
					jQuery("#flashContent").animate({bottom:'50%'}, 500);
          		else
              		jQuery("#flashContent").animate({bottom:'0px'}, 500);
			}
		break;

		default: // Load a new popup
		
		    var curSection = jQuery(this);
			var curSectionClassName = jQuery.splitLink(page);

			jQuery("#backfull").show();
			jQuery(bg).removeClass().addClass(curSectionClassName);
			curSection.removeClass().addClass(curSectionClassName + 'Content');
			
			var NAS = true;
			
			pageObj.url  = page;
			
			if(newPage != null && typeof newPage == 'string' && newPage.split('news_id'[0]).length > 0 ) {
				pageObj.data = newPage;
				NAS = false;
			}
			
			if(NAS && newPage != null && typeof newPage == 'string' && newPage.split('news_id'[0]).length <= 0 ) {
				pageObj.url = newPage;
			}else {
				jQuery("#flashContent").animate(
					{bottom:'-' + jQuery('#mainContainer').height() + 'px'},
					500
				);
			}
			curSection.loadPopupPage(pageObj, bg, callback);
		break;
	}
};

jQuery(document).ready(function(){ handleLoader(); });

var debug = false;

function launchPopup(name) {
	if(debug){
		jQuery("#backfull").show();
		
		jQuery("#backfull").click(function(){
			jQuery("#backfull").hide();
			return false;
		});
	} else {
	    var gparam = '';
	    var gname  = name.split('?')[0];
	    var gparam = name.split('?')[1];
        var gJSON  = {};
        if (typeof gparam != "undefined" && gparam.length > 0) {
            var gjName    = gparam.split('=')[0];
            var gjValue   = gparam.split('=')[1];
            gJSON[gjName] = gjValue;            
        }
        
		jQuery('#content').setPopup(popups[gname], '#background', gparam);
	}
}



