// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function wait() {
  var obj = document.getElementById('wait_id');
  obj.style.display='block';
}

function check_all(form_name) {
  for(i=0; i<form_name.elements.length; i++) {
    if(form_name.elements[i].type=='checkbox'){
      if(form_name.elements[i].checked==true){
        form_name.elements[i].checked=false;
      } else {
        form_name.elements[i].checked=true;
      }
    }
  };
}
// функцию нужно вешать на линк если вам нужно сделать post запрос с подтверждеием и защитой от повторного нажатия
function confirm_and_do_once(text,button,method)
{   if (!method) method = 'POST';

    if(button.disabled == true) return false;
    if (confirm(text))
    {

        if(do_once(button))
        {
            var f = document.createElement('form');
            f.style.display = 'none';
            button.parentNode.appendChild(f);
            f.method = 'POST';
            f.action = button.href;
            var m = document.createElement('input');
            m.setAttribute('type', 'hidden');
            m.setAttribute('name', '_method');
            m.setAttribute('value', method);
            f.appendChild(m);            
            f.submit();
        }

    }
    return false;

}
// выпоняет декоративную функцию
function do_once_modalbox(button)
{
    try{
            Modalbox.show($('please_wait'), {title: button.title||button.value, width: 600});
            Modalbox.deactivate();
            setTimeout("Modalbox.activate();Modalbox.show($(\'waiting_failed\'));",60000);
    }
    catch(e){}
}

// дает пользователю еще одну возможность послать запрос, если ответ небыл получем (например, в следствии плохой связи)
function cancel_do_once(button,img)
{
   button.disabled = false;
   button.style.color="#fff";
   img.remove();

}

function do_once_done(button)
{
   button = $(button);
   button.disabled = false;
   remove_spin(button.id);

}

function remove_spin(button_id)
{
    existing =$(button_id+'_do_once_spinner');
    if(existing) (existing.remove());
}
function attach_spin(button)
{
       if(button.id){
           existing =$(button.id+'_do_once_spinner');
           if(existing) return existing; 
       }

        button.style.color="#444";
        var f = document.createElement('img');
        f.src= '/picto/ajax-loader.gif';
        if(button.id)f.id=button.id+'_do_once_spinner';
        f.class_name= 'do_once_spinner';
        button.parentNode.appendChild(f);
        return f;
}

function do_once_no_wait(button)
{
    try{
        if(button.disabled == true) return false;
        button.disabled = true;
        var f = attach_spin(button);
    }
    catch(e)
    {
        button.style.display="none";
    }
    return true;

}

function do_once(button)
{
    try{
        if(button.disabled == true) return false;
        button.disabled = true;
        var f = attach_spin(button);
        setTimeout(cancel_do_once, 30000, button,f); // пол минуты на выполнение запроса, потом даем 2 шанс на сабмит
        setTimeout(do_once_modalbox,5000,button); // если выполнение затягивается покажем пользователю красивый сплеш, чтобы он не волновался

    }
    catch(e)
    {
        button.style.display="none";
    }
    return true;

}

function switch_display_by_id(id) {
 var element = document.getElementById(id);
 if (element.style.display != 'none') {
   element.style.display = 'none';
   if (id == 'php_code') {
	$('isphp').className='codes';
   }
   if (id == 'perl_code') {
	$('isperl').className='codes';
   }
   if (id == 'not_code') {
	$('isresolved').className='codes';
   }   
 } else {
   element.style.display = 'block';
   if (id == 'php_code') {
	$('isphp').className='codes uped';
   }
   if (id == 'perl_code') {
	$('isperl').className='codes uped';
   }
   if (id == 'not_code') {
	$('isresolved').className='codes uped';
   }
   if (id == 's_form') {
	element.style.display = '';
   }  
 }
}

