var is_login = false; 
var GraduatedButtonStatus = false;
var AccessLvlButtonStatus = true;
var cert_primary = 0;

$(document).ready(function(){
  $('div.help, div.extra').tooltip({
  	track: true,
  	delay: 100,
  	showBody: '::',
  	opacity: 0.85
  });

   $("#degree_type_id").change(function(){
    
  
    if($(this).val() == "")
      $("td.dat").css({display:""});
     else
      $("td.dat").css({display:"none"});
      
  });
  
  $($('#add_cert')).click(function(){     
    if($("#cert_name_"+(cert_primary+1)).val().length < 3)
      alert($("#trn_emptyfname").html());
    else{
      cert_primary++;
      doNewCert($("#cert_img_"+cert_primary) , 'cert_img_' , 'file' , false);      
      doNewCert($("#cert_name_"+cert_primary) ,'cert_name_' , 'text' , true);
      var v = $("#cert_name_"+(cert_primary)).val();         
      $("div#cert_container").append('<div>'+v+' &nbsp; &nbsp; <img src="/cms/themes/blue/generic/img_delete.gif" style="cursor:pointer;" alt=""/></div>').find("img").click(function(){
        simple_confirm($("#trn_emptycerificate").html(), function(){
          $(this).parent().remove();
          $($( "#cert_img_"+(cert_primary-1))).remove();
          $($("#cert_name_"+(cert_primary-1))).remove();
          return true; 
        });        
      });      
    }
    return false;
  });
  
  function doNewCert(obj ,  iname , itype , rec) {     
      $(obj).hide();      
      $(obj).parent().prepend('<input name="'+iname+(cert_primary+1)+'" type="'+itype+'" id="'+iname+(cert_primary+1)+'" />');
   }
   
function function_exists( function_name ) {

    if (typeof function_name == 'string'){
        return (typeof this.window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}   
  $("#application_country_id").change(function(){
        
        if(typeof(ajax_get_state_filter) == 'undefined')ajax_get_state_filter = '';
        var ajaxBaseUrl = document.location.href;
        var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
        ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
        var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_country_state";
        
        $("#application_country_state_id").html("<option value=''>Loading...</option>");        
        
				$.getJSON(requestStr,{id: $(this).val(),get_state_filter: ajax_get_state_filter}, function(j){
					var options = '<option value="">' + $("#trn_select_country_state").html() + '</option>';
					var show = false;
					for (var i = 0; i < j.length; i++) {
						options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
            show = true;
					}
					if (show) {
					  $("#application_country_state_id").html(options);
					  $('#application_country_state_id option:first').attr('selected', 'selected');
            //$("#application_country_state_id").style.display = 'block';
            $("tr[name=country_state_block]").removeClass("weg");
          } else {
            //$("#application_country_state_id").style.display = 'none';
            $("tr[name=country_state_block]").addClass("weg");
          }
		  
				});				
			});		
	$("#accept").change(function(){
    if($("#accept:checked").length > 0)
    {
      $("#acceptl").css({color:""});
    }
    else
    {
      $("#acceptl").css({color:"red"});       
    }
	})
	
	$("#is_booth").change(function(){ 
    if($("#is_booth:checked").length > 0)
    {
      $("#booth").val($("#trn_booth_text").html());
    }
    else
    {
      $("#booth").val('');
    }
	})
  
  if(!GraduatedButtonStatus)
   $(document).find('tr.graduated').css({display:"none"});
  else
   $(document).find('tr.graduated').css({display:""});
   
  $("#graduated").change(function(){
    if($("#graduated:checked").length > 0)
    {
      $(document).find('tr.graduated').css({display:""});      
    }
    else
    {
      $(document).find('tr.graduated').css({display:"none"});       
    }
  })
	
	if(!AccessLvlButtonStatus)
	 $(document).find('tr.accesslvl').css({display:"none"});
	else
	 $(document).find('tr.accesslvl').css({display:""});
	 
	$("#grant_system_access").change(function(){
    if($("#grant_system_access:checked").length > 0)
    {
      $(document).find('tr.accesslvl').css({display:""});      
    }
    else
    {
      $(document).find('tr.accesslvl').css({display:"none"});       
    }
	})
	
	
  $("#country_id").change(function(){
    
        if(typeof(global_country_state_id) == 'undefined'){
          global_country_state_id = 0;
        }
        if(typeof(global_search_param) == 'undefined'){
		      global_search_param = '';
		    }
        
        //alert(global_search_param);
        
        var ajaxBaseUrl = document.location.href;
        var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
        ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
        var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_city";
		    if(typeof( __jsox_dynamic_param ) != "undefined"){
			    __jsox_dynamic_param[0] = $(this).val();
			    __jsox_dynamic_param[3] = $(this).val();
		    }
        $("#city_id").html("<option value=''>Loading...</option>");
        $("#country_state_id").html("<option value=''>Loading...</option>");
        
				$.getJSON(requestStr,{id: $(this).val(), search_param: global_search_param}, function(j){
					var options = '<option value="">' + $("#trn_select_city").html() + '</option>';
					
					for (var i = 0; i < j.length; i++) {
						options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
					}
					
					$("#city_id").html(options);
					if(global_country_state_id < 1)
					  $('#city_id option:first').attr('selected', 'selected');
				});
				
				if(typeof(ajax_get_state_filter) == 'undefined')ajax_get_state_filter = '';
				var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_country_state";
				
				$.getJSON(requestStr,{id: $(this).val(),get_state_filter: ajax_get_state_filter}, function(j){
					var options = '<option value="">' + $("#trn_select_country_state").html() + '</option>';
          if(typeof(not_show_empty_state) != "undefined"){
            if(not_show_empty_state){
               options = "";
            }
          }
					var show = false;					
					for (var i = 0; i < j.length; i++) {
						options += '<option value="' + j[i].optionValue + '"';
						//alert(global_country_state_id + '=' + j[i]);
						if(global_country_state_id == j[i].optionValue){
						//alert(777);
							options += ' selected="selected"';
						}
						options +='>' + j[i].optionDisplay + '</option>';						
                        show = true;						
					}
          if (show) {
            $("#country_state_id").html(options);
			      if(global_country_state_id < 1){
              show_first = true;
               if(typeof(not_select_first_state) != "undefined"){
                  if(not_select_first_state){
                     show_first = false;
                  }
                }
               if(show_first)
                $('#country_state_id option:first').attr('selected', 'selected');
               
             }
            //$("#country_state_id").style.display = 'block';            
            $("tr[name=country_state_block]").removeClass("weg");            
          } else {
            //$("#country_state_id").style.display = 'none';
            $("tr[name=country_state_block]").addClass("weg");
          }
		  		  
		  if(function_exists('set_country_state')){
		    set_country_state();
		  }

				});
				
			});
			
			$("#information_candidates_country_id").change(function(){
        
        var ajaxBaseUrl = document.location.href;
        var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
        ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
				var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_country_state";
				
				$.getJSON(requestStr,{id: $(this).val()}, function(j){
          var options = '';
					//var options = '<option value="">' + $("#trn_select_country_state").html() + '</option>';
					
					for (var i = 0; i < j.length; i++) {
						options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
					}
					
					$("#information_candidates_country_state_id").html(options);					
					$("#information_candidates_country_state_id").val(information_country_state_id);
          if (typeof(with_validation) == 'undefined' || with_validation){
            //$("#eintrag1").valid();
          }
				});
				
			});
			
  $.validator.addMethod("uniqueLogin", function(value, element) {
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_unique_login";
    
    if(value.length < 3)return false; 
        
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { login: value },
        success: function(answ){
         if(answ == "correct"){
          is_login = true;          
          $('#'+$(element).attr('id')+'_error_message').addClass('weg');
         }
         else{
          is_login = false;          
          $('#'+$(element).attr('id')+'_error_message').removeClass('weg');
         }
        }
        
        
      }
    );   
    
    return is_login;
  }, 'This is not unique login for current domain');

  var anchor = "";
  var GET = Array();
  function parseGET(str){
    str = str.split('?');
    str = str[1];
    if(str.indexOf('#')!=-1)
    {
      anchor = str.substr(str.indexOf('#')+1);
      str = str.substr(0,str.indexOf('#'));
    }
    params = str.split('&');
    for (i=0; i<params.length; i++)
    {
      var keyval = params[i].split('=');
      GET[keyval[0]]=keyval[1];
    }
    return (GET);
  }
  
  $.validator.addMethod("uniqueLoginProfile", function(value, element) {
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_unique_login_profile";
    GET = parseGET(location.search);
    if(value.length < 3)return false; 
        
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { login: value, profile_id: GET['id'] },
        success: function(answ){
         if(answ == "correct"){
          is_login = true;          
          $('#'+$(element).attr('id')+'_error_message').addClass('weg');
         }
         else{
          is_login = false;          
          $('#'+$(element).attr('id')+'_error_message').removeClass('weg');
         }
        }
        
        
      }
    );   
    
    return is_login;
  }, 'This is not unique login for current domain');

  $.validator.addMethod("uniqueLanguage", function(value, element) {
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_check_bio_language_unique";

    if(is_bio_new){
      is_bio_new = false;
      bio_mode[5] = 0;
    }
    is_unique = false;
      
    if(value.length = 0)return false; 
        
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: {item_id: bio_mode[5]
              , language_id: value
              , cv_id: cv_id},
        success: function(answ){
         if(answ == "correct"){
          is_unique = true;          
          //$('#'+$(element).attr('id')+'_error_message').addClass('weg');
         }
         else{
          is_unique = false;          
          //$('#'+$(element).attr('id')+'_error_message').removeClass('weg');
         }
        }
      }
    );   
    
    return is_unique;
  }, 'This language was typed already');
  
  $.validator.addMethod("validYear", function(value, element) {
    
    if(value.length < 1){
      return true;
    }
    var pattern = /^(\d{4})$/;   
    var matchArray = value.match(pattern);
    
    if (matchArray == null) {
      return false;
    }
    
    return true;
  }, 'This is not valid year value');
  
  $.validator.addMethod("validCaptcha", function(value) {
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_check_captcha";
    
    if(value.length < 1) return false;
    $.ajax({
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { val: value },
        success: function(answ){
         //alert(answ);
         if(answ == "correct")
          result = true;
         else
          result = false;
        }
      });   
    
		return result;
	}, 'Invalid captcha code');
	
   $.validator.addMethod("positiveCatrgories", function(value) { 
    if($("#application_categories1").get(0).options.length < 1)   
     return false;
    return true;
  }, 'You must select as least one value'); 
  
  $.validator.addMethod("positiveAclspr", function(value) { 
    if($("#access_levels1").get(0).options.length < 1)   
     return false;
    return true;
  }, 'You must select as least one value');  
  
  $.validator.addMethod("positiveAclscatpr", function(value) { 
    if($("#access_companies1").get(0).options.length < 1)   
     return false;
    return true;
  }, 'You must select as least one value');   

   $.validator.addMethod("positiveSubjects", function(value) {
	if($("#vacancy_subjects1").get(0).options.length < 1)   
     return false;
    return true;
  }, $.validator.messages['positiveCatergoriesEmplTrn']);  
  
  $.validator.addMethod("positiveCatergoriesEmpl", function(value) {  
    if($("#vacancy_categories1").get(0).options.length < 1)
     return false;
    return true;
  }, $.validator.messages['positiveCatergoriesEmplTrn']);
  
   $.validator.addMethod("positiveCatergoriesEmplTraining", function(value) {  
    if($("#training_categories1").get(0).options.length < 1)   
     return false;
    return true;
  }, 'You must select as least one value');  
  
	 $.validator.addMethod("positiveWorkscopes", function(value) {  
	  if($("#workscopes1").get(0).options.length < 1)   
	   return false;
		return true;
	}, 'You must select as least one value');
	
   $.validator.addMethod("positiveDatesTraining", function(value) {  

     var dateStart = new Date($('select[name="date_start[date_start_Year]"]').val(),
                              $('select[name="date_start[date_start_Month]"]').val(),
                              $('select[name="date_start[date_start_Day]"]').val());  
     var dateEnd   = new Date($('select[name="date_end[date_end_Year]"]').val(),
                              $('select[name="date_end[date_end_Month]"]').val(),
                              $('select[name="date_end[date_end_Day]"]').val());  
       if (dateStart.getTime() > dateEnd.getTime()) {
         return false;
       }
       return true;
  }, 'Please select a valid date period'); 
  
  $.validator.addMethod("positiveDatesStudy", function(value) {  
       var dateStart = new Date($('select[name="date_fromYear"]').val(),
                                $('select[name="date_fromMonth"]').val(),
                                1);  
     var dateEnd   = new Date($('select[name="date_tillYear"]').val(),
                              $('select[name="date_tillMonth"]').val(),
                              1);  
       if (dateStart.getTime() > dateEnd.getTime()) {
         return false;
       }
       return true;
  }, 'Please select a valid date period');  
  
  $.validator.addMethod("positiveDatesJob", function(value) {  
  
    if($('#flag_ongoing').attr('checked')){
      return true;
    }
    val_m = $('#date_till_2_month').val();
    val_y = $('#date_till_2_year').val();
       
     var dateStart = new Date($('#date_from_2_year').val(), 
                              $('#date_from_2_month').val(),
                              1);  
     var dateEnd   = new Date($('#date_till_2_year').val(),
                              $('#date_till_2_month').val(),
                              1);  
       if (dateStart.getTime() > dateEnd.getTime()) {
         return false;
       }
       return true;
  }, 'Please select a valid date period');  
  
   $.validator.addMethod("positiveDateRegTraining", function(value) {  

     if ($("#flag_with_registration:checked").length > 0) {  
       var dateReg = new Date($('select[name="registration_date[registration_date_Year]"]').val(),
                              $('select[name="registration_date[registration_date_Month]"]').val(),
                              $('select[name="registration_date[registration_date_Day]"]').val());  
       var dateEnd   = new Date($('select[name="date_end[date_end_Year]"]').val(), 
                                $('select[name="date_end[date_end_Month]"]').val(), 
                                $('select[name="date_end[date_end_Day]"]').val());  
       if (dateReg.getTime() > dateEnd.getTime()) {
         return false;
       }
     }
       return true;
  }, 'Please select a valid registration date');  

  $.validator.addMethod("required_fck", function(value, element) {
    if (typeof(FCKeditorAPI) != 'undefined') {
      var fckinstance = FCKeditorAPI.GetInstance(element.name);
      if (fckinstance) {
        var txt = fckinstance.GetData(false);
        //alert (txt + ' original length ' + txt.length);
        oRegex = new RegExp( "(\s|\xA0|<br />)+$", 'gim' ) ;
        element.value = value = txt.replace(oRegex, "");;
      }
      lngth = $('#'+element.id).attr('minlength');
      if (lngth) { 
        //alert(value + ' : ' + value.length + ' < ' + length);
        if (value.length < lngth)
          return false;
      }
      lngth = $('#'+element.id).attr('maxlength');
      if (lngth) {
        //alert(value + ' : ' + value.length + ' > ' + length);
        if (value.length > lngth)
          return false;
      }
    }
    
    //alert(value);
    if(value.length < 1 || value == "<br />" || value == "&lt;br /&gt;")
      return false;
    return true;
  }, $.validator.messages['required']);
  
  $.validator.addMethod("required_apply_method", function(value, element) {
    if ( !$("#apply_method_1").attr('checked') 
      && !$("#apply_method_2").attr('checked')
      && !$("#apply_method_3").attr('checked')
      ) return false;
    
    if ($("#apply_method_1").attr('checked') == 'checked' && !$('input[name="external_url"]').val())
      return false;
    if ($("#apply_method_2").attr('checked') == 'checked' && !$('input[name="direct_email"]').val())
      return false;
    
    return true;
  }, $.validator.messages['required']);
  
  $("#eintrag").validate({messages: {accept:" "}}); 
});

