jQuery(document).ready(function() {
	if (top.location == self.document.location){
		initHome();
	}
	initPopup();
	container = jQuery('#widget-container');
});

var container;

function initHome() {
	jQuery('head').append('<link rel="stylesheet" type="text/css" media="screen" href="' + tPath + '/home.css" />');
	jQuery('body').prepend('<div id="bgi"><div><img src="' + tPath + '/img/bg-img.jpg" alt="" /></div></div><div id="gdlogo"></div><div class="cbook warning">' + msg + '</div>');
	jQuery('body').append('<div id="reflexion"></div>');
	Cufon.replace('#widget-body .warning' , { fontFamily: 'cbook' , hover: true });
};

function initPopup() {
	jQuery("a[href='#w-popup']").click(function(event){
		event.preventDefault();
		hidePopup();
		loadData(jQuery(this));
	});
};

function reinitPopup() {
	container.find('#popup a[href="#w-popup"]').click( function(event) {
		event.preventDefault();
		hidePopup();
		loadData(jQuery(this));
	});
};

function loadData( el ) {
	var datas = el.attr('rel').split(',');
	jQuery.ajax({
		type: 'POST',
		url: tPath + '/ajax_popup.php',
		data: 'id=' + datas[0],
		success: function(post) {
			showPopupBg();
			container.append(post);
			container.find('#popup').css({
				'width' : '100%',
				'height' : container.height() - container.find('#footer').height() + 'px',
				'opacity' : 0,
				'display' : 'block'
			}).animate({ 'opacity' : 1 }, 150, function() { removeFilter(jQuery(this)); } );
			if ( datas[1] == 'scroll' ) {
				container.find('#popup #pop-content').css({ 'height' : '180px', 'padding-right' : '10px', 'padding-bottom' : '20px' });
				fleXenv.fleXcrollMain("pop-content");
				Cufon.replace('#popup #pop-content h1' , { fontFamily: 'cbook' , hover: true });
			}
			if ( datas[1] == 'galerie' || datas[1] == 'video' ) {
				container.find('#popup #pop-marg, #popup #pop-content, #popup #pop-content p').css({ 'padding' : 0, 'margin' : 0 });
			}
			if ( datas[1] == 'galerie' ) {
				initGallery( container.find('#popup') );
			}
			Cufon.replace('#popup .cbook, #popup h2, #popup h3, #popup h4, #popup h5, #popup h6' , { fontFamily: 'cbook' , hover: true });
			Cufon.replace('#popup .gill' , { fontFamily: 'glight' , hover: true });
			reinitPopup();
			container.find('#popup #pop-close').click( function(event) { event.preventDefault(); hidePopup(); } );
			
			if ( container.find('form').hasClass('clipboard') ) {
				copyToClipboard( container.find('form.clipboard') );
			}
			
			if ( datas[1] == 'validate' || datas[2] == 'validate' ) {
				initForm( datas[0] );
			}
		}
	});
};

function showPopupBg() {
	container.append('<div id="bg-popup"></div>');
	jQuery('#bg-popup')
		.css({ 'width' : '100%', 'height' : container.height() - 73 + 'px', 'background-color' : '#FFF', 'opacity' : 0, 'position' : 'absolute', 'top' : 0, 'left' : 0, 'z-index' : 40 })
		.fadeTo( 150, 0.95 );
};

function hidePopup() {
	container.find('#bg-popup').fadeOut( 150, function() { removeElement( jQuery(this) ); } );
	container.find('#popup').fadeOut( 150, function() { removeElement( jQuery(this) ); } );
	currentScroll = 0;
};

function removeElement( el ){
	el.remove();
};

var copyThis;
function copyToClipboard( form ) {
	copyThis = form.find('textarea.ctc');
	var ctCode = "<object id='clipboard' data='" + tPath + "/dt-copier.swf' width='150' height='35' type='application/x-shockwave-flash' data='" + tPath + "/dt-copier.swf'><param name='allowScriptAccess' value='always' /><param name='allowFullScreen' value='false' /><param name='movie' value='" + tPath + "/dt-copier.swf' /><param name='quality' value='high' /><param name='wmode' value='transparent' /><param name='flashvars' value='callback=cTc' /></object>";
	var button = form.find('button#copy');
	form.append(ctCode);
	jQuery('#clipboard').css({
		'position' : 'absolute',
		'left' : button.position().left,
		'top' : button.position().top + 5,
		'z-index' : 70
	});
};

