/*
**  MiniLib Javascript
*/

// Desactive le conflit avec jQuery
jQuery.noConflict();
////////////////////////////////////


//fonction qui scroll jusqu'a un id
function scrollTo(trgt) {
  var target_offset = jQuery('#'+trgt).offset();
  if(!!target_offset)
  {
	  var target_top = target_offset.top;
	  jQuery('html, body').animate({scrollTop:target_top}, 500);
  }
  
}

//vérification d'une addresse mail
  function check_mail(email) {
    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(jQuery(email).val())) {
      return false;
    }
    return true;
  }

//validation du changement de mot de passe
function changePasswordValidate() {
  if (jQuery('#curPwd').val() && jQuery('#newPwd').val() && jQuery('#newConfPwd').val()) {
    if (jQuery('#newPwd').val() == jQuery('#newConfPwd').val()) {
      return true;
    }
    jQuery('#confErrPass').text('Votre nouveau mot de passe et la confirmation sont différents');
    return false;
  }
  jQuery('#newErrPass').text('Veuillez remplir tous les champs');
  jQuery('#confErrPass').text('Veuillez remplir tous les champs');
  jQuery('#curErrPass').text('Veuillez remplir tous les champs');
  return false;
}

//validation du changement de nom d'utilisateur
  function changeUsernameValidate() {
    if (jQuery('#newId').val() && jQuery('#newConfId').val()) {
      if(check_mail('#newId') && check_mail('#newConfId')){
        return true
      }
      jQuery('#newErrId').text('Veuillez spécifier une addresse mail valide');
      return false;
    }
    jQuery('#curErrId').text('Veuillez remplir tous les champs');
    jQuery('#newErrId').text('Veuillez remplir tous les champs');
    return false;
  }

//toggle the sidebar menu (candidate)
function deploy() {
  if (jQuery("#submenu:visible").length != 0) {
    jQuery("#submenu").hide();
  }
  else {
    jQuery("#submenu").show();
  }
}

// See apps/frontend/modules/contact/templates/_recruiter_synthesis.php
function colorElement(element, text_color, bg_color, border)
{
	element.style.cursor = 'pointer';
	element.style.color = text_color;
	element.style.backgroundColor = bg_color;
	if (border != null && border != undefined && border != 'undefined' && border == 'show_top')
	{
		element.style.borderTop = '5px solid ' + bg_color + ' !important';
	}
	else if (border != null && border != undefined && border != 'undefined' && border == 'remove_top')
	{
		element.style.borderTop = '0px solid white !important';
	}
}

// See apps/frontend/modules/contact/templates/_recruiter_synthesis.php
function ArrowsConf(down_arrow_img_id, up_arrow_img_id, right_arrow_img_id, last_arrow_direction)
{
	this.downArrowImgElement   = document.getElementById(down_arrow_img_id);
	this.upArrowImgElement     = document.getElementById(up_arrow_img_id);
	this.rightArrowImgElement  = document.getElementById(right_arrow_img_id);
	
	if (last_arrow_direction != null && last_arrow_direction != undefined && last_arrow_direction != 'undefined')
		this.lastArrowDirection = last_arrow_direction;
	else
	    this.lastArrowDirection = 'down';
	
	this.switchToSimpleArrow    = function()
							      {
								    this.rightArrowImgElement.style.display = 'none';
	 	
 									if (this.lastArrowDirection == 'down')
									{
									  this.downArrowImgElement.style.display = 'none';
									  this.upArrowImgElement.style.display   = 'block';
										
									  this.lastArrowDirection = 'up';
									}
									else
									{
									  this.upArrowImgElement.style.display   = 'none';
									  this.downArrowImgElement.style.display = 'block';
										
									  this.lastArrowDirection = 'down';
								    }
							      }
	
	this.switchToRightArrow    = function()
							     {
								   this.downArrowImgElement.style.display   = 'none';
								   this.upArrowImgElement.style.display     = 'none';
								   this.rightArrowImgElement.style.display = 'block';
						  	     }
}

// See apps/frontend/modules/contact/templates/_recruiter_synthesis.php
function switch_candidates_tab_arrows(index)
{
	for (var i = 0; i < arrows_conf.length; ++i)
	{
		if (i == index)
			arrows_conf[i].switchToSimpleArrow();
		else
			arrows_conf[i].switchToRightArrow();
	}
}