if( jQuery.browser.mozilla ) {	
	$( function() {		
		$( 'form.eintrag' ).hide().find( 'p>label:not(.nocmx):not(.error)' ).each( function() {
			var $this = $(this);
			var labelContent = $this.html();
			var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );			
			var labelSpan = $("<span>")
				.css("display", "block")
				.width(labelWidth)
				.html(labelContent);			
			$this.css("display", "-moz-inline-box")				
				.empty()				
				.append(labelSpan);		
		}).end().show();
	});
};


function DeleteImageApplicantCert(applicant_id ,cert_id , element_id , confirm_message){
  simple_confirm(confirm_message, function(){  
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_delete_applicant_certificate";       
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { id: applicant_id,  certificate: cert_id},
        success: function(answ){
         if(answ == "correct")
         {          
          $("#"+element_id).remove();          
         }         
        }
        
      }
     )
  });
}

function DeleteImageApplicant(applicant_id , row_name, image_id , button_id , confirm_message){
 simple_confirm(confirm_message, function(){
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_delete_image_applicant";       
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { id: applicant_id,  row: row_name},
        success: function(answ){
         if(answ == "correct")
         {          
          $("#"+image_id).remove();
          $("#"+button_id).remove();
         }
        }
        
        
      }
     )
  });
}