function cTc() {
	var s = copyThis.val();
	if (window.clipboardData)
		window.clipboardData.setData('text', s);
	else
		return (s);
};

/*--FORM--*/
function initForm( datas ) {
	var form = jQuery("#form-" + datas);
	if ( datas == 'w-pop-inscription' ) {
		jQuery('form#form-inscription').submit( function() {
			validInscription( jQuery(this) );
			return false;
		});
		jQuery('form#form-login').submit( function() {
			validInscription( jQuery(this) );
			return false;
		});
	} else {
		form.submit( function() {
			form.find('.a-response').remove();
			if ( form.attr('id') == 'form-w-pop-compte' ) {
				validCompte( form );
			} else if ( form.attr('id') == 'form-pop-mdprecup' ) {
				validLost( form );
			} else {
				validateForm( form );
			}
			return false;
		});
	}
	if ( form.find('a.delete-account') ) {
		var deLink = form.find('a.delete-account');
		deLink.attr('href' , deLink.attr('href') + '&parrain_id=' + parrainID );
	}
};

function validateForm( form ) {
	if ( form.find('input.required').val() != '' ) {
		var correctMail = true;
		form.find('input.email[value!=""]').each( function() {
			if ( !checkMail( jQuery(this).val() ) ) correctMail = false;
		});
		if (correctMail) {
			validForm( form );
		} else {
			errorMsg( form, 'Veuillez v&eacute;rifier les adresses e-mail saisies' );
		}
	} else {
		errorMsg( form, 'Veuillez entrer au moins une adresse e-mail' );
	}
};

function validLost( form ) {
	if ( form.find('input.[name="mail"]').val() == '' ) {
		errorMsg( form, 'veuillez saisir un mail' );
	} else {
		jQuery.ajax({
			type: 'POST',
			url: tPath + '/trait-mdprecup.php',
			data: form.serialize(),
			success: function( data ) {
				form.append( '<div class="form-error a-response">' + data + '</div>' );
			}
		});
	}
};


function checkMail( mail ) {
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(mail)) {
		return true;
	} else {
		return false;
	}
}

function errorMsg( form, msg ) {
	form.append('<div class="form-error a-response">' + msg + '</div>');
}

function validForm( form ) {
	jQuery.ajax({
		type: 'POST',
		url: tPath + '/trait-parrainnage.php',
		data: form.serialize(),
		success: function() {
			form.children().fadeTo( 150, 0 );
			form.append( validMsg );
			form.find('#form-valid').css({
				'position' : 'absolute',
				'opacity' : 0,
				'display' : 'block',
				'width' : form.width()  + 'px',
				'height' : form.height() + 50 + 'px',
				'top' : 0,
				'left' : 0
			})
			.animate({ 'opacity' : 1 })
			.find('#paragain').click( function(event) {
				event.preventDefault();
				jQuery('#form-valid').animate({ 'opacity' : 0 }, function() { removeElement(jQuery('#form-valid')) } );
				form.children().fadeTo( 150, 1 );
				form.find('input[type="text"]').val( '' );
			});
		},
		error: function() {
			form.append('<div class="form-error a-response">' + 'une erreur est survenue, merci de r&eacute;it&eacute;rer ult&eacute;rieurement' + '</div>');
		}
	});
}

var validMsg = '<div id="form-valid" class="a-response"><h3>L\'inscription de vos filleuls &agrave; bien &eacute;t&eacute; prise en compte.<br /><a id="paragain" href="">Inscrivez d\'autres ami(e)s</a> et augmentez vos chances d\&ecirc;tre tir&eacute; au sort</h3></div>';

function validCompte( form ) {
	jQuery.ajax({
		type: 'POST',
		url: tPath + '/w-trait-moncompte.php',
		data: form.serialize(),
		success: function( result ) {
			if ( result == 'reload' ) {
				reloadPage();
			} else {
				form.find('#user_infos').empty().append( result );
				Cufon.replace('#popup #user_infos .cbook', { fontFamily: 'cbook' });
				Cufon.replace('#popup #user_infos .gill', { fontFamily: 'glight' });
				form.append('<div class="form-valid" class="a-response"><strong>Compte mis a jour</strong></div>');
				form.find('.form-valid').css({
					'position' : 'absolute',
					'color' : '#000',
					'margin-top' : '3px',
					'right' : '5px' })
				.delay(2000).fadeOut(1000, function() { removeElement(jQuery('this')) } );
			}
		}
	});
};