//validate the fields takken for mobility (CV)
function validationmobilite() {
	var x = document.getElementById("mobilityChoice");
	if (x.selectedIndex == 1) {
		if (jQuery('#mobilityCountryChoice select').val() != null && jQuery('#mobilityCountryChoice select').val() != "") {
			return true;
		}
	}
	else if (x.selectedIndex == 2) {
		return true;
	}
	else if (x.selectedIndex == 3) {
		if ((jQuery('#french_departments_and_regions :checked').val() == "on") || (jQuery('.regionSelect:checked').val()) ) {
			return true;
		}
	}
	else if (x.selectedIndex == 4) {
		if (jQuery('#mobilityCityChoice select').val() != "") {
			return true;
		}
	}
	alert('Votre choix de mobilité n\'est pas correct.\r\nLes données par défaut vont être appliquées.');
	return false;
}

//show the correct divs in CV (mobility)

function sfToggleMobilityChoice(value, initValue){
	if (value == '1') {
		jQuery('#french_departments_and_regions').find('.regionSelect').removeAttr('checked');
		jQuery('#mobilityCountryChoice').show();
        jQuery('#french_departments_and_regions').hide();
        jQuery('#mobilityRadiusChoice').hide();
        jQuery('#mobilityCityChoice').hide();
        jQuery('#mobilityChoice option[value="1"]').attr('selected', 'selected');
	}
	else if (value == '2') {
        if (jQuery('#countrySelect option:selected').value != 'FR') {
            jQuery('#countrySelect option[value="FR"]').attr('selected', 'selected');
          }
          jQuery('#french_departments_and_regions').find('.regionSelect').attr('checked', 'checked');
          jQuery('#mobilityCountryChoice').hide();
          jQuery('#french_departments_and_regions').hide();
          jQuery('#mobilityRadiusChoice').hide();
          jQuery('#mobilityCityChoice').hide();
          jQuery('#mobilityChoice option[value="2"]').attr('selected', 'selected');
	}
	else if (value == '3') {
        if (jQuery('#countrySelect option:selected').value != 'FR') {
            jQuery('#countrySelect option[value="FR"]').attr('selected', 'selected');
          }
          if (initValue == 0) {
           jQuery('#french_departments_and_regions').find('.regionSelect').removeAttr('checked');
            jQuery('#french_departments_and_regions').find('.options').hide();
            jQuery('#french_departments_and_regions').find('.title').removeClass('active');
          }
          jQuery('#mobilityCountryChoice').hide();
          jQuery('#french_departments_and_regions').show();
          jQuery('#mobilityRadiusChoice').hide();
          jQuery('#mobilityCityChoice').hide();
          jQuery('#mobilityChoice option[value="3"]').attr('selected', 'selected');
	}
	else if (value == '4') {
        jQuery('#french_departments_and_regions').find('.regionSelect').removeAttr('checked');
        jQuery('#mobilityCountryChoice').hide();
        jQuery('#french_departments_and_regions').hide();
        jQuery('#mobilityRadiusChoice').show();
        jQuery('#mobilityCityChoice').show();
        jQuery('#mobilityChoice option[value="4"]').attr('selected', 'selected');
	}
	else {
        jQuery('#mobilityCountryChoice').hide();
        jQuery('#french_departments_and_regions').hide();
        jQuery('#mobilityRadiusChoice').hide();
        jQuery('#mobilityCityChoice').hide();
        jQuery('#mobilityChoice option[value="empty"]').attr('selected', 'selected');
	}		
	
}

function toggleMobilityChoice(value, initValue){
	if(value == 'international') {
          jQuery('#french_departments_and_regions').find('.regionSelect').removeAttr('checked');
          jQuery('#mobilityCountryChoice').show();
          jQuery('#french_departments_and_regions').hide();
          jQuery('#mobilityRadiusChoice').hide();
          jQuery('#mobilityCityChoice').hide();
          jQuery('#mobilityChoice option[value="international"]').attr('selected', 'selected');
	}
	else if (value == 'france') {
          if (jQuery('#countrySelect option:selected').value != 'FR') {
            jQuery('#countrySelect option[value="FR"]').attr('selected', 'selected');
          }
          jQuery('#french_departments_and_regions').find('.regionSelect').attr('checked', 'checked');
          jQuery('#mobilityCountryChoice').hide();
          jQuery('#french_departments_and_regions').hide();
          jQuery('#mobilityRadiusChoice').hide();
          jQuery('#mobilityCityChoice').hide();
          jQuery('#mobilityChoice option[value="france"]').attr('selected', 'selected');
	}
	else if (value == 'region') {
          if (jQuery('#countrySelect option:selected').value != 'FR') {
            jQuery('#countrySelect option[value="FR"]').attr('selected', 'selected');
          }
          if (initValue == 0) {
           jQuery('#french_departments_and_regions').find('.regionSelect').removeAttr('checked');
            jQuery('#french_departments_and_regions').find('.options').hide();
            jQuery('#french_departments_and_regions').find('.title').removeClass('active');
          }
          jQuery('#mobilityCountryChoice').hide();
          jQuery('#french_departments_and_regions').show();
          jQuery('#mobilityRadiusChoice').hide();
          jQuery('#mobilityCityChoice').hide();
          jQuery('#mobilityChoice option[value="region"]').attr('selected', 'selected');
	}
	else if (value == 'ville') {
          jQuery('#french_departments_and_regions').find('.regionSelect').removeAttr('checked');
          jQuery('#mobilityCountryChoice').hide();
          jQuery('#french_departments_and_regions').hide();
          jQuery('#mobilityRadiusChoice').show();
          jQuery('#mobilityCityChoice').show();
          jQuery('#mobilityChoice option[value="ville"]').attr('selected', 'selected');
	}
	else {
          jQuery('#mobilityCountryChoice').hide();
          jQuery('#french_departments_and_regions').hide();
          jQuery('#mobilityRadiusChoice').hide();
          jQuery('#mobilityCityChoice').hide();
          jQuery('#mobilityChoice option[value="empty"]').attr('selected', 'selected');
	}
}