function DeleteImageEmployer(employer_id , row_name, image_id , button_id , confirm_message){
  simple_confirm(confirm_message, function(){
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_delete_image_employer";       
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { id: employer_id,  row: row_name},
        success: function(answ){
         if(answ == "correct")
         {          
          $("#"+image_id).remove();
          $("#"+button_id).remove();
         }
        }
        
        
      }
     )
  });
}

function SetChecked(el_name){
  document.getElementById(el_name).click();  
}

function ReverseCheckBox(el_name){
  document.getElementById(el_name).click();  
  //document.getElementById(el_name).checked=!document.getElementById(el_name).checked;   
}

/*function CategoriesSelector(is_right){
  s1 = document.getElementById("application_categories");   
  s2 = document.getElementById("application_categories1");
  
  if(is_right)
    selected_el = s2;
  else
    selected_el = s1;
    
  while(selected_el.selectedIndex != -1)
  {
    if(!is_right)
    {    
      s2.options[s2.options.length] = new Option(s1.options[s1.selectedIndex].text, s1.options[s1.selectedIndex].value); 
      s1.options[s1.selectedIndex] = null; 
    } 
      else
    {
      s1.options[s1.options.length] = new Option(s2.options[s2.selectedIndex].text, s2.options[s2.selectedIndex].value); 
      s2.options[s2.selectedIndex] = null; 
    } 
  }
  
  var postval = "";
  for(var i=0 ; i<s2.options.length;i++) 
  {
    postval += s2.options[i].value + ";";
  }
  
  document.getElementById("application_categories_box").value = postval;
}*/ 
function CategoriesSelector(is_right, box, box1, box_val){
  
  if (typeof box     == "undefined") box     = "application_categories";
  if (typeof box1    == "undefined") box1    = "application_categories1";
  if (typeof box_val == "undefined") box_val = "application_categories_box";
  
  s1 = document.getElementById(box);   
  s2 = document.getElementById(box1);
  
  if(is_right)
    selected_el = s2;
  else
    selected_el = s1;
    
  if ($('#'+box).hasClass('combo')) { // for custom selects: ul/li
    if(is_right) {
      from_list = $('#'+box1);
      to_list = $('#'+box);
    } else {
      from_list = $('#'+box);
      to_list = $('#'+box1);
    }
  }                                   // for custom selects: ul/li 
  
  while(selected_el.selectedIndex != -1)
  {
    if(!is_right)
    {    
      s2.options[s2.options.length] = new Option(s1.options[s1.selectedIndex].text, s1.options[s1.selectedIndex].value); 
      s1.options[s1.selectedIndex] = null; 
    } 
      else
    {
      s1.options[s1.options.length] = new Option(s2.options[s2.selectedIndex].text, s2.options[s2.selectedIndex].value); 
      s2.options[s2.selectedIndex] = null; 
    } 
  }
  
  var postval = "";
  for(var i=0 ; i<s2.options.length;i++) 
  {
    postval += s2.options[i].value + ";";
  }
  
  document.getElementById(box_val).value = postval;
  
  if ($('#'+box).hasClass('combo')) { // for custom selects: ul/li
    //$("select.combo").selectBox('options');
    from_list.selectBox('options');
    to_list.selectBox('options');
    setTooltipForCustomCombo();
    setCustomComboEvents(box, box1, box_val);
  }
  
  if(typeof SetAccessToAccountLevel == 'function') { 
    SetAccessToAccountLevel(); 
  }
  
  //alert(document.getElementById(box_val).value); 
}

function setTooltipForCustomCombo() {
  $("a.tltip ul.selectBox-options li a").each(function(){
  //$("ul.selectBox-options li a").each(function(){
    var txt = $(this).text();
    $(this).attr('title', txt);
    $(this).tooltip({
      track: true,
      delay: 100,
      showBody: '::',
      opacity: 0.85
    });
  });
}

function setCustomComboEvents(box, box1, box_val) {
  
  $("select#"+box+",select#"+box1).parent().children('a').children("ul.selectBox-options").children('li').each(function(){
    $(this).bind("dblclick", function(){
      var caller_select_id = $(this).parent().parent().prev('select').attr('id');
      var is_right = false;
      if (caller_select_id == box1) {
        is_right = true;
      }
      CategoriesSelector(is_right, box, box1, box_val);
    });
  });
}

function mBlur(el , text)
{
  if(el.value == "")el.value = text;
}

function mFocus(el , text)
{
  if(el.value == text)el.value = "";
}

function ShowExtra(el ,text)
{
  el = $(document);
  alert(el);
  $('#extra_div').html(text);
  var height = $('#extra_div').height();
  var width = $('#extra_div').width();
  leftVal=el.pageX-(width/2)+"px";
  topVal=el.pageY-(height/2)+"px";
  
  $('#extra_div').css({left:leftVal,top:topVal}).show("fast");  
}

function HideExtra()
{
  $('#extra_div').hide();  
}

function ShowHideApplicantSearchForm(){
    if($("#show_area_id_5:checked").length == 1){
      $(document).find('tr.show_area_id').css({display:""});      
      $(document).find('tr.weg').css({display:"none"});      
      $('.search_filter_box, .search_fields').show();
    } else {
        $(document).find('tr.show_area_id').css({display:"none"});       
        $('.search_filter_box, .search_fields').hide();
    }
}

function in_array(what, where) {
    if (typeof(where) == 'object') {
      for(var i=0; i<where.length; i++)
        if(what == where[i]) 
          return true;
    }
    return false;
}

function ClearApplicantSearchForm(){
  if (typeof(reset_values) == 'object') {
  
    $('.search_filter_box .search_filter_head').each(function() {
      if (!$(this).hasClass('open')) {
        $(this).trigger('click');
      }
    });
  
    for(var prop in reset_values) {
      if (!reset_values.hasOwnProperty(prop)) continue;
      $('input:checkbox[name="'+prop+'[]"]').each(function(i) {
        if($(this).is(':checked')) {
          $('label[for="'+$(this).attr('id')+'"]').trigger('click');
        }
        if($.browser.msie){
          $(this).attr('checked',''); //$(this).removeAttr('checked');
        }else{
          $(this).trigger('click');
        };
        //var val = $(this).val();
        if (in_array($(this).val(), reset_values[prop])) {
          $('label[for="'+$(this).attr('id')+'"]').trigger('click');
          if($.browser.msie){
            $(this).attr('checked','checked'); 
          }else{
            $(this).trigger('click');
          };
        }
      });
    }
  }
  
  if (typeof(reset_values_location) != 'undefined') {
    var init_states = reset_values_location.split(';');
    $.tree.plugins.checkbox.get_checked().each(function(){
      var state     = $(this).attr('id'); 
      var tree_node = $("li[id="+state+"]");
      //if (!in_array($(this).attr('id'), init_states)) {
      if (tree_node) {
        $.tree.plugins.checkbox.uncheck(tree_node);
      }
      //} 
      //alert($(this).attr('id'));
    });
    for(var i=0; i<init_states.length; i++) {
      //alert(init_states[i]);
      var tree_node = $("li[id="+init_states[i]+"]");
      //if (tree_node) {
      if (tree_node && $.tree.reference(tree_node)) {
        $.tree.plugins.checkbox.check(tree_node);
      }
    }
    
    $('input:hidden[name="location_tree_list"]').val(reset_values_location);
  }
}

