/**
 * JavaScript library for the User
 */

function checkValuesFromPopup(ext){
	
	if(null != ext){
		var field_ext = ext;
	}else{
		var field_ext = '';
	}
	
	//variable to use in the function
	var url;
	var view = '';
	var email = checkSubscriptionData(field_ext);
	
	if(email != false){
		switch(ext){
			case '_preview':
			default:
				view = 'videos/preview_forbidden';
			break;
		}
		
		var parent_url = escape(parent.location);
		
		// set to url to check if the email address exists
		url = siteBaseUrl + view + '/checkemailexists?email=' + email + '&ajax=1';
	
		document.location = url;
	}
}

function checkSubscriptionData(field_ext){
	//check for a specific error in preview videos
	if (document.getElementById('error_from_validation')){
		document.getElementById('error_from_validation').style.display = 'none';
	}

	//get variable for the text boxes
	var last_name_input  = document.getElementById('last_name' + field_ext);
	var first_name_input = document.getElementById('first_name' + field_ext);
	
	//email should always be there, so get the value directly
	var email = document.getElementById('email' + field_ext).value;

	//if there is a field for last name, get the value and validate it
	// check the field nom
	if (null != last_name_input && last_name_input.value == 'votre nom') {
		document.getElementById('showError' + field_ext).innerHTML = 'Ecrivez votre nom, SVP';
		document.getElementById('showError' + field_ext).style.display = 'block';
		return false;
	}

	// check the field prenom
	if (null != first_name_input && first_name_input.value == 'votre prénom') {
		document.getElementById('showError' + field_ext).innerHTML = 'Ecrivez votre prénom, SVP';
		document.getElementById('showError' + field_ext).style.display = 'block';
		return false;
	}

	// check teh syntax of email address
	// TODO: Modify regex to validate french characters as correct (does not currently)
	var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/;

	if (regex.test(email) == false) {
		errMsg = (null != document.getElementById('invalid_email_error')) ? document.getElementById('invalid_email_error').value : 'Adresse email invalide';
		document.getElementById('showError' + field_ext).innerHTML = errMsg;
		document.getElementById('showError' + field_ext).style.display = 'block';
		return false;
	}
	
	return(email);
}

function validateEmail(email) {
	var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/;
	return regex.test(email);
}


/**
 * depending on the type of user display the right xslt in the lightbox 
 * @param type  // fm or vip 
 */
function displayDeleteUnsubLightBox(type, keepNewsletter) {
	tb_show(
			'Désinscrire',
			siteBaseUrl + 'profile/unsubscribedelete?type=' + type + '&keepnewsletter=' + keepNewsletter + '&lightbox=1&TB_iframe=true&modal=true&height=260&width=800');
}


/**
 * display in the same lightbox the message - email send on close redirect to
 * the profile
 */
function confirmationUnsubscribe(type, keepNewsletter){
	
	url = siteBaseUrl + 'profile/emailsent/';
	
	if('vip' == type){
		url += 'unsubscribe';
	} else if('fm' == type){
		url += 'sendconfirmemail?keepnewsletter=' + keepNewsletter;
	}
	self.location.href = url;
}

/**
 * Changes the images on the subscribe form from xx-idle to xx-checked, and adds
 * the hidden value member_type = 'vipmember' or 'freemember'
 */
 
function selectMemberType(member_type, type) {
	
	var vip = document.getElementById('divVIPBox');
	var free = document.getElementById('divFreeBox');
	

	/*
	 * hidden value on the form that is set based on what is picked. no default
	 * currently.
	 */
	var member_type_input = document.getElementById('member_type');
	

	/*
	 * membership-checkbox-idle.jpg -> membership-checkbox-checked.jpg and vice
	 * versa for the freemember one. If the other is checked, it will be
	 * unchecked, and vice versa. Gives the look of using a checkbox, although
	 * it is not a form element, instead an image that changes onClick() and the
	 * other image changes as well (if checked) to idle.
	 */
	if (member_type == 'vipmember') {
		vip.className = 'choice selected';
		free.className = 'choice';
		member_type_input.value = 'vipmember';
	} else if (member_type == 'freemember') {
		free.className = 'choice selected';
		vip.className = 'choice';
		member_type_input.value = 'freemember';
	}
	
	if (type == 'fm'){
		document.getElementById('creer_fm').style.display = 'inline';
		document.getElementById('creer_vip').style.display = 'none';
	}else if (type == 'vip'){
		document.getElementById('creer_fm').style.display = 'none';
		document.getElementById('creer_vip').style.display = 'inline';
	}
}

