function apply_bubble() {
  $('.bubbleInfo').each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.trigger', this);
    var popup = $('.popup', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element      
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: -100,
          left: -33,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
}


function ajax_check_field(field_name, field_value, lang){      
	url = "http://"+document.location.hostname+"/scripts/check_field.php";	
	http_request = false;

        if (window.XMLHttpRequest) { 
            http_request = new XMLHttpRequest();            
        } else if (window.ActiveXObject) { 
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Cannot create an XMLHTTP instance');
            return false;
        }
        
        httpstr = "fname=" + field_name + "&fvalue=" + field_value + "&lang=" + lang;
	        
        http_request.open('POST', url, false);
	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http_request.send(httpstr);
return http_request.responseText;
}

function change_nomination_list(kid,nid,lang,tmpl_id,u_id,wid){               
        url = "http://"+document.location.hostname+"/scripts/change_nomination_list.php";	
	http_request = false;

        if (window.XMLHttpRequest) { 
            http_request = new XMLHttpRequest();            
        } else if (window.ActiveXObject) { 
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Cannot create an XMLHTTP instance');
            return false;
        }
  
        if(!wid){wid=0;}     
        httpstr = "kid=" + kid + "&lang=" + lang + "&nid=" + nid + "&tmpl_id=" + tmpl_id + "&u_id=" + u_id + "&wid=" + wid;
	        
        http_request.open('POST', url, false);
	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http_request.send(httpstr);
        if(!tmpl_id){
          if(!nid){
            document.getElementById('nominat').innerHTML = "<span id=\"nomination_warn\" class=\"wf\"><select name=\"f_nomination\" onChange=change_nomination_list("+document.adminForm.f_konkurs.value+",this.value,'"+lang+"',0,"+u_id+")>"+http_request.responseText+"</select></span><img src=\"/images/asterisk_odd.gif\" alt=\"*\" />";
          }else{
            if(document.getElementById('work_serie')){
              document.getElementById('work_serie').innerHTML = "<span id=\"sid_warn\" class=\"wf\"><select name=\"f_sid\" onChange=fill_work_fields_for_serie(this.value,"+u_id+",'"+lang+"') ><option value=0></option>"+http_request.responseText+"</select></span>";
            }
          }
        }else{
          document.getElementById('add_fields').innerHTML = http_request.responseText;

          if(kid==24 || kid==25){
             if(document.getElementById('dra_idea')){
            document.getElementById('dra_idea').innerHTML = "<div class='bubbleInfo'><span class='trigger' id='idea'><a href=# class='js'>Как заполнять?</a></span><div class='popup'>Правила предоставления креативных материалов:\
								<ul>\
									<li>Активная URL ссылка на каждый креативный элемент кампании. Пожалуйста, убедитесь в том, что все ссылки работают, неработающая ссылка может привести к дисквалификации.\
									<li>Информация для входа в систему (если требуется) - логин, пароль.\
									<li>Дополнительные инструкции (к примеру, 'нажмите на данную кнопку')\
									<li>Не обязательно, но очень рекомендуется предоставить видео не длиннее 5 минут.\
								</ul></div></div>\
                                                            ";
            }
          }else if(kid==26){
             if(document.getElementById('dra_idea')){
            document.getElementById('dra_idea').innerHTML = "<div class='bubbleInfo'><span class='trigger' id='idea'><a href=# class='js'>Как заполнять?</a></span><div class='popup'>Правила предоставления креативных материалов:\
								<ul>\
									<li>Активная URL ссылка на каждый креативный элемент инструмента. Пожалуйста, убедитесь в том, что все ссылки работают, неработающая ссылка может привести к дисквалификации.\
									<li>Информация для входа в систему (если требуется) - логин, пароль.\
									<li>Дополнительные инструкции (к примеру, 'нажмите на данную кнопку')\
									<li>Не обязательно. Но очень рекомендуется предоставить Power Point презентацию с иллюстрациями идеи, не более 5 слайдов.\
								</ul></div></div>\
                                                            ";
           }
          }else{
		   
            if(document.getElementById('dra_idea')){document.getElementById('dra_idea').innerHTML = "";}
          }

          apply_bubble();
        }
return 1;
}

function change_konkurs_list(kid,nid,lang,tmpl_id,u_id,wid,fest_id,is_serie){
        url = "http://"+document.location.hostname+"/scripts/change_konkurs_list.php";	
	http_request = false;

        if (window.XMLHttpRequest) { 
            http_request = new XMLHttpRequest();            
        } else if (window.ActiveXObject) { 
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Cannot create an XMLHTTP instance');
            return false;
        }
  
        if(!wid){wid=0;}     
        httpstr = "kid=" + kid + "&lang=" + lang + "&nid=" + nid + "&tmpl_id=" + tmpl_id + "&u_id=" + u_id + "&wid=" + wid + "&fest_id=" + fest_id;
	        
        http_request.open('POST', url, false);
	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http_request.send(httpstr);
        if(!is_serie){
          document.getElementById('konkurs').innerHTML = "<span id=\"konkurs_warn\" class=\"wf\"><select name=\"f_konkurs\" onChange=change_nomination_list(this.value,0,'"+lang+"',0,"+u_id+");change_nomination_list(this.value,document.adminForm.f_nomination.value,'"+lang+"',0,"+u_id+");change_nomination_list(this.value,0,'"+lang+"',86,"+u_id+");>"+http_request.responseText+"</select></span><img src=\"/images/asterisk_odd.gif\" alt=\"*\" />";
        }else{
          document.getElementById('konkurs').innerHTML = "<span id=\"konkurs_warn\" class=\"wf\"><select name=\"f_konkurs\" onChange=change_nomination_list(this.value,0,'"+lang+"',0)>"+http_request.responseText+"</select></span><img src=\"/images/asterisk_odd.gif\" alt=\"*\" />"; 
        }

return 1;
}

function validate_form(step,reg_type,lang){
  err_str='';
  document.getElementById('warn').style.display='none';
  document.getElementById('warn').innerHTML='';
  
  if(step==99&&document.getElementById('s_e')){document.getElementById('s_e').style.display='none';}

  $('.wf').removeClass('wr'); 
  if(step==99){is_valid=1;}
  if(step==1 || step==99){
     if(step!=99){is_valid=1;} 
     if(step!=99){
       valid_res = ajax_check_field('login', document.adminForm.f_Login.value, lang);
     }else{
       if(document.adminForm.f_Login.value==document.adminForm.Login_old.value){
         valid_res = 1;
       }else{
	 valid_res = ajax_check_field('login', document.adminForm.f_Login.value, lang);
       } 
     }
     
     if(document.adminForm.f_Login.value==''){ 
       $('#Login_warn').addClass('wr');      
       err_str+=c_empty_login+'<br>';
       is_valid=0;
     }else if(valid_res!=1){
       $('#Login_warn').addClass('wr');
       err_str+=valid_res;
       is_valid=0;
     }

     if(step!=99){
       if(document.adminForm.Password1.value==''){
         $('#Password1_warn').addClass('wr');
         err_str+=c_empty_pwd+'<br>';
         is_valid=0;
       }
       if(document.adminForm.Password1.value!=document.adminForm.Password2.value){
         $('#Password1_warn').addClass('wr');
         $('#Password2_warn').addClass('wr');
         err_str+=c_pwd_not_equal+'<br>';
         is_valid=0;
       }
     } 
    
     if(document.adminForm.f_country_en.value==''){
       $('#country_en_warn').addClass('wr'); 
       err_str+=c_empty_country_en+'<br>';
       is_valid=0;
     }

     if(document.adminForm.f_town_en.value==''){
       $('#town_en_warn').addClass('wr');
       err_str+=c_empty_city_en+'<br>';
       is_valid=0;
     } 

  }
  if(step==2 || step==99){
     if(step!=99){is_valid=1;}
     if(reg_type==1){

       if(document.adminForm.Name.value==''){
          $('#Name_warn').addClass('wr');
          err_str+=c_empty_name+'<br>';
          is_valid=0;
       }
       if(document.adminForm.LastName.value==''){
          $('#LastName_warn').addClass('wr');
          err_str+=c_empty_surname+'<br>';
          is_valid=0;
       }

     }else if(reg_type==2){
       
       if(document.adminForm.Name_en.value==''){
          $('#Name_en_warn').addClass('wr');
          err_str+=c_empty_company_name_en+'<br>';
          is_valid=0;
       }
       if(document.adminForm.org_MailIndex.value==''){
          $('#org_MailIndex_warn').addClass('wr');
          err_str+=c_empty_area_en+'<br>';
          is_valid=0;
       }
       if(document.adminForm.RegisteredName.value==''){
          $('#RegisteredName_warn').addClass('wr');
          err_str+=c_empty_legal_name+'<br>';
          is_valid=0;
       }
       if(document.adminForm.LegalAddress.value==''){
          $('#LegalAddress_warn').addClass('wr');
          err_str+=c_empty_legal_address+'<br>';
          is_valid=0;
       }
       if(document.adminForm.RealAddress.value==''){
          $('#RealAddress_warn').addClass('wr');
          err_str+=c_empty_real_address+'<br>';
          is_valid=0;
       }

     }else{
       is_valid=0;
     } 
  }
  if(step==3 || step==99){
     if(step!=99){is_valid=1;}
     if(reg_type==1){

       if(document.adminForm.Phone.value==''){
          $('#Phone_warn').addClass('wr');
          err_str+=c_empty_phone+'<br>';
          is_valid=0;
       }
       if(step!=99){
         valid_res = ajax_check_field('email', document.adminForm.email.value, lang);
       }else{
         if(document.adminForm.email.value==document.adminForm.email_old.value){
           valid_res = 1; 
         }else{
           valid_res = ajax_check_field('email', document.adminForm.email.value, lang);
         }
       }
 
       if(document.adminForm.email.value==''){
          $('#email_warn').addClass('wr'); 
          err_str+=c_empty_email+'<br>';
          is_valid=0;
       }else if(valid_res!=1){
          $('#email_warn').addClass('wr'); 
          err_str+=valid_res;
          is_valid=0;
       }else{
          document.adminForm.f_Email.value=document.adminForm.email.value;
       }

     }else if(reg_type==2){

       if(document.adminForm.org_phone.value==''){
          $('#org_phone_warn').addClass('wr');
          err_str+=c_empty_phone+'<br>';
          is_valid=0;
       }

       if(step!=99){
         valid_res = ajax_check_field('email', document.adminForm.org_email.value, lang);
       }else{
         if(document.adminForm.org_email.value==document.adminForm.org_email_old.value){
           valid_res = 1;
         }else{
           valid_res = ajax_check_field('email', document.adminForm.org_email.value, lang);
         }
       }
 
       if(document.adminForm.org_email.value==''){
          $('#org_email_warn').addClass('wr');
          err_str+=c_empty_email+'<br>';
          is_valid=0;
       }else if(valid_res!=1){
          $('#org_email_warn').addClass('wr');
          err_str+=valid_res;
          is_valid=0;
       }else{
          document.adminForm.f_Email.value=document.adminForm.org_email.value;
       }

       if(document.adminForm.org_contact.value==''){
          $('#org_contact_warn').addClass('wr');
          err_str+=c_empty_contacts+'<br>';
          is_valid=0;
       }

     }else{
       is_valid=0;
     } 
  }

  if(is_valid==1){ 
     if(step!=99){    
       show_next_page(step,reg_type,lang);
     }else{
       document.adminForm.submit();
     }
  }else{
    //вывод инф. о неправильно заполненных полях
     document.getElementById('warn').innerHTML=err_str;
     document.getElementById('warn').style.display='block';
  }  
}

function show_next_page(step,reg_type,lang){
  if(step==1){
    if(lang=='ru'){
      document.getElementById('step_block').innerHTML='<img src=\"/images/reg_step_two.jpg\" class=\"reg_step\" alt=\"2\" />';
    }else{
      document.getElementById('step_block').innerHTML='<img src=\"/images/reg_step_two_en.jpg\" class=\"reg_step\" alt=\"2\" />';
    }
    if(reg_type==1){
      document.getElementById('step1_common').style.display='none';
      document.getElementById('step2_individual').style.display='block';       
    }else if(reg_type==2){
      document.getElementById('step1_common').style.display='none';
      document.getElementById('step2_organization').style.display='block';
    }
  }else if(step==2){
    if(lang=='ru'){ 
      document.getElementById('step_block').innerHTML='<img src=\"/images/reg_step_three.jpg\" class=\"reg_step\" alt=\" 3\" />';
    }else{
      document.getElementById('step_block').innerHTML='<img src=\"/images/reg_step_three_en.jpg\" class=\"reg_step\" alt=\" 3\" />'; 
    }
    if(reg_type==1){
      document.getElementById('step2_individual').style.display='none'; 
      document.getElementById('step3_individual').style.display='block';      
    }else if(reg_type==2){
      document.getElementById('step2_organization').style.display='none'; 
      document.getElementById('step3_organization').style.display='block';
    }    
  }else if(step==3){
    document.adminForm.submit();
  }
}

function form_add_btn(lang){
  err_str='';
  document.getElementById('warn').style.display='none';
  document.getElementById('warn').innerHTML='';
  if(document.getElementById('s_e')){document.getElementById('s_e').style.display='none';}
  $('.wf').removeClass('wr');
  is_valid=1;

  if(document.adminForm.f_name.value=='' && lang=='ru'){
       $('#name_warn').addClass('wr'); 
       err_str+=c_empty_s_name_ru+'<br>';
       is_valid=0;
  }else if(lang=='en'){
       document.adminForm.f_name.value = document.adminForm.f_en_name.value;
  }

  if(document.adminForm.f_en_name.value==''){
       $('#en_name_warn').addClass('wr'); 
       err_str+=c_empty_s_name_en+'<br>';
       is_valid=0;
  }

  if(is_valid==1){ 
       document.adminForm.submit();
  }else{
       document.getElementById('warn').innerHTML=err_str;
       document.getElementById('warn').style.display='block';
  }
}

function form_add_work_btn(lang,ftype,kid){
  err_str='';
  document.getElementById('warn').style.display='none';
  document.getElementById('warn').innerHTML='';
  if(document.getElementById('s_e')){document.getElementById('s_e').style.display='none';}
  $('.wf').removeClass('wr');
  is_valid=1;

  if(ftype){
	if(document.adminForm.f_name.value=='' && lang=='ru'){
       	  $('#name_warn').addClass('wr'); 
          if(ftype==1){
       	    err_str+=c_empty_wi_name_ru+'<br>';
          }else if(ftype==2){
            err_str+=c_empty_wf_name_ru+'<br>';
	  }else if(ftype==3){
            err_str+=c_empty_wsf_name_ru+'<br>';
	  }else if(ftype==4){
 	    err_str+=c_empty_vm_name_ru+'<br>';
	  }
       	  is_valid=0;
  	}else if(lang=='en'){
       	  document.adminForm.f_name.value = document.adminForm.f_en_name.value;
  	}

  	if(document.adminForm.f_en_name.value==''){
       	  $('#en_name_warn').addClass('wr'); 
	  if(ftype==1){
       	    err_str+=c_empty_wi_name_en+'<br>';
          }else if(ftype==2){
            err_str+=c_empty_wf_name_en+'<br>';
	  }else if(ftype==3){
            err_str+=c_empty_wsf_name_en+'<br>';
	  }else if(ftype==4){
 	    err_str+=c_empty_vm_name_en+'<br>';
	  }
       	  is_valid=0;
  	}    

        if(ftype==4){
          if(document.adminForm.f_work_vm_code.value==''){
            $('#work_vm_code_warn').addClass('wr');
            err_str+=c_empty_vm_code+'<br>';
            is_valid=0;
          }
        }
  }else{
       //work add or edit
       err_str+=check_field_valid('f_name','f_en_name',lang,c_empty_w_name_ru,c_empty_w_name_en,'name');     
       err_str+=check_field_valid('f_advert_product','f_en_advert_product',lang,c_empty_ap_ru,c_empty_ap_en,'advert_product');       

       if((kid>0 && kid<10) || kid==13 || kid==22){
         err_str+=check_field_valid('f_advert_agency','f_en_advert_agency','en',c_empty_aa_ru,c_empty_aa_en,'advert_agency');       
         err_str+=check_field_valid('f_production_studio','f_en_production_studio','en',c_empty_ps_ru,c_empty_ps_en,'production_studio');       
         err_str+=check_field_valid('f_advert_customer','f_en_advert_customer','en',c_empty_ac_ru,c_empty_ac_en,'advert_customer');       
       }
                     
       if(kid==5){
         if(document.adminForm.f_w_url.value==''){
           $('#w_url_warn').addClass('wr');
           err_str+=c_empty_url+'<br>';          
         }
       }    

       err_str+=check_field_valid('f_idea_descr','f_en_idea_descr',lang,c_empty_idea_ru,c_empty_idea_en,'idea_descr');       
       
       if(err_str!=''){
         is_valid=0;
       } 
  }
  

  if(is_valid==1){ 
       document.adminForm.submit();
  }else{
       document.getElementById('warn').innerHTML=err_str;
       document.getElementById('warn').style.display='block';
  }
}

function check_field_valid(fname,fname_en,lang,ru_err,en_err,warn_name){
  err_str_res='';
  if(document.adminForm[fname].value=='' && lang=='ru'){
     $('#'+warn_name+'_warn').addClass('wr'); 
     err_str_res+=ru_err+'<br>';     
  }else if(lang=='en'){
     document.adminForm[fname].value = document.adminForm[fname_en].value;
  }

  if(document.adminForm[fname_en].value==''){
     $('#en_'+warn_name+'_warn').addClass('wr'); 
     err_str_res+=en_err+'<br>';
  }
  return err_str_res;
}


function change_contest(cid,obj){
  
  show_content(cid);
		
  $('.dl_block dt').removeClass('open');
  $(obj).addClass('open');
		
  $('.dl_block dd.dd_block').hide();
  $('#dd_' + cid).show();
}

function show_content(cid){
  if($('#desc_' + cid).html()){         
     var desc_html = $('#desc_' + cid).html();
     $('#rb_desc').empty();
     $('#rb_desc').append(desc_html);
  }
  
  $('.nc_row .right_block .pretext').remove();
  $('.nc_row .right_block').append("<div class='pretext'>"+$('#pretext_'+cid).html()+"</div>");
}

function show_auth_form(){
  var cur_state = $('#auth_form_block').css('display');
  if(cur_state=='none'){
    $('#auth_form_block').css({'display':'block'});
    $('#search_auth_block').css({'display':'none'});
  }else{
    $('#auth_form_block').css({'display':'none'});
    $('#search_auth_block').css({'display':'block'});
  }
}

function change_auth_ch_img(){
check_flag = $('input[name=\"loginsave\"]').attr('checked');

if(check_flag===true){
  var img_html = '<img src=\"/images/auth_chbox.gif\" alt=\"\" />';
  $('input[name=\"loginsave\"]').attr('checked', false);
}else{
  var img_html = '<img src=\"/images/auth_chbox_ch.gif\" alt=\"\" />';
  $('input[name=\"loginsave\"]').attr('checked', true);
}

$('#auth_ch_img').empty();
$('#auth_ch_img').append(img_html);

}

function input_focus(id, v) {
	$(id).focus(function() {
		if ($(this).val() == v) {
			$(this).val('');
		}
	}).blur(function() {
		if($(this).val() == '') {
			$(this).val(v);
		}
	});
}

function change_partn(cid,obj){  
  $('.nav_f_partners li').removeClass('state');
  $(obj).addClass('state');
		
  $('.partn').hide();
  $('#partn_' + cid).show();
}

function form_create_bill_btn(){
  err_str='';
  document.getElementById('warn').style.display='none';
  document.getElementById('warn').innerHTML='';
  is_valid=1;

  if(document.bill_form.bill_curr.value == 0 || document.bill_form.bill_curr.value == ''){
       err_str+=c_empty_curr+'<br>';
       is_valid=0;
  }

  if(is_valid==1){ 
       document.bill_form.submit();
       //document.getElementById('s_e').style.display='block';
       //document.getElementById('p_b').style.display='none';
  }else{
       document.getElementById('warn').innerHTML=err_str;
       document.getElementById('warn').style.display='block';
  }  
}

function del_btn(frm_name){
  if(window.confirm(c_del_confirm)==true){     
    document[frm_name].submit(); 
  }
}

function form_add_accr(){
  err_str='';
  document.getElementById('warn').style.display='none';
  document.getElementById('warn').innerHTML='';
  if(document.getElementById('s_e')){document.getElementById('s_e').style.display='none';}
  $('.wf').removeClass('wr');
  is_valid=1;

  if(document.adminForm.f_name.value==''){
       $('#name_warn').addClass('wr'); 
       err_str+=c_empty_name_accr+'<br>';
       is_valid=0;
  }

  if(document.adminForm.f_company.value==''){
       $('#company_warn').addClass('wr'); 
       err_str+=c_empty_company_accr+'<br>';
       is_valid=0;
  }
  
  if(document.adminForm.f_position.value==''){
       $('#position_warn').addClass('wr'); 
       err_str+=c_empty_post_accr+'<br>';
       is_valid=0;
  }

  if(is_valid==1){ 
       document.adminForm.submit();
  }else{
       document.getElementById('warn').innerHTML=err_str;
       document.getElementById('warn').style.display='block';
  }
}
function fill_work_fields_for_serie(s_id,u_id,lang){
	url = "http://"+document.location.hostname+"/scripts/fill_work_fields_for_serie.php";	
	http_request = false;

        if (window.XMLHttpRequest) { 
            http_request = new XMLHttpRequest();            
        } else if (window.ActiveXObject) { 
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Cannot create an XMLHTTP instance');
            return false;
        }
               
        httpstr = "s_id=" + s_id + "&lang=" + lang + "&u_id=" + u_id;
	        
        http_request.open('POST', url, false);
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http_request.send(httpstr);
		if(http_request.responseText!=""){
			eval(http_request.responseText);
		}
return 1;
}