function ClearApplicantFirmSearchForm(){
  //document.getElementById("show_area_id_5").click();
  document.getElementById("keywords_type_1").click();
  $('#workscope_id option').attr('selected', '');
  
  $('#number_of_empl option:first').attr('selected', 'selected');
  $('#org_type option:first').attr('selected', 'selected');
  $('#age option:first').attr('selected', 'selected');
  
  $('#country_id option:first').attr('selected', 'selected');
  $("#country_state_id").html("<option value=0></option>");
  //$("#country_state_id").style.display = 'none';
  $("tr[name=country_state_block]").addClass("weg");
  
  $("#keywords").val("");
  $("#years").val("");
}               
	
function ShowRegistrationDate() {
  if ($("#flag_with_registration:checked").length > 0) {
    $("#registration").show();
  } else {
    $("#registration").hide();
  }
}

function GetApplicantSpecialAtributes(obj){
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=get_special_atributes";
  $.getJSON(requestStr,{table_name: "jv_applicant", country_id: obj.value}, function(j){
    $("tr.additional_td").remove();
    if (j) {
    for (var i = 0; i < j.length; i++) {      
      if(!$("#tab_"+j[i].position).length) j[i].position=max_tab;        
      if(j[i].innerHTML.substr(0,5) == "<text"){
    	 $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td colspan='2'>"+j[i].innerHTML+"</td></tr>");
      } else {
        $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td>"+j[i].innerHTML+"</td><td></td></tr>");
      }
    }
    }
    if(typeof SetSpecialAtributesNewValues == 'function') {
      //alert("is function");
      SetSpecialAtributesNewValues();
    } 
	});
}

function GetEmployerProfileSpecialAtributes(obj){
  __jsox_dynamic_param[0] = obj.value;
  __jsox_dynamic_param[3] = obj.value;
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=get_special_atributes";
  $.getJSON(requestStr,{table_name: "jv_employer_profile", country_id: obj.value}, function(j){
    $("tr.additional_td").remove();
    if (j) {
    for (var i = 0; i < j.length; i++) {      
      if(!$("#tab_"+j[i].position).length) j[i].position=max_tab;        
      if(j[i].innerHTML.substr(0,5) == "<text"){
    	 $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td colspan='2'>"+j[i].innerHTML+"</td></tr>");
      } else {
        $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td>"+j[i].innerHTML+"</td><td></td></tr>");
      }
    }
    }
    if(typeof SetSpecialAtributesNewValues == 'function') {
      //alert("is function");      
      SetSpecialAtributesNewValues();
    } 
    ChangeProfCountry();
  });
}

function ChangeProfCountry() {
  if ( document.getElementById("profl_country_id") != null ) {
    $("#profl_country_id").change(function(){
      if(typeof(ajax_get_state_filter) == 'undefined')ajax_get_state_filter = '';
      var ajaxBaseUrl = document.location.href;
      var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
      ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
      var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_country_state";
      
      $("#profl_country_state_id").html("<option value=''>Loading...</option>");        
      
      $.getJSON(requestStr,{id: $(this).val(),get_state_filter: ajax_get_state_filter}, function(j){
        var options = '<option value="">' + $("#trn_select_country_state").html() + '</option>';
        var show = false;
        for (var i = 0; i < j.length; i++) {
         options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
          show = true;
        }
        if (show) {
          $("#profl_country_state_id").html(options);
          $('#profl_country_state_id option:first').attr('selected', 'selected');
          //$("#application_country_state_id").style.display = 'block';
          $("tr[name=country_state_block]").removeClass("weg");
        } else {
          //$("#application_country_state_id").style.display = 'none';
          $("tr[name=country_state_block]").addClass("weg");
        }
    
    });
    });
  }  
}

function GetEmployerSpecialAtributes(obj){
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=get_special_atributes";
  $.getJSON(requestStr,{table_name: "jv_employer", country_id: obj.value}, function(j){
    $("tr.additional_td").remove();
    if (j) {
    for (var i = 0; i < j.length; i++) {      
      if(!$("#tab_"+j[i].position).length) j[i].position=max_tab;        
      if(j[i].innerHTML.substr(0,5) == "<text"){
    	 $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td colspan='2'>"+j[i].innerHTML+"</td></tr>");
      } else {
        $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td>"+j[i].innerHTML+"</td><td></td></tr>");
      }
    }
    }
    if(typeof SetSpecialAtributesNewValues == 'function') {
      //alert("is function");
      SetSpecialAtributesNewValues();
    } 
	});
}

function GetEmployerRegisterSpecialAtributes(obj){
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=get_special_atributes_reg_employer";
  
  $.getJSON(requestStr,{country_id: obj.value}, function(j){
    $("tr.additional_td").remove();    
    if (j) {
    for (var i = 0; i < j.length; i++) {      
      if(j[i].param == 1){
        if(!$("#tab_"+j[i].position).length) j[i].position=max_tab;      
        if(j[i].innerHTML.substr(0,5) == "<text"){
    	   $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td colspan='2'>"+j[i].innerHTML+"</td></tr>");  
        }else{
          $("#tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td>"+j[i].innerHTML+"</td><td></td></tr>");  
        }
      } else {
        if(!$("#pr_tab_"+j[i].position).length) j[i].position=pr_max_tab; 
        if(j[i].innerHTML.substr(0,5) == "<text"){
          $("#pr_tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td colspan='2'>"+j[i].innerHTML+"</td></tr>");  
        } else {
          $("#pr_tab_"+j[i].position).before( "<tr class='additional_td'><td></td><td>"+j[i].innerHTML+"</td><td></td></tr>");            
        }
    	  
      }
      
    }
    }
    if(typeof SetSpecialAtributesNewValues == 'function') {
      //alert("is function");
      SetSpecialAtributesNewValues();
    } 
	});
}

var BuyDivStatus = 0;
function ShowHideBuyTable(international){  
  if(!international){
    $("#buy_country").hide();
    if(BuyDivStatus == 1)
    {
      $("#buy_div").hide();
      BuyDivStatus = 0;
    }
    else if(BuyDivStatus == 0){
      $("#buy_div").show();      
      BuyDivStatus = 1;
    } else {
      BuyDivStatus = 1;
    }
  } else {
      $("#buy_country").show();
      if(BuyDivStatus == 2){
        $("#buy_div").hide();
        BuyDivStatus = 0;
      }
      else if(BuyDivStatus == 0){
        $("#buy_div").show();
        BuyDivStatus = 2;
      } else {
        BuyDivStatus = 2;
      }
  }
  $("#buy_message").hide();
}

function DeleteApplicantAdditionalFile(applicant_id ,file_id , element_id){
  simple_confirm($("#trn_delete_file").html(), function(){  
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_delete_applicant_additional_file";       
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { id: applicant_id,  file: file_id},
        success: function(answ){
         if(answ == "correct")
         {          
          $("#"+element_id).remove();            
          count_files--;
          if(count_files < 1)
            $("#div_src_prof").html( '<br /><br /><center>'+$("#trn_no_files").html()+'</center>'  );          
         }
        }
        
      }
     )
  });

}
temp_element = null;
teml_text = null;
function showFilesPopup(id, e){
  if(!fpopup_is_show){  
    $("#hidden_popup").attr('elid', id);
    if(temp_element != null && (temp_element != id)){
      optText = '<option value="'+temp_element+'">'+teml_text+'</option>';      
      $("#list_files").html($("#list_files").html()+optText);      
      temp_element = null;
      teml_text = null;
    }    
    sel = document.getElementById("list_files");
    
    for(var i=0;i<sel.length;i++)
    {      
      document.getElementById("list_files").options[i].selected = false;     
      if(document.getElementById("list_files").options[i].value == id){
        temp_element = document.getElementById("list_files").options[i].value;
        teml_text = document.getElementById("list_files").options[i].innerHTML;
        
        document.getElementById("list_files").options[i] = null;
      }
      
    }
    
  cursor = getPosition(e);
    $('#hidden_popup').css('top', cursor.y);  
    $('#hidden_popup').css('left', cursor.x);  
    $('#hidden_popup').show('fast', function(){
    fpopup_is_show = true;        
  });      
  }
}