/*--INSCRIPTION--*/
function validInscription ( form ) { 
	container.find('span.rederror').empty();
	if ( form.find('input.required').attr('type') == 'checkbox' ) {
		if ( form.find('input.required:checked').val() != 1 ) {
			container.find('span.rederror').append('Veuillez accepter le r&egrave;glement du jeu concours');
		} else {
			sendInscription( form )
		}
	} else {
		sendInscription( form )
	}
};

function sendInscription( form ) {
	form.find('input[name="parrain_id"]').val( parrainID );
	jQuery.ajax({
		type: 'POST',
		url: tPath + '/w-trait-logorreg.php',
		data: form.serialize(),
		success: function( data ) {
			if ( data == 'reload' ) {
				reloadPage();
			} else {
				container.find('span.rederror').append( data );
			}
		}
	});
};

function reloadPage() {
	jQuery.ajax({
		url: tPath + '/w-navbar.php',
		success: function( data ) {
			container.find('#navbar').empty().prepend( data );
			Cufon.replace('#widget-container #navbar a' , { fontFamily: 'cbook' , hover: true });
			initPopup();
		}
	});
	jQuery.ajax({
		type: 'GET',
		url: tPath + '/w-footer-content.php',
		data: 'parrain_id=' + parrainID,
		success: function( data ) {
			container.find('#footer').empty().prepend( data );
			initPopup();
		}
	});
	jQuery.ajax({
		url: tPath + '/page_widget_content.php',
		success: function( data ) {
			container.find('#widget-content').empty().prepend( data );
			Cufon.replace('#widget-container #widget-content .cbook' , { fontFamily: 'cbook' , hover: true });
			Cufon.replace('.cbooki' , { fontFamily: 'cbooki' });
			Cufon.replace('#widget-container #widget-content .gill' , { fontFamily: 'glight' , hover: true });
			hidePopup();
			initPopup();
		}
	});
}

function removeFilter( el ) {
	if (jQuery.browser.msie) {
		document.getElementById(jQuery(el).attr('id')).style.removeAttribute("filter");
	}
};

/* GALLERY */
var slidePrev;
var slideNext;
var galC;
var imgs;
var currentScroll = 0;

function initGallery( el ) {
	var globalC = el.find('#pop-marg');
	galC = globalC.find('#pop-content');
	imgs = galC.find('img');
	globalC.css({
		'position' : 'relative',
		'overflow' : 'hidden',
		'width' : '425px',
		'height' : '242px'
	});
	galC.css({
		'position' : 'absolute',
		'top' : 0,
		'left' : 0
	});
	imgs.css({
		'width' : globalC.width(),
		'height' : 'auto',
		'display' : 'block',
		'margin' : 0,
		'padding' : 0,
		'border' : 'none',
		'position' : 'absolute',
		'top' : 0,
		'left' : 0,
		'opacity' : 0,
		'z-index' : 0
	});
	imgs.eq(0).css({
		'opacity' : 1,
		'z-index' : 5
	});
	globalC.append('<a href="#" id="slide-prev"></a>');
	slidePrev = globalC.find('#slide-prev');
	globalC.append('<a href="#" id="slide-next"></a>');
	slideNext = globalC.find('#slide-next');
	checkGal();
	slidePrev.click( function(event) { event.preventDefault(); slidePrevImg(); } );
	slideNext.click( function(event) { event.preventDefault(); slideNextImg(); } );
};

function slidePrevImg() {
	imgs.eq(currentScroll).css({ 'z-index' : 0 }).delay(500).animate({ 'opacity' : 0 }, 0);
	currentScroll -= 1;
	checkGal();
	imgs.eq(currentScroll).css({ 'z-index' : 5 }).animate({ 'opacity' : 1 }, 500);
}

function slideNextImg() {
	imgs.eq(currentScroll).css({ 'z-index' : 0 }).delay(500).animate({ 'opacity' : 0 }, 0);
	currentScroll += 1;
	checkGal();
	imgs.eq(currentScroll).css({ 'z-index' : 5 }).animate({ 'opacity' : 1 }, 500);
}

function checkGal() {
	if (currentScroll == 0) {
		slidePrev.hide();
	} else {
		slidePrev.show();
	}
	if (currentScroll >= imgs.length - 1) {
		slideNext.hide();
	} else {
		slideNext.show();
	}
}