/**
 * 
 * checks if a connected user is subscribed or not to receive newsletter in both
 * cases use ajax call to subscribe or unsubscribe to newsletter if the user
 * unsubscribe confirm again before unsubscribing
 * 
 */
function subscribeUnsubscribeNewsletter(check_newsleter) {
	// get the curent time to added on the url for ajax call
	var stamp = new Date();
	stamp = stamp.getTime();

	// the user checked receive newsletter
	if (check_newsleter.checked == 1) {
		// change the db ; users table , is_subscribed = 1 where user_id = param
		// user_id
		// set the url to subscribe user to receive newsletter
		var url = siteBaseUrl + 'profile/editprofile/subscribenewsletter?is_subscribed=1&ajax=1&date="' + stamp + '"';
		AjaxGetData(url, getResult);
	} else {
		var answer = confirm(_('confirm_newsletter_unsubscribe'));
		if (answer) {
			// made an ajax call to update data base
			// change the db ; users table , is_subscribed = 1 where user_id =
			// param user_id
			var url = siteBaseUrl + 'profile/editprofile/subscribenewsletter?is_subscribed=0&ajax=1&date="' + stamp + '"';
			AjaxGetData(url, getResult);
		} else {
			check_newsleter.checked = 1;
		}
	}
}

 /**
	 * unsubscribeNewsletterNoAccount
	 * 
	 * if the user unchecks the 'subscribe newsletter' button on the signup
	 * page, do a best effort to preserve that selection. There is no account at
	 * that time and no way to keep the information through the call to paysite,
	 * so we will stick it in the session, and pray that when the user clicks on
	 * the link to login to their account, it's still there...
	 * 
	 * @param check_newsletter
	 *            $check_newsletter
	 * @return void
	 */
function unsubscribeNewsletterNoAccount(check_newsletter) {
	var stamp = new Date();
	stamp = stamp.getTime();

	// made an ajax call to update session
	if (check_newsletter.checked == 1) {
		// make an ajax call to update session
		var url = siteBaseUrl + 'profile/editprofile/subscribenewsletter?is_subscribed=1&ajax=1&date="' + stamp + '"';

	} else {
		// make an ajax call to update session
		var url = siteBaseUrl + 'profile/editprofile/subscribenewsletter?is_subscribed=0&ajax=1&date="' + stamp + '"';
	}
	AjaxGetData(url, getResult);
}

/**
 * function used to get the callback
 */
function getResult(data) {}

function openMessager(){

	var module = document.getElementById('module').value;
	var action = document.getElementById('action').value;
	var new_action = document.getElementById('new_action').value;
	var view = document.getElementById('view').value;
	var url_base = document.getElementById('url_base').value;
	var email = document.getElementById('email').value;
	var is_marqueblanche = document.getElementById('is_marqueblanche').value;
	var document_id = document.getElementById('document_id').value;
	
	if(checkEmail(email)){
		var url = url_base + 'd' + document_id + '/' + module + '/' + view + '/' + action + '?new_action=' + new_action + '&email=' + email + '&is_marqueblanche=' + is_marqueblanche;
		self.parent.location.href = url;
	}else{
		document.getElementById('spanError').style.display = 'block';
	}
}