function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else {
        cursor.x = e.clientX +(document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
        cursor.y = e.clientY +(document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
    }
    return cursor;
}

function replaceFile(){
  $("#old_val").val($("#hidden_popup").attr('elid'));
  $("#new_val").val($("#list_files").val());
  $("#is_replace").val(1);
  $("#replace_form").submit();  
}

function DeleteApplicantPicture(applicant_id, confirm_message, new_message){
  simple_confirm(confirm_message, function(){  
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_delete_image_applicant";       
    $.ajax(
      {
        async: false,
        timeout: 3000,
        type: 'POST',
        url: requestStr,
        data: { id: applicant_id,  row: 'photo_image_path'},
        success: function(answ){
         if(answ == "correct")
         {          
          $("#pctd").html(new_message);          
         }
        }
        
        
      }
     )
  });
}

var new_file_iterator = 0;
function  AddApplicationAdditionalFileRow(commentText,deleteText){    
  if(($('#att_image').val() == '')||($('#att_image').val() == null)){
    return false;
  }
  if (typeof(commentText) == 'undefined') commentText="Comment";
  if (typeof(deleteText) == 'undefined') deleteText="Delete";
  var img = $('#att_image').attr('name');
  if(img.length > 0){
    img = '<img alt="comm1" src="'+img+'"/>';
  } else {
    img = '';
    //return false;
  }
  var txt = '<tr id="fake'+new_file_iterator+'"><td><input type="hidden" value="'+$('#att_image').val()+'" name="new_img_'+new_file_iterator+'">'+img+'</td><td><input class="required" type="text" value="'+$('#att_comment').val()+'" name="new_comm_'+new_file_iterator+'"/><br/><label class="for_select">'+commentText+'</label></td><td><a href="javascript: DeleteFakeApplicationAdditionalFileRow(\'fake'+new_file_iterator+'\')"><img src="'+base_url+'resources/img_delete.gif" alt="'+deleteText+'" /></a></td></tr>';
  $('#add_tbl').append(txt);
  new_file_iterator++;
}

function DeleteFakeApplicationAdditionalFileRow(trid){
  simple_confirm($('#trn_delete_attache').html(), function(){
    $('#'+trid).remove();
  });
}

function refreshCaptcha() {
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_reset_captcha";
  
  $.ajax({
      async: false,
      timeout: 3000,
      type: 'POST',
      url: requestStr,
      data: {},
      success: function(answ){
       //alert(answ);
       if(answ == "correct")
        result = true;
       else
        result = false;
      }
    });   
  t = new Date().getTime();
  $("#captchaimg").attr("src", "");
  $("#captchaimg").attr("src", ajaxBaseUrl + "?_md=captcha&_ac=get&t=" + t);
  $(".validCaptcha").val("");
  return result;
}

function remind_password() {

  valid = $("#remind_password").valid();
  
  if (valid) {
    username = $('#usernumber').val();
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_remind_password";
    
    var a = $.get( requestStr
                 , { username: username
                   }
                 , function(data, textStatus) {
                 //alert(data);
                     if (data == 1) {
                       if(typeof(redirect_path_reminder_sent ) == 'undefined') redirect_path_reminder_sent  = 'reminder_sent.html';
                       document.location.replace(ajaxBaseUrl + redirect_path_reminder_sent);
                     } else {
                       refreshCaptcha();
                       $("#remind_error").removeClass("weg");
                     }
                   }
                 );
  }
}

var vacancy_categories_is_showed = false;

function see_vacancy_categories(){
    elms = $('.error');
	for(var i=0;i<elms.length;i++){
	  if($(elms[i]).attr('for') == 'vacancy_categories1'){
	    if($("#vacancy_categories1").get(0).options.length < 1){
		  $(elms[i]).css('display', '');
		}
	  }
	}

	if($("#vacancy_categories1").get(0).options.length < 1){
	  if(!vacancy_categories_is_showed){
		vacancy_categories_is_showed = true;		
		$("#vacancy_categories1").after('<label for="vacancy_categories1" generated="true" class="error">'+$.validator.messages['positiveCatergoriesEmplTrn']+'</label>');		
	  }
	}
     return false;
    return true;
}

function numericKey(e)
{
  // Make sure to use event.charCode if available
  var key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);
  // Ignore special keys
  if (e.ctrlKey || e.altKey || key < 48 || key > 57)
    return false;

  key = String.fromCharCode(key);
  return /\w/.test(key);
}

function set_new_prof_form(){
  __jsox_dynamic_param[3] = $('#profl_country_id').val();
  var options = {           	        
    success: send_ajax,
    timeout: 3000
  };
  $('#finish_button_addr').click(function(){          
    if($('#prof_popup').valid()){
      addrPopupSubmit();
      //$('#prof_popup').ajaxSubmit(options);         
    }
    return false;
  });
  /*$('#prof_popup').submit(function() { 
    if($('#prof_popup').valid()){
      profPopupSubmit();
      //$(this).ajaxSubmit(options);
    }
    return false;
  });        */
}

function show_loaded_prof_overlay(overlay_id){
  if(typeof(overlay_id) == 'undefined'){
    overlay_id = null;
  }
  if($('#contact_person').val()>0){
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_employer_profile";
    
    /*
    salutation
    profl_firstname
    profl_email
    
    */
    $.getJSON(requestStr,{id: $('#contact_person').val()}, function(j){
    $('#finish_button_addr').val($('#finish_button_addr').attr('edv'));
      show_overlay('profl_overlay', 'undefined', 'undefined', overlay_id);
       $('#prof_popup').clearForm(); 
      if(j.profile_data.grant_system_access == 1){
        $('#profl_type_id_user').attr('checked','checked');
        $('#profl_type_id_user').change();
      } else {
        $('#profl_type_id_user').attr('checked','');
      }
      if(j.profile_data.grant_system_access == 0){
        $('#profl_type_id_contact').attr('checked','checked');
        $('#profl_type_id_contact').change();
      } else {
        $('#profl_type_id_contact').attr('checked','');
      }
      
      $('#profl_salutation_id').val(j.profile_data.salutation_id);
      $('#profl_lastname').val(j.profile_data.lastname);
      $('#profl_firstname').val(j.profile_data.firstname);
      $('#profl_email').val(j.profile_data.email);
      $('#profl_email2').val(j.profile_data.email);
      $('#profl_password').val(j.profile_data.password);
      $('#profl_password2').val(j.profile_data.password);
      $('#profl_phone').val(j.profile_data.main_phone);
      $('#profl_fax').val(j.profile_data.fax);      
      $("#is_edit_prof").val($('#contact_person').val());
      $('#profl_street').val(j.profile_data.address_street);
      $('#profl_address_house_no').val(j.profile_data.address_house_no);
      $('#profl_address_extra').val(j.profile_data.address_extra);
      $('#profl_zip').val(j.profile_data.zip_code);
      $('#access_levels_box').val(j.profile_data.access_levels_box);
      $('#access_companies_box').val(j.profile_data.access_companies_box);
      for(var i in j.profile_data.cities_list){ 
        if(j.profile_data.cities_list[i].id == j.profile_data.city_id){
          document.getElementById('profl_city_id[text]').value = j.profile_data.cities_list[i].name;
        }
      }
      
      $('#profl_country_state_id').find('option').remove();
      
      for(var i in j.profile_data.countries_state_list){ 
        $('#profl_country_state_id').addOption(j.profile_data.countries_state_list[i].id, j.profile_data.countries_state_list[i].name);
      }
      if(j.profile_data.country_state_id != null)
        $("#profl_country_state_id").selectOptions(j.profile_data.country_state_id);      
      
      $('#profl_country_id').val(j.profile_data.country_id);
      
      __jsox_dynamic_param[3] = j.profile_data.country_id;
      
      $('#profl_language_id').val(j.profile_data.language_id);
      
      //$('#profl_language_id').val(j.profile_data.language_id);---cat
      //$('#profl_language_id').val(j.profile_data.language_id);--prof
      
      clear_multi_selects($('#access_levels'), $('#access_levels1'));
      
      var al = split(';', j.profile_data.access_levels_box);      
      
      opt1 = $('#access_levels').find('option');
      
      for(var i=0;i<al.length;i++){
        if(al[i] > 0){          
          for(var x=0;x<opt1.length;x++){            
            if($(opt1[x]).attr('value') == al[i]){              
              $('#access_levels1').append($(opt1[x]));              
              opt1 = $('#access_levels').find('option');
            }
          }          
        }
      }     
      
      clear_multi_selects($('#access_companies'), $('#access_companies1'));
      var al = split(';', j.profile_data.access_companies_box);
      opt1 = $('#access_companies').find('option');
      for(var i=0;i<al.length;i++){
        if(al[i] > 0){
          for(var x=0;x<opt1.length;x++){
            if($(opt1[x]).attr('value') == al[i]){
              $('#access_companies1').append($(opt1[x]));
              opt1 = $('#access_companies').find('option');
            }
          }          
        }
      }            
      
      $('#prof_popup').validate();
      $('#finish_button_addr').click(function(){
        if($('#prof_popup').valid()){
          addrPopupSubmit();
          //$('#prof_popup').ajaxSubmit(options);         
        }
        return false;
      });	  
      /*$('#prof_popup').submit(function() { 
        if($('#prof_popup').valid()){
          profPopupSubmit();
          //$(this).ajaxSubmit(options); 
        }        
        return false;
      });      */
    });    
  }
}