function check_all_by_id(id,checkbox_id){
  var tbs=document.getElementById(id).getElementsByTagName('INPUT');
  var checkbox_status = document.getElementById(checkbox_id);
  for (var zxc0=0;zxc0<tbs.length;zxc0++){
    if(checkbox_status.title!='Отметить все'){
      tbs[zxc0].checked=false;
    } else {
      tbs[zxc0].checked=true;
    }
  }
  if(checkbox_status.title!='Отметить все'){
    checkbox_status.title='Отметить все';
  } else {
    checkbox_status.title='Снять все';
  }
}

function show_hide_tabs($site_id) {
        var $t = document.getElementById($site_id);
        if ($t.style.display == "none") {
            $t.style.display = "block";
        } else {
            $t.style.display = "none";
        }
        return false;
}

// Отображение урлов для данного проекта через Ajax
function display_table(id) {
    var obj = document.getElementById(id);
    var div_obj = document.getElementById('updated_' + id);
    var ids = new Array();
    var ids_new = new Array();
    var ids_string;
    var exist_in_array = '0';
    opened_projects=getCookie('opened_projects');
    if (opened_projects!=null && opened_projects!=""){
      ids_string = opened_projects;
      ids = ids_string.split(', ');
    }
    if (obj.title == 'Показать урлы данного проекта') {
      div_obj.style.display = 'block';
      obj.title = 'Скрыть урлы данного проекта';
      for(i=0; i<ids.length; i++){
        if (ids[i] == id) {
          exist_in_array = '1';
        }
      }
      if (exist_in_array == '0') {ids.push(id);}
      setCookie('opened_projects',ids.join(', '),1);
    } else {
      obj.title = 'Показать урлы данного проекта';
      div_obj.style.display = 'none';
      for(i=0; i<ids.length; i++){
        if (ids[i] != id) {
          ids_new.push(ids[i]);
        }
      }
      setCookie('opened_projects',ids_new.join(', '),1);
    }
}

function display_table_only(id) {
    var obj = document.getElementById(id);
    var div_obj = document.getElementById('updated_' + id);
    if (!obj) {
      clearCookie('opened_projects');
    } else {
    if (obj.title == 'Показать урлы данного проекта') {
      div_obj.style.display = 'block';
      obj.title = 'Скрыть урлы данного проекта';
    } else {
      obj.title = 'Показать урлы данного проекта';
      div_obj.style.display = 'none';
    }
    }
}

function clearCookie(c_name){
    setCookie(c_name,'',1);
}

// Отображение урлов для всех проектов
function open_all(str) {
    setCookie('opened_projects',str,1);
    var ids = new Array();
    ids = str.split(', ');
    for(i=0; i<ids.length; i++){
      var obj = document.getElementById(ids[i]);
      var div_obj = document.getElementById('updated_' + ids[i]);
      if (obj.title == 'Показать урлы данного проекта') {
        div_obj.style.display = 'block';
        obj.title = 'Скрыть урлы данного проекта';
      }
    }
}

function reset_by_id(id, checked) {
    obj = document.getElementById(id);
    obj.value = '';
    obj.disabled = (!checked);
}

function toggle_auto($enable) {
    obj_auto = document.getElementById('auto_part');
    obj_manual = document.getElementById('manual_part');
    if($enable == 'auto' || $enable == 'semi_auto') {
      $message = $msg_auto_mode_on;
      obj_auto.style.display='block';
      obj_manual.style.display='none';
    } else {
      $message = $msg_manual_mode_on;
      obj_auto.style.display='none';
      obj_manual.style.display='block';
    }
}

function alert_auto() {
    if ($message.length > 0) {
      alert($message);
    }
}

function setCookie(c_name,value,expiredays,path){
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
  ((path==null || path=="") ? "" : "; path="+path);
}