function sendMessage(message_case) {

	// remove any errors if they exist
	if (document.getElementById('error_email')) {
		document.getElementById('error_email').innerHTML = "";
	}
	if (document.getElementById('error_thread_subject_id')) {
		document.getElementById('error_thread_subject_id').innerHTML = "";
	}
	if (document.getElementById('error_message')) {
		document.getElementById('error_message').innerHTML = "";
	}

	// begin validation
	var email = document.getElementById('email').value;

	var checkSubject = true;

	if (document.getElementById('thread_subject_id') != null) {
		var thread_subject_id = document.getElementById('thread_subject_id').value;

		if (thread_subject_id == 0) {
			checkSubject = false;
		}
	} else {
		var thread_subject = document.getElementById('thread_subject').value;

		if (thread_subject == '') {
			checkSubject = false;
		}
	}
	var check = checkEmail(email);
	var ok = true;

	if (!check) {
		document.getElementById('error_email').innerHTML = document
				.getElementById('new_thread_error_invalid_email').value;
		ok = false;
	}

	if (!checkSubject) {
		if (message_case == 'support') {
			var error = document
					.getElementById('new_thread_error_choose_subject').value;
		} else {
			var error = document
					.getElementById('new_thread_error_enter_subject').value;
		}
		document.getElementById('error_thread_subject_id').innerHTML = error;
		ok = false;
	}

	// check the message
	var message = document.getElementById('message').value;

	if ('' == message
			|| document.getElementById('default_message_box_text').value == message) {
		document.getElementById('error_message').innerHTML = document
				.getElementById('new_thread_error_enter_message').value;
		ok = false;
	}

	if (ok) {
		document.form.submit();
	}
}

function showCodeFields() {
	var options = document.getElementById('thread_subject_id').options;
	var selected = document.getElementById('thread_subject_id').selectedIndex;
	var ids = codeNeededFor.split('-');
	var needed = false;

	for ( var i = 0; i < ids.length; i++) {
		if (options[selected].value == ids[i]) {
			needed = true;
		}
	}

	if (needed) {
		showCodeNextTo('code_0');
	} else {
		for ( var i = 1; i <= 12; i++) {
			document.getElementById('p_code_' + i).style.display = 'none';
		}
	}
}

function showCodeNextTo(name) {
	var tmp = name.split('_');
	var next = parseInt(tmp[1]) + 1;

	document.getElementById('p_code_' + next).style.display = 'block';

	if (next == 12) {
		document.getElementById('a_code_' + next).style.display = 'none';
	}
}



/**
 * Function checks the email of the user, and tries to create a temporary account for him/her
 * Called when creating a new user after using an audiotel Code In The MB
 * Uses ajax calls to create the user, or display errors
 */
function checkAudiotelSignupFromMB()
{ 
	
	//hide the error block if it's not hidden
	document.getElementById('showErrorAllopass').style.display = 'none';
	
	//disable the submit button
	document.getElementById('allopass-submit').disabled=true;
	
	//declare variables
	var email = document.getElementById('allopass-email').value;
	var url;
	var mail_check = validateEmail(email);
	
	//check the email
	if (false == mail_check) {
		document.getElementById('showErrorAllopass').style.display = 'block';
		document.getElementById('wrong_email').style.display = 'block';
		
		//enable the submit button
		document.getElementById('allopass-submit').disabled=false;		
		return false;
	}
	
	//email passed verification, make the first ajax call to check if the email exists
	// set to url to check if the email address exists
	url = siteBaseUrl + 'login/create_audiotel_temp_account_from_mb?email=' + email + '&ajax=1';

	//add a parameter for the newsletter
	if (document.getElementById('allopass_newsletter') && true == document.getElementById('allopass_newsletter').checked)
	{
		url = url + "&newsletter=1";
	}
	
	if (document.getElementById('submit_from_pdt') && 'true' == document.getElementById('submit_from_pdt').value)
	{
		url = url + "&submit_from_pdt=1";
	}
	
	// send the url, get the answer and make actions depending on result
	AjaxGetData(url, checkAudiotelSignupFromMB2, null);	
}