function send_ajax(responseText, statusText){  
    if(responseText.substring(0, 2) == 'OK'){
      if($('#is_edit_prof').val() == '0'){        
        $("#contact_person").addOption(responseText.substring(2), $('#profl_firstname').val()+' '+$('#profl_lastname').val());      
        $("#contact_person").val(responseText.substring(2));
      } else {
          var opts = $("#contact_person").find('option');
          for(var i=0;i<opts.length;i++){
            if($(opts[i]).val() == $('#contact_person').val()){
              $(opts[i]).html($('#profl_firstname').val()+' '+$('#profl_lastname').val())
            }
          }        
      }      
      $('#addr_close').click();      
      __jsox_dynamic_param[3] = $('#country_id').val();
    }    
  return false;
}

function clear_multi_selects(select1, select2){
  select1.append(select2.find('option'));
  //select2.find('option').remove();
}

function explode (delimiter, string, limit) { 
    var emptyArray = { 0: '' };    
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {        
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
function split (delimiter, string) {
    return this.explode(delimiter, string);
}

function set_new_address_form(){ 
  show_overlay('profl_overlay');
  $('#prof_popup').clearForm();
  $('#delivery_id_email').attr('checked', 'checked');
  $('#country_id').val(curr_dom);
  $('#country_id').change();
  $("#is_edit_prof_id").val('new');    
  $('#prof_popup').validate();  
  $('#finish_button_addr').click(function(){          
    if($('#prof_popup').valid()){
      profPopupSubmit();
      //$('#prof_popup').ajaxSubmit(options);         
    }
    return false;
  });
  /*$('#prof_popup').submit(function() { 
    if($('#prof_popup').valid()){
      profPopupSubmit();
      //$(this).ajaxSubmit(options);         
    }
    return false;
  }); */
}

function show_loaded_address_overlay(){  
  if($('#contact_address').val()>0){
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_employer_address";

    $.getJSON(requestStr,{id: $('#contact_address').val()}, function(j){      
      if(j.loaded){
        show_overlay('profl_overlay');  
        $('#prof_popup').clearForm(); 
        $('#delivery_id_post').attr('checked', 'checked');

        if(j.id != null)
          $("#is_edit_prof_id").val(j.id);
        if(j.street != null)
          $('#street').val(j.street);
        if(j.name != null)
          $('#name').val(j.name);
        if(j.home_number != null)
          $('#home_number').val(j.home_number);
        if(j.extra_address != null)
          $('#extra_address').val(j.extra_address);
        if(j.comment != null)
          $('#comment').val(j.comment);
        if(j.zip_code != null)
          $('#zip_code').val(j.zip_code);
        if(j.city_name != null){        
          //alert(document.getElementById('city_id[text]')).value;
          if(typeof(document.getElementById('city_id[text]')) != null){
            el = document.getElementById('city_id[text]');            
            $(el).val(j.city_name);            
          }
        }
        if(j.country_id != null){
          $('#country_id').val(j.country_id);        
          $('#country_id').change();
        }
		
        if(j.delivery == 'Email'){
          $('#delivery_id_email').attr('checked', 'checked');
        } else {
          $('#delivery_id_post').attr('checked', 'checked');
        }
        if(j.taxnumber != null)
          $('#taxnumber').val(j.taxnumber);
        if(j.contact_person_id != null)
          $('#contact_person_id').val(j.contact_person_id);        

        
        $('#prof_popup').validate();  
        
        $('#finish_button_addr').click(function(){          
          if($('#prof_popup').valid()){
            profPopupSubmit();
            //$('#prof_popup').ajaxSubmit(options);         
          }
          return false;
        });
        
        /*$('#prof_popup').submit(function() {          
          if($('#prof_popup').valid()){            
            profPopupSubmit();
            //$(this).ajaxSubmit(options);         
          }
          return false;
        }); */
      }
    });    
  }
}

function send_ajax_address(responseText, statusText){  
  if(responseText.substring(0, 2) == 'OK'){    
    if($('#is_edit_prof_id').val() == 'new'){        
      $("#contact_address").addOption(responseText.substring(2), $('#name').val());      
      $("#contact_address").val(responseText.substring(2));
    } else {
        var opts = $("#contact_address").find('option');
        for(var i=0;i<opts.length;i++){
          if($(opts[i]).val() == $('#contact_address').val()){
            $(opts[i]).html($('#name').val())
          }
        }        
    } 
    change_dataform();     
    $('#addr_close').click();
  }    
return false;
}

function change_dataform(){
  if($('#contact_address').val()>0){
    
    var ajaxBaseUrl = document.location.href;
    var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
    ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
    var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_get_employer_address";

    $.getJSON(requestStr,{id: $('#contact_address').val()}, function(j){          
      if(j.loaded){
        $addr = $('#b_addr');
        $addr.removeClass('weg');
        $addr.html('');
        $addr.append("" + j.street + " " + j.home_number);
        if (j.extra_address) {
          $addr.append("<br/>" + j.extra_address);
        }
        $addr.append("<br/>" + j.zip_code + " " + j.city_name);
        $addr.append("<br/>" + j.country_name);
        if(j.taxnumber != null){
          if(j.taxnumber.length > 0){
            $('#bs_tax').removeClass('weg');
            $('#b_tax').html(j.taxnumber);
          } else {
              $('#bs_tax').addClass('weg');    
          }
        } else {
          $('#bs_tax').addClass('weg');  
        }
        
        if(j.contact.name_contact != null){
          if(j.contact.name_contact.length > 0){
            $('#bs_contact').removeClass('weg');
            $('#b_contact').html(j.contact.name_contact+'<br />');
          } else {
              $('#bs_contact').addClass('weg');    
          }
        } else {
          $('#bs_contact').addClass('weg');  
        }
        
        if(j.contact.email != null){
          if(j.contact.email.length > 0){
            $('#bs_email').removeClass('weg');
            $('#b_email').html(j.contact.email+'<br />');
          } else {
              $('#bs_email').addClass('weg');    
          }
        } else {
          $('#bs_email').addClass('weg');  
        }
        
        if(j.contact.phone != null){
          if(j.contact.phone.length > 0){
            $('#bs_phone').removeClass('weg');
            $('#b_phone').html(j.contact.phone+'<br />');
          } else {
              $('#bs_phone').addClass('weg');    
          }
        } else {
          $('#bs_phone').addClass('weg');  
        }
        
        if(j.contact.fax != null){          
          if(j.contact.fax.length > 0){
            $('#bs_fax').removeClass('weg');            
            $('#b_fax').html(j.contact.fax);
          } else {
              $('#bs_fax').addClass('weg');    
          }
        } else {
          $('#bs_fax').addClass('weg');  
        }
                
        if(j.delivery != 'Email'){
          $('#invoice_post').removeClass('weg');
          $('#invoice_mail').addClass('weg');
        } else {
          $('#invoice_post').addClass('weg');
          $('#invoice_mail').removeClass('weg');
        }
        
                
        if(j.comment != null){
          if(j.comment.length > 0){            
            $('#bs_comment').removeClass('weg');
            $('#b_comment').html(j.comment);            
          } else {
              $('#bs_comment').addClass('weg');    
          }
        } else {
          $('#bs_comment').addClass('weg');  
        }
        
        
        /*if(j.taxnumber.length != null){
          if(j.taxnumber.length > 0){
            $('#bs_tax').removeClass('weg');
            $('#b_tax').html(taxnumber);
          } else {
              $('#bs_tax').addClass('weg');    
          }
        } else {
          $('#bs_tax').addClass('weg');  
        }*/
  
             
      }


                 
    });    
  }
}

function setSortable(el1, el2, el3){
  opts = $("#"+el2).find('option');
  $("#"+el1).html('');
  for(i=0;i<opts.length;i++){  
    $("#"+el1).html($("#"+el1).html()+'<li isselect="no" value="'+$(opts[i]).val()+'" id="'+el1+'_li_'+$(opts[i]).val()+'">'+$(opts[i]).html()+'</li>');    
    
  }  
  $("#"+el1).find('li').mousedown(function(){ 
    $("#"+el1).find('li').css('background-color','');
    $("#"+el1).find('li').css('color','');
    $("#"+el1).find('li').attr('isselect','no');
    $(this).css('background-color','#0A246A');
    $(this).css('color','#FFFFFF');
    $(this).attr('isselect','yes');
  });
  $("#"+el1).sortable({axis: 'y',cursor: 'default', dropOnEmpty: false, stop: function(event, ui) {
    setSortableSelect(el1, el2, el3);
  }});
}

function setSortableSelect(el1, el2, el3){
  opts = $("#"+el1).find('li');
  $("#"+el2).html('');
  for(i=0;i<opts.length;i++){
    $("#"+el2).html($("#"+el2).html()+'<option value="'+$(opts[i]).attr('value')+'">'+$(opts[i]).html()+'</option>');    
  }
  var postval = "";
  for(var i=0 ; i<document.getElementById(el2).options.length;i++) 
  {
    postval += document.getElementById(el2).options[i].value + ";";
  }
  
  document.getElementById(el3).value = postval; 
}

function setSelectedOption(el1, el2){
  lis = $("#"+el1).find('li');
  opts = $("#"+el2).find('option');
  for(i=0;i<lis.length;i++){
    if($(lis[i]).attr('isselect') == 'yes'){ 
      for(j=0;j<opts.length;j++){
        if($(opts[j]).attr('value') == $(lis[i]).attr('value')){
          $(opts[j]).attr('selected', 'selected');
        }
      }
    }
  }
}

function pushUp(el1, el2, el3){  
  lis = $("#"+el1).find('li');  
  st = document.getElementById(el1+'_d').scrollTop;
  if(lis.length < 1)return null;
  curel = 0;
  elm = 0;
  insearch = true;
  for(i=0;i<lis.length;i++){
    if($(lis[i]).attr('isselect') == 'yes'){
      insearch = false;
      elm = i;
    }
    if(insearch)curel=i;
  }
  if(!insearch){
    txt = '';
    for(i=0;i<lis.length;i++){
      if(i == curel){
        txt += '<li isselect="yes" style="background-color:#0A246A;color:#FFFFFF" value="'+$(lis[elm]).attr('value')+'" id="'+el1+'_li_'+$(lis[elm]).attr('value')+'">'+$(lis[elm]).html()+'</li>';
      } else if(i == elm){
        txt += '<li isselect="no" value="'+$(lis[curel]).attr('value')+'" id="'+el1+'_li_'+$(lis[curel]).attr('value')+'">'+$(lis[curel]).html()+'</li>';        
      } else {
        txt += '<li isselect="no" value="'+$(lis[i]).attr('value')+'" id="'+el1+'_li_'+$(lis[i]).attr('value')+'">'+$(lis[i]).html()+'</li>';
        
      }      
      
    }
    document.getElementById(el1+'_d').scrollTop = st-13;
    $("#"+el1).html(txt);
    $("#"+el1).find('li').mousedown(function(){ 
      $("#"+el1).find('li').css('background-color','');
      $("#"+el1).find('li').css('color','');
      $("#"+el1).find('li').attr('isselect','no');
      $(this).css('background-color','#0A246A');
      $(this).css('color','#FFFFFF');
      $(this).attr('isselect','yes');
    });
    $("#"+el1).sortable({axis: 'y',cursor: 'default', dropOnEmpty: false, stop: function(event, ui) {
      setSortableSelect(el1, el2, el3);
    }});
  }
}

function pushDown(el1, el2, el3){  
  lis = $("#"+el1).find('li');
  st = document.getElementById(el1+'_d').scrollTop;
  if(lis.length < 1)return null;
  curel = -1;
  elm = 0;
  insearch = false;
  for(i=0;i<lis.length;i++){
    if(insearch){
      curel=i;
      insearch = false;
    }
    if($(lis[i]).attr('isselect') == 'yes'){
      insearch = true;
      elm = i;
    }    
  }
  if(curel > 0){
    txt = '';
    for(i=0;i<lis.length;i++){
      if(i == curel){
        txt += '<li isselect="yes" style="background-color:#0A246A;color:#FFFFFF" value="'+$(lis[elm]).attr('value')+'" id="'+el1+'_li_'+$(lis[elm]).attr('value')+'">'+$(lis[elm]).html()+'</li>';
      } else if(i == elm){
        txt += '<li isselect="no" value="'+$(lis[curel]).attr('value')+'" id="'+el1+'_li_'+$(lis[curel]).attr('value')+'">'+$(lis[curel]).html()+'</li>';        
      } else {
        txt += '<li isselect="no" value="'+$(lis[i]).attr('value')+'" id="'+el1+'_li_'+$(lis[i]).attr('value')+'">'+$(lis[i]).html()+'</li>';
        
      }
    }
    document.getElementById(el1+'_d').scrollTop = st+13;
    $("#"+el1).html(txt);
    $("#"+el1).find('li').mousedown(function(){ 
      $("#"+el1).find('li').css('background-color','');
      $("#"+el1).find('li').css('color','');
      $("#"+el1).find('li').attr('isselect','no');
      $(this).css('background-color','#0A246A');
      $(this).css('color','#FFFFFF');
      $(this).attr('isselect','yes');
    });
    $("#"+el1).sortable({axis: 'y',cursor: 'default', dropOnEmpty: false, stop: function(event, ui) {
      setSortableSelect(el1, el2, el3);
    }});
  }
}

function profPopupSubmit(){  
  $('#prof_popup').validate();  
  if(!$('#prof_popup').valid()){
    return false;
  }
  
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_save_address";
  $.ajax(
  {
    async: false,
    timeout: 3000,
    type: 'POST',
    url: requestStr,
    data: { 
      name: $('#name').val(),
      is_edit_prof_id: $('#is_edit_prof_id').val(),
      street: $('#street').val(),
      home_number: $('#home_number').val(),
      extra_address: $('#extra_address').val(),
      zip_code: $('#zip_code').val(),
      city_id: document.getElementById('city_id[text]').value,
      country_id: $('#country_id').val(),
      delivery_id_email: $('#delivery_id_email').attr('checked') ? $('#delivery_id_email').val() : $('#delivery_id_post').val(),
      taxnumber: $('#taxnumber').val(),
      contact_person_id: $('#contact_person_id').val(),
      comment: $('#comment').val()      
    },
    success: function(answ){
      send_ajax_address(answ, 'success');     
    }
  });
}

function addrPopupSubmit(){  
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=jv_save_profile";
  $.ajax(
  {
    async: false,
    timeout: 3000,
    type: 'POST',
    url: requestStr,
    data: { 
      is_edit_prof: $('#is_edit_prof').val(),
      grant_system_access: ($('#profl_type_id_user').attr('checked')?1:0),
      street: $('#street').val(),
      salutation_id: $('#profl_salutation_id').val(),
      lastname: $('#profl_lastname').val(),
      firstname: $('#profl_firstname').val(),
	  email: $('#profl_email').val(),
      email2: $('#profl_email2').val(),
      password: $('#profl_password').val(),
      password2: $('#profl_password2').val(),
      phone: $('#profl_phone').val(),
      fax: $('#profl_fax').val(),
      address_street: $('#profl_street').val(),
      address_house_no: $('#profl_address_house_no').val(),
      address_extra: $('#profl_address_extra').val(),
      zip: $('#profl_zip').val(),
	  city_id: document.getElementById('profl_city_id[text]').value,
      country_id: $('#profl_country_id').val(),
      country_state_id: $('#profl_country_state_id').val(),
      language_id: $('#profl_language_id').val(),
      role_id: $('#profl_role_1').val(),
      access_levels_box: $('#access_levels_box').val(),
      access_companies_box: $('#access_companies_box').val()
    },
    success: function(answ){	
      send_ajax(answ, 'success');     
    }
  });
}

function CVLEtterRequired(){
  if( $('#cover_letter_id').val() > 0){
    $('#cv_id').removeClass('required');
	return true;
  }
  if( $('#cv_id').val() > 0){
    $('#cover_letter_id').removeClass('required');
	return true;
  }
  $('#cv_id').addClass('required');
  $('#cover_letter_id').addClass('required');
  return true;
}

function ClearEmployerSearchForm(){
  $('#country_id').val(curr_domain_country);
  $('#country_id').click();
  $('#country_id').change();  
  
  
  $('#keywords').val('');
  $('#degreetype_id').val(0);
  $('#jobexperience').val(0);
  
  $('#keywords_type_1').click();
  
  $('#show_area_id_5').click();
}

//if ($("#location_tree").get(0)) {
if (typeof(edit_vacancy) != 'undefined' || typeof(edit_search) != 'undefined' || typeof(edit_search_company) != 'undefined' || typeof(edit_search_training) != 'undefined') {

  if (typeof(edit_search) != 'undefined' && edit_search == 'new') {
    var method = 'jv_get_locations_for_search_vacancy';
  } else if (typeof(edit_search_company) != 'undefined' && edit_search_company == 'new') {
    var method = 'jv_get_locations_for_search_company';
  } else if (typeof(edit_search_training) != 'undefined' && edit_search_training == 'new') {
    var method = 'jv_get_locations_for_search_training';
  } else if (typeof(edit_search_training) != 'undefined' && edit_search_training != 'new') {
    var method = 'jv_get_country_city_tree';
  } else {
    var method = 'jv_get_country_state_tree';
  }
  
//  if (typeof(edit_vacancy) != 'undefined') {
//    var method = 'jv_get_country_state_tree';
//  } else {
//    var method = 'jv_get_locations_for_search_vacancy';
//  }
//  alert(method);
  var ajaxBaseUrl = document.location.href;
  var ajaxTemp = ajaxBaseUrl.lastIndexOf("/") + 1;
  ajaxBaseUrl = ajaxBaseUrl.substring(0, ajaxTemp);
  var requestStr = ajaxBaseUrl + "index.html?__ajaxMethod=" + method;
  
  $(function () {
      $("#location_tree").tree({
          ui: {
              theme_name: "checkbox"
          },
          data: {
              type: "json",
              opts: {
                  method: "POST",
                  url: requestStr                  
              }
          }, 
          plugins: {
              checkbox: {}
          },
          callback: {
              onload: function (tree) {
                  /*$('li[selected=true]').each(function () {
                      $.tree.plugins.checkbox.check(this);
                  });*/
                  //alert($("#location_tree_list").val());
                  var location_tree_list = $("#location_tree_list").val();
                  //location_tree_list = 'state_20, state_23, country_44, 4444';
                  var init_states = location_tree_list.split(';');
                  if (init_states) {
                    for(var i=0; i<init_states.length; i++) {
                      state = init_states[i].replace(/(^\s+)|(\s+$)/g, "");
                      if (state) { 
                        var tree_node = $("li[id="+state+"]");
                        if ($("li[id="+state+"]").get(0)) {
                          $.tree.plugins.checkbox.check(tree_node);
                        }
                      }
                    }
                  }
                  $("#location_tree").find("ul.ltr > li").each(function () {
                     if($(this).children("ul").size() == 0) {
                       $(this).removeClass('open').removeClass('closed').addClass('leaf');
                     } else {
                      $(this).find("ul > li").each(function () {
                        $(this).removeClass('open').removeClass('closed').addClass('leaf');
                      });
                     }
                  });
              } ,
              onchange: function (tree) {
                  //$("#location_tree_list").val("");
                  var chk = $.tree.plugins.checkbox.get_checked();
                  var res = '';
                  for(var i=0; i<chk.length; i++){
                     var item = chk[i];
                     res = res + ';'+ item.id;
                  }
                  $("#location_tree_list").val(res);
              }
          }
      });

      if (typeof(edit_search) != 'undefined' || typeof(edit_search_company) != 'undefined' || typeof(edit_search_training) != 'undefined') {
        $("#eintrag").submit(function () {
          if($('#eintrag').valid()){
            var leaf = 'state';
            if (typeof(edit_search_training) != 'undefined') {
              leaf = 'city';
            }
            generateHiddenFieldsForSearch("location_tree", leaf); 
          }
        });
      }
  });

  function generateHiddenFieldsForSearch(treeId, leaf) {
      if ($("#" + treeId).length === 0) {
          alert("invalid treeId for generateHiddenFieldsForSearch");
          return;
      }
      $('#location_inputs').empty();
      
      if (!$("#location_tree_list").val()) {
        return true;
      }
      
      $('#location_tree_list').remove();
      $('#location_inputs').append('<select id="country_id"       name="country_id[]"       multiple="multiple"></select>');
      if (leaf == 'city') {
        $('#location_inputs').append('<select id="city_id" name="city_id[]" multiple="multiple"></select>');
      } else {
        $('#location_inputs').append('<select id="country_state_id" name="country_state_id[]" multiple="multiple"></select>');
      }
      $.tree.plugins.checkbox.get_checked($.tree.reference("#" + treeId)).each(function () {
      
          var t = $.tree.reference(this);
          var skip = false;
          n = t.get_node(this);
          n.parents("li").each(function () { 
            if ($(this).parents("li").andSelf().children("a").hasClass("checked")) {
              //alert(this.id);
              skip = true;
            }
          });
            
          var checkedId = this.id;
          var type = null;
          if (checkedId.indexOf('country_')!=-1) {
            type = 'country';
          } else if (checkedId.indexOf('state_')!=-1) {
            type = 'country_state';
          } else if (checkedId.indexOf('city_')!=-1) {
            type = 'city';
          } 
          if (type && !skip) {
            var tmp = checkedId.lastIndexOf("_") + 1;
            var id = checkedId.substring(tmp);
            $('#location_inputs > #'+type+'_id').append('<option value="'+id+'" selected="selected"/>');
            //alert($('#location_inputs').html());
          }
      });
      return false;
  }

//  function generateHiddenFieldsForTree(treeId) {
//      if ($("#" + treeId).length === 0) {
//          alert("invalid treeId for generateHiddenFieldsForTree");
//          return;
//      }

//      $.tree.plugins.checkbox.get_checked($.tree.reference("#" + treeId)).each(function () {
//          var checkedId = this.id;
//          $("<input>").attr("type", "hidden").attr("name", checkedId).val("on").appendTo("#" + treeId);
//      });
//  }
    
}