function getCookie(c_name){
  if (document.cookie.length>0){
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1){
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

function replyWithTemplate(templateText){
  text = $('content').value
  lines = text.split("\n")
  count = 0
  counted = false
  lines.each(function(l){
    if(l[0] == '>') {
      if(!counted){
        count++
      }
      else
      {
        counted = true
      }
    }
  })
  newlines = []
  for(i=0; i<count; i++){
    newlines.push(lines[i]);
  }
  newtext = newlines.join("\n") + "\n\n" + templateText;
  $('content').value = newtext

}

// Раскрывание всех площадок при поиске
function open_all_platforms(str, fold_msg, unfold_msg) {
    var expire_days = 7;
    var obj_button = document.getElementById('open_all_button');
    if(obj_button.innerHTML == unfold_msg) { // 'Развернуть все'
      display = 'block';
      anchor  =  fold_msg;  // 'Свернуть все'
    } else {
      display = 'none';
      anchor  = unfold_msg; // 'Развернуть все'
    }
    setCookie('opened_tree',display,expire_days,'/');
    obj_button.innerHTML = anchor;

    var ids = new Array();
    ids = str.split(', ');
    for(i=0; i<ids.length; i++){
      var obj = document.getElementById(ids[i]);
      var div_obj = document.getElementById(ids[i]);
      div_obj.style.display = display;
    }
}


function pretty_alert(text,title)
{
    if(typeof(Modalbox) != "undefined")
    {
        Modalbox.show(text,{title:title});        
    }
    else
    {
       alert(title+"\n\n"+text);
    }
    
}

function check_article_content() {
    
    article = document.getElementById('publication_request_url')    
    announce = document.getElementById('publication_request_announce_url')
    if(article.value == '' || announce.value == ''){
       $('publish_button').enable();
       $('publish_button').value = "Опубликовано"; // FIXME i18n javascripts
       pretty_alert("Некоторые поля не запонены","Ошибка")
       return false;
    }
    var uri_article  = article.value;
    var uri_announce = announce.value;
    uri_announce = encodeURIComponent(uri_announce);
    uri_article = encodeURIComponent(uri_article);

    document.getElementById('submit_spinner').style.display = 'inline';

    new Ajax.Request('/uri-content/?uri=' + uri_announce, {
        onComplete: function(transport1) {
          new Ajax.Request('/uri-content/?uri=' + uri_article, {
              onComplete: function(transport2) {
                document.create_form.submit();
              }
          });
        }
    });

}

function setToFullConfig(){
    var show_dop_obj = document.getElementById('show_dop')
    if (show_dop_obj != null) {show_dop_obj.value = 'true';}
    document.getElementById('FullListLink').style.display = 'none';
    document.getElementById('ShortListLink').style.display = 'block';
    document.getElementById('config').style.display = 'block';}

function setToShortConfig(){
    var show_dop_obj = document.getElementById('show_dop')
    if (show_dop_obj != null) {show_dop_obj.value = '';}
    document.getElementById('config').style.display = 'none';
    document.getElementById('FullListLink').style.display = 'block';
    document.getElementById('ShortListLink').style.display = 'none';}

function toggleFilter(active) {
	if (active == 'url_list')
		document.search.method = 'post';
	else
		document.search.method = 'get';
	['url_list', 'link_text', 'statuses'].each(function(id) {
		$(id).hide();
		$(id + '_form').hide();
	});
	['filter', 'list_filter', 'status'].each(function(id) {
		$$('#'+id)[0].disable(); // костыль!
	});
	$(active).show();
	$(active + '_form').show();

	switch(active){
		case 'url_list':
			$('list_filter').enable();
		break;
		case 'link_text':
			$('filter').enable();
		break;
		case 'statuses':
			$('status').enable();
		break;
	};
	return false;
}

function toggleDisabled (id)
{
    $(id).disabled=!$(id).disabled;
}

function ihelp_hide(controller,action) {
  $('ihelp').remove();
  hides = eval(getCookie('ihelp'));
  if (!hides) { hides=[] };
  new_hide = [controller,action]
  hides.push(new_hide);
  setCookie('ihelp',hides.toSource(),10000,'/');
}

function ihelp_message_sent_toggle()
{
  $('feed_send_form').toggle();
  $('feed_send_link').toggle();
  $('ihelp_message_sent').toggle();
  $('content').value='';
}