function checkAudiotelSignupFromMB2(data)
{
	//we look at the return data, and search for the possible return values
	//no duplicate entry or empty email messages
	if ("CREATE_OK" == data) 
	{ 
		// Show success message
		document.getElementById('showSuccessAllopass').style.display = 'block';
		
		if (document.getElementById('unlimited-view')) {
			document.getElementById('unlimited-view').style.display = 'none';
		}
		
		// Disable the input box
		document.getElementById('allopass-email').disabled = true;
		document.getElementById('allopass_newsletter').disabled = true;
		
	}
	else
	{
	
		document.getElementById('showErrorAllopass').style.display = 'block';
		
		//depending on the return value, display an error message
		switch (data)
		{
			case "DUPLICATE": 	// "Adresse email existe déjà";
				document.getElementById('duplicate_from_pdt').style.display = 'none';
				document.getElementById('wrong_email').style.display 		= 'none';
				document.getElementById('duplicate').style.display 			= 'block';
				document.getElementById('email_empty').style.display		= 'none';
				document.getElementById('create_error').style.display 		= 'none';
				break;
			case "DUPLICATE_FROM_PDT":  // Cette adresse existe déjà<br /> link forget passsword
				document.getElementById('duplicate_from_pdt').style.display = 'block';
				document.getElementById('wrong_email').style.display 		= 'none';
				document.getElementById('duplicate').style.display 			= 'none';
				document.getElementById('email_empty').style.display 		= 'none';
				document.getElementById('create_error').style.display 		= 'none';
				break;
			case "EMAIL_EMPTY": // "Adresse email invalide";
				document.getElementById('duplicate_from_pdt').style.display = 'none';
				document.getElementById('wrong_email').style.display 		= 'none';
				document.getElementById('duplicate').style.display 			= 'none';
				document.getElementById('email_empty').style.display 		= 'block';
				document.getElementById('create_error').style.display 		= 'none';
				break;
			case "CREATE_ERROR":
			default:  //  "Une erreur s'est produite. Veuillez réesayer.";
				document.getElementById('duplicate_from_pdt').style.display = 'none';
				document.getElementById('wrong_email').style.display 		= 'none';
				document.getElementById('duplicate').style.display 			= 'none';
				document.getElementById('email_empty').style.display 		= 'none';
				document.getElementById('create_error').style.display 		= 'block';
				break;
		}
			
		//enable the submit button
		document.getElementById('allopass-submit').disabled=false;			
		return false;		
	}	
}

function showRadios(){
	var imgs = document.getElementsByTagAndClassName('*', 'radio');
	
	for(var i = 0 ; i < imgs.length ; i++){
		document.getElementById(imgs[i].id).style.display = 'block';
	}
}

/**
 * Form to return true or false on weahter or not to submit the signup form, and where to send it
 */
function signUpFormSubmit()
{
	//Validate the form of the email
	var email = document.getElementById('email').value;

	//hide any previous errors
	document.getElementById('showError').style.display = 'none';

	//commence verification
	if ("" == email || validateEmail(email) == false) {
		// test the email
		document.getElementById('showError').style.display = 'block';
		return false;
	}	
	else 
	{
		//check if vip member is selected, if so, then we need to change the action and target of the form
		var member_type_input = document.getElementById('member_type');
		var form_obj = document.getElementById("signup_form");
		if ("vipmember" == member_type_input.value)
		{
			form_obj.target = "_blank";
			form_obj.action = document.getElementById("vip_signup_url").value;	
		}
		else
		{
			form_obj.target = "_self";
			form_obj.action = document.getElementById("free_member_signup_url").value;		
		}
		
		//return true to submit the form
		return true;
	}
}

/**
 * Function validates the buy with credit card form
 * If a user is not logged (i.e. the email filed is there), it validates the email.
 * Sets the selected product
 * returns true on successful completion to submit form
 */ 
function confirmBuyWithCC(form_id, element_ext)
{
	//see if an element extension was passed
	if(element_ext === undefined){
		var field_ext = '';
	}else{
		var field_ext = element_ext;
	}

	//get the form
	var form_obj = document.getElementById(form_id);
	
	//get the submit button and disable it
	var submit_but = document.getElementById('validerImg'+field_ext)
	submit_but.disabled = true;
	
	
	//check if we need to verify
	if (null != document.getElementById('email' + field_ext))
	{
		//email should always be there, so get the value directly
		var email = document.getElementById('email' + field_ext).value;
	
		//hide any previous errors
		document.getElementById('showError' + field_ext).style.display = 'none';
	
		//commence verification
		// test the email
		if ("" == email || validateEmail(email) == false) {
			// display the error
			try {
				var ef = document.getElementById('subscribeDiv');
				ef.style.paddingTop = '12px';
				ef.style.height = '92px';
				document.getElementById('emailAddress').style.margin = '0 0 4px 0';
			} catch(e) {
				
			}
			
			document.getElementById('showError' + field_ext).style.display = 'block';
			//re-enable the submit button, and return false
			submit_but.disabled = false;
			return false;
		}
	}	

	//We made if here, so we set up the link and proceed.
	
	// get the selected product if this wasn't a VIP form.
	var selected_prod = null;
	//if the call didn't come from the new VIP form, we perform the check. If it did, it doesn't matter.
	//The old functionality is kept in to make sure the forms still work before the design changes
	//TODO When PDV is completed, revise this piece of code.
	if ("VIP" != element_ext)
	{
		if (document.getElementById('purchase-type-subscription') && document.getElementById('purchase-type-subscription').checked) {
			selected_prod = document.getElementById('purchase-type-subscription').value;
		}else if (document.getElementById('purchase-type-subscription') && document.getElementById('subscription') && document.getElementById('subscription').value == 1) {
			selected_prod = document.getElementById('purchase-type-subscription').value;
		} else {
			selected_prod = document.getElementById('list-of-packs').value;
		}
		
		// set the hidden field
		document.getElementById('selectedproduct').value = "" + selected_prod;
	}
		
	//submit the form
	form_obj.submit();
}