function toggleAgencyInfo(caller, agencyTagId, agencyIdValue) {
  if (caller.value == agencyIdValue) {
    jQuery(agencyTagId).show();
    jQuery('#subscriptionActivityLabel').hide();
    jQuery('#subscriptionNameLabel label').text('Nom du cabinet *');
    jQuery('#subscriptionLogoLabel label').text('Logo du cabinet');
  } else {
    jQuery(agencyTagId).hide();
    jQuery('#subscriptionActivityLabel').show();
    jQuery('#subscriptionNameLabel label').text('Nom de l\'entreprise *');
    jQuery('#subscriptionLogoLabel label').text('Logo de l\'entreprise');
  }
}

// Disable ctrl-c && ctrl-v
function disableCtrlPastAndCtrlCopy(e) {
  if ((e.ctrlKey) && ((e.which == 67) || (e.which == 86))){
    return false;
  }
}

// Disable right-clic
function disableRightClick(e){
    jQuery(document).bind("contextmenu",function(e){
        return false;
    });
}

// Redirection page
function  redirectTo(redirect, time){
  var url = parseUri(location);
  setTimeout(function () {
    jQuery(location).attr('href', url.protocol + "://" + url.authority + "/" + redirect)}, time);
}

// Active popup
function  myPopup(e){
  var href = e.target;
  window.open(href, 'popup', 'heigh=800, width=1000, toolbar=no, location=no, status=no, scrollbars=yes, resizable=yes');
  return false;
}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
// example http://stevenlevithan.com/demo/parseuri/js/

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};
//options for parseUri
parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


// toggle element

function toggle(div){
    if(jQuery('#'+div).is(':visible')) jQuery('#'+div).hide();
    else jQuery('#'+div).show();
}

/* collapseEltButton
 * Usage :
 * - eltToCheck : element to check
 * - first : first value to check
 * - second : second second to check
 * - id : id element to hide/show
 */

function collapseEltButton(eltToCheck, first, second, id){
  if(jQuery('#'+eltToCheck+'_'+first).is(':checked'))
    jQuery('#'+id).hide();

  jQuery('#'+eltToCheck+'_'+first).click(function (){
    jQuery('#'+id).hide();
  });
  jQuery('#'+eltToCheck+'_'+second).click(function (){
    jQuery('#'+id).show();
  });
}

/* Onglets
 * Usage :
 * - elmnt : the LI to select
 * - toselect : the LI to select (facultatif)
 */
function select_tab(toselect, elmt)
  {
    jQuery('#onglets .current').removeClass('current');
    jQuery('#onglets #' + toselect).addClass('current');
    if(elmt){
      jQuery('#onglets_divs .onglet').removeClass('active');
      jQuery('#onglets_divs #' + elmt).addClass('active');
    }
    _initAjax();
  }

function updateSynthesisOfferRow(elementId, url)
{
  jQuery.ajax({
    type:       'POST',
    dataType:   'html',
    success:    function(data, textStatus) {
                  jQuery('#' + elementId).html(data);
                }
    ,
    url:        url
  });
  return false;
}

/* Toggle selected button
 * Usage :
 * - elmnt : the LI to select
 * - toselect : the a to select (facultatif)
 */
function toggle_current(toselect, theparent)
  {
    jQuery('#'+theparent+' .selected').removeClass('selected');
    jQuery('#'+toselect).addClass('selected');
  }

// Print element
function printElem(div){
  jQuery(div).printElement({printMode:'none'});
 }

// SubmitTo helper
function submitTo(form, url){
  //var old_action = jQuery(form).attr('action');
  jQuery(form).attr('action', url);
  jQuery(form).submit();
 }

function toggleAccountMenu(button){
  jQuery("#top-menu-content").slideToggle(300);
  jQuery("#account-top").toggleClass("opened");
  if(jQuery(button).text()=='Afficher ma synthèse') jQuery(button).text('Masquer ma synthèse');
  else jQuery(button).text('Afficher ma synthèse');
}

function toggleJob(button){
  jQuery(".job-details-div").slideToggle(300);
  jQuery(button).toggleClass("opened");
  if(jQuery(button).text()=='Voir l\'annonce') jQuery(button).text('Cacher l\'annonce');
  else jQuery(button).text('Voir l\'annonce');
}

function initAjaxBox() {
  jQuery('a.ajaxBox').fancybox(
  {
	  'overlayOpacity'	: '0.7',
      'centerOnScroll'  : 'true',
      ajax : {type : "POST"}
  });
}

function initAjaxForm(_target) {

  var options = { 
    target: !_target ? jQuery('.ajaxForm').parent() : _target
  }; 
  jQuery('.ajaxForm').ajaxForm(options);

}

// INIT function

function _initAjax() {
  
  jQuery('#print_button').click(function() {
      printElem('#print_area');
   });
  
   jQuery('.popup').popupWindow({
     centerBrowser:1,
     height:600,
     width:800
   });
  
   jQuery('.confirmAction').click(function(event) {
     msg = jQuery(event.target).attr('rel') ? jQuery(event.target).attr('rel') : 'Etes-vous sur de vouloir effectuer cette action ?';
     if(!confirm(msg)) return false;
   });

   jQuery('.alert').click(function(event) {
     msg = jQuery(event.target).attr('rel');
     alert(msg);
     return false;
   });
  
   jQuery('#toggle-account-menu').text('Afficher ma synthèse');
   jQuery('#toggle-account-menu').click(function(event){
     toggleAccountMenu(jQuery(event.target));
   });
  
   jQuery('.toggle-job-button').text('Voir l\'annonce');
   jQuery('.toggle-job-button').click(function(event) {
     toggleJob(jQuery(event.target));
   });
  
   initAjaxBox();
  
   jQuery('.tooltip').tooltip({
     offsetX   : -50,
     offsetY   : 30,
     bgcolor   : "#FFFFFF",
     fontcolor : "#666666",
     fontsize  : "11px"
   });
  
   initAjaxForm();
}

function tinyMceReplaceContent(pl, o)
{
    o.content = o.content.replace(/<!--[^>]*>/g, "");
}

// Provisoire
function validationCompteCoach()
{
  if (jQuery('#emailCoach').val() == "")
  {
    alert( "Veuillez entrer l'adresse e-mail de votre login");
    jQuery('#emailCoach').addClass('error').focus();
    return false ;
  }
  var email = jQuery('#emailCoach').val();
  email = email.replace(/\./g, '$');
  var link = jQuery('#validCoachHref').attr("href");
  jQuery('#validCoachHref').attr("href", link + email);
  
  return true;
}

// INIT CALL

jQuery(document).ready(function() {
  _initAjax();
  jQuery('body').keydown(function(e){
    if((jQuery('.flash_box:visible'))) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if(code == 13) {
        jQuery(".flash_box").hide();
        jQuery(".flash_box_background").hide();
      }
    }
  });
});
/**
 * Fonction rechargeant une liste d'information
 * @param id
 * @param url
 * @param content
 */
function reloadList(id, url, content)
{
	jQuery.ajax({url : url,
				 type : 'POST',
				 data : {'id' : id},
				 success : function(data)
				 {
					jQuery('#'+content).html(data); 
				 }
				})
}
/**
 * Fonction permettant d'afficher la box d'attente
 * @param message
 */
function showWaitBox(message)
{
	//Initilisation de la boite de dialogue au cas ou une autre utilisation a été faite
	jQuery('#confirm').css({'background-image' : 'none', 
							'padding' 	: '15px 45px',
							'width' 	:'470px',
							'height'	: '70px'});
	jQuery('#confirm').html('<p id="flash_box_confirm_text"></p>');
	
	
	jQuery('#confirm').show();
	
	jQuery('.flash_box_background').show() ;
	jQuery('#confirm #close_link').hide();
	jQuery('#confirm p').html(message+'<br><br><img src="/images/loader-cvtheque.gif" />');
}
/**
 * Fonction permettant de cacher la box d'attente
 * Si param defini alors repositionnement dans la page
 * 
 * @param redirectPosition
 */
function hideWaitBox(redirectPosition)
{
	jQuery('#confirm').hide();
	jQuery('.flash_box_background').hide();
	
	if(redirectPosition)
	{
		scrollTo(redirectPosition);
	}
}