function checkForAllopass(code, secondcode) {
	// if no second code was passed, fill it in for testing purposes
	if (secondcode === undefined) {
		secondcode = 'test8chr';
	}

	if (8 == trim(code).length && 8 == trim(secondcode).length) {
		document.getElementById('allopassForm').submit();
		return;
	}
	document.getElementById('showErrorCode').style.display = '';
	document.getElementById('showErrorCode').innerHTML = _('invalid_allopass_code');
}

function resizeCommentsPopup(numofcomments) {
	if (numofcomments >= 1)
		commentspopupheight = 700;
	else
		commentspopupheight = 420;

	resizeTo(570, commentspopupheight);
}

function submitComment(default_comment_text) {
	var text = document.getElementById('comment').value;

	if (text != '' && text != default_comment_text) {
		document.form.submit();
	}
}

function limitElementText(el, textlen) {
	document.getElementById(el).value = document.getElementById(el).value.substring(0, textlen);
}


function startPoll() {
	setInterval("pollWindow()", 100);
}

function pollWindow() {
	var truncateLimit = 200;
	var charCount = document.getElementById('comment').value.length;

	// If there has been no change since the last call, do not process again.
	var oldCharCount = 0;
	if (charCount == oldCharCount)
		return;
	else
		oldCharCount = charCount;

	// If we are above the truncateLimit, cut off the end text.
	if (charCount > truncateLimit) {
		document.getElementById('comment').value = document.getElementById('comment').value.substring(0, truncateLimit);
		charCount = document.getElementById('comment').value.length;
	}
}

// function to submit the CB30 VIP form
function confirmCB30Form(video_id) {

	// hide the error message
	$('showError_' + video_id).style.display = 'none';

	// get and validate the email
	var email = $('email_cb_30_' + video_id).value;

	if ("" == email || validateEmail(email) == false) {
		// display the error
		$('periode_essai_cb_30_' + video_id).innerHTML = $('showError_' + video_id).innerHTML;
		$('periode_essai_cb_30_' + video_id).style.color = 'white';
		$('periode_essai_cb_30_' + video_id).style.background = '#990000';

		return false;
	}

	// submit the form
	$('form_cb_30_' + video_id).submit();
}

// Check ticketKey submitted in the faq form
function checkTicketKey() {
	// trim ticket key
	var emptyTicketKey = (trim($('ticket_key_text').value) === '');

	// display error if ticket key is empty
	$('ticket_key_error').style.display = (emptyTicketKey) ? 'block' : 'none';

	if (!emptyTicketKey)
		$('ticket_key_form').submit();
}

//validates the cb purchase on the mobile pdv page
function confirmMobileCbForm(form_id) {
	//get the form
	var form_obj = document.getElementById(form_id);

	//get the submit button and disable it
	var submit_but = document.getElementById('validerImg');
	submit_but.disabled = true;

	//check if we need to verify
	if (null != document.getElementById('email')) {
		//email should always be there, so get the value directly
		var email = document.getElementById('email').value;

		//hide any previous errors
		document.getElementById('showError').style.display = 'none';

		//commence verification
		// test the email
		if ("" == email || validateEmail(email) == false) {
			// display the error
			document.getElementById('showError').style.display = 'block';
			//re-enable the submit button, and return false
			submit_but.disabled = false;
			return false;
		}
	}

	//submit the form
	form_obj.submit();
}

