// JavaScript Document
var rate=0;
var from_img=0
var keys_checking=0
var height=0
var tmp_div=document.createElement('div')
var sesid="";
var export_data="";

function get_server_domen(){
  var sp=location.host.split(".");
  return "."+sp[sp.length-2]+"."+sp[sp.length-1];
}

function load_images_stats(div){
      $.ajax({ 
        type: "POST", 
        url: "/load_content.php", 
        data: "load="+div, 
        success: function(msg){
          d=byid(div)
          d.innerHTML=msg
        }    
      }) 

}  

function get_sesid(){
      $.ajax({ 
        type: "GET", 
        url: "/sesid.php", 
        data: "", 
        success: function(msg){
          sesid=msg
          export_data=msg
//          alert(sesid)
        }    
      }) 
}
/*function is_cookie_enabled(){
//  if (document.cookie=="" || !navigator.cookieEnabled) return false;
  SetCookie('varCook','True','','/','','');
  if (GetCookie() == "True")
    return true;
   else 
    return false;
  
 
}*/
function load_footer(div){
      $.ajax({ 
        type: "POST", 
        url: "/load_content.php", 
        data: "load="+div, 
        success: function(msg){
          d=byid(div)
          d.innerHTML=msg
          var scripts = d.getElementsByTagName("script");
          for (var i = 0; i<scripts.length; i++)
            //alert(scripts[i].innerHTML)
              eval(scripts[i].innerHTML);
        }    
      }) 

}  

function showWhiteDiv(){
  b=byid('white')
  b.style.left=0
  b.style.top=0
  
//  if (is_ie())
  if (!height) height=document.body.scrollHeight
    b.style.height=height
  b.style.display="block"
  
  
}

function show_div(div){
  d=document.getElementById(div)
  s=d.style
  maxwidth=document.body.clientWidth
  s.left=(maxwidth-d.offsetWidth)/2;
  s.top=(($(document).scrollTop()+$(window).height()/2.2)-$(d).height()/2)//$('#settings_div').offset().top;
  s.zIndex=100
  s.visibility='visible';
  showWhiteDiv()
}

function comment_check_keys(e){
  id='post_comment'
  setTimeout("check_keys('"+id+"','[^a-z^0-9^а-я^й^,^.^:^!^)^(^ ^\?^\-]')",10)
  if (e.keyCode==46 || e.keyCode==8 || e.keyCode>=37 && e.keyCode<=40) return true;
  else
    if ($('#'+id).val().length>990){ 
      $('#'+id).val($('#'+id).val().substr(0,991)) 
      return false;
    }  
  
}

function closeMail(){
  $('#mail').css('visibility','hidden')
  $('#white').hide()
}
function back_check_keys(e){
  id='post_back'
  setTimeout("check_keys('"+id+"','[^a-z^0-9^а-я^й^,^_^\@^.^:^!^)^(^ ^\?^\-]')",20)
  
}


function send_mail(){
  var back,comment
  $('#post_error').hide()
  byid('post_button').disabled='disabled';
  back=byid('post_back').value;
  comment=byid('post_comment').value;
  if (comment.length<3){
    byid('post_error').innerHTML="<font color=red>В сообщении должно быть не менее 3 символов<\/font>"
    $('#post_error').show()
    byid('post_button').disabled=false;
    return
  }
  $.ajax({ 
        type: "POST", 
        url: "/send_mail.php", 
        data: "back="+back+"&id="+sesid+"&comment="+comment, 
        success: function(msg){
        if (msg!="ok")
          byid('post_error').innerHTML="<font color=red>"+msg+"<\/font>"
        else
          byid('post_error').innerHTML="<font color=green>Ваше сообщение отправлено<\/font>"
        $('#post_error').show()
        } 
      }) 
  
  
}


function show_mail(){
  d=tmp_div
  d.id="send_mail"
  str=""
  str+="<div style='margin:15px;text-align:left;'>"
  str+="<div class='mtop10'><\/div><div class=left><font class=smallandgray2>Адрес для связи с Вами (email, icq)<\/font><\/div>"
  str+="<div class=left><input maxlength='30' id=post_back style='width:100%'><\/div>";
  str+="<div class='mtop5'><\/div><div class=left><font class=smallandgray2>Текст<\/font><\/div>"
  str+="<textarea style='width:100%' id=post_comment rows=8 cols=33 />";
  str+="<div class='mtop5'><\/div>"
  str+="<center><div class=status id=post_error><\/div><\/center>"
  str+="<div class=mtop10><\/div><button id=post_button style='font-size:8pt' onclick=send_mail()>Отправить</button></div>"
  $(d).html(str)
  $(d).dialog({"title":"Отправить сообщение","modal":true,"position":"center","resizable":false,"width":550})
  $("#post_button").button()
  
//  show_div('mail')
  //return false;
}

function rate_img(img,like,href){
      if (rate) return false;
      rate=1;
      $.ajax({ 
        type: "POST", 
        url: "rate_img.php", 
        data: "img="+img+"&like="+like, 
        success: function(msg){
          if (msg=="повтор")
            href.innerHTML="Уже нажимали"
          else if (msg=="ok"){
            href.innerHTML="Спасибо!"
            
            if (like==1) byid('rate_for').innerHTML=Number(byid('rate_for').innerHTML)+1
            else 
              byid('rate_against').innerHTML=Number(byid('rate_against').innerHTML)+1
          }    
        } 
      }) 
  return false;
}


var from_img=0;

function update_img_views(img){
      $.ajax({ 
        type: "POST", 
        url: "update_img_views.php", 
        data: "img="+img, 
        success: function(msg){
          if (from_img) byid('views_label').innerHTML=msg
        } 
      }) 

}

function get_img_info(img,ty,callback){
      $.ajax({ 
        type: "POST", 
        url: "get_img_info.php", 
        data: "img="+img+"&type="+ty, 
        success: function(msg){
          eval(callback+'"'+msg+'")')
    
        } 
      }) 

}


function preload_images(){
  if (img_last>12) return;
  for (i=1;i<=img_last;i++)
    if (byid('imgpreload_'+i)!=undefined && byid('imgpreload_'+i)!=null) 
      setTimeout('preload_img("'+$('#imgpreload_'+i).val()+'")',200*i)
    
}

function preload_img(src){
  img=document.createElement('img')
  img.src=src;
  s=img.style
  s.width=10
  s.height=10
  s.position='absolute'
  s.visibility='hidden'
  s.left=0
  s.top=0
  document.body.appendChild(img);
}

  function light(e,c){
    e.style.border='1px solid '+ c
  }
  
  function lighttext(e,c){
    e.style.color=c;
  }
  
  function highlight(field) {
    field.focus();
    field.select();
  }

  function check_desc_gal(){
    if (!byid('public_check').checked) return true;
    for (i=1;i<=cur_files;i++)
      if (byid('imgcheck_'+i).checked)
      if ($('#desc_'+i).val().length<10){
        show_desc(i)
        setErrorStatus('status_desc',"Включена опция добавления в каталог, необходимо ввести описание для каждого изображения или изменить настройки")
        return false;
      }  
    return true;  
  }


  function check_desc(){
    if (!byid('public_check').checked) return true;
    for (i=1;i<=cur_files;i++)
      if ($('#desc_'+i).val().length<10){
        show_desc(i)
        setErrorStatus('status_desc',"Включена опция добавления в каталог, необходимо ввести описание для каждого изображения или изменить настройки")
        
        return false;
      }  
    return true;  
  }

function setErrorStatus(sd,msg){
    id=sd;
    sd=$('#'+id)
    sd.html("<font color=red>"+msg+"</font>")
    sd.show()
}

function del_img(img,id,status,callback){
      //a=document.getElementById(href)
      //a.style.color="red";
      $.ajax({ 
        type: "POST", 
        url: "del.php", 
        data: 'id='+id+'&obj='+img, 
        success: function(msg){
            
            if (msg=="0") {
//               a.style.color="red";
           	   status.innerHTML="Удалено!";
               //one image deleteted 
           	   if (callback=='') {
           	    gal=img.split("/")
           	    gal=gal[0]
           	    str='/gal.php?id='+id+'&gal='+gal
           	    location.href=str
           	    return
           	   }
           	   
          	   
           	   
            }
            else
            if (msg=="1") {
              status.innerHTML="Удалено!";
     	         r=document.referrer.split("/myimages/")
               if (r.length>1)
             	   setTimeout('location.href="/myimages/'+r[1]+'"',500)
               else
           	     setTimeout('location.href="/"',500)
               return
               
            }
            else {
               //a.style.color="red";
               
               status.innerHTML="<b>"+msg+"</b>"
            }
            eval(callback)          	   
        } 
      }) 
      
   
}	


function edit_img(img,id,status,callback)
{
		 if (byid('size_check').checked)
            size=byid('size_edit').value;			
      else size="no"
   		if (byid('rotate_check').checked){
   		   r=byid('rotate_select')
   		   n=r.selectedIndex
         rotate=r.options[n].value;			
       }
       else rotate="no"
 		   r=byid('public_select')
   		 n=r.selectedIndex
       public_value=r.options[n].value;			
//nothing to do?
      if (!byid('public_check').checked && size=="no" && rotate=="no") {
        byid('save_button').disabled=false
        return
      }
        
      if (byid('public_check').checked)  
        callback+=public_value+')'
      else           
        callback+=2+')'
//title edit
      status.innerHTML="Сохранение.."
      $(status).show()
      if ((size!="no") || (rotate!="no"))
      $.ajax({ 
        type: "POST", 
        url: "img_edit.php", 
        data: 'id='+id+'&obj='+img+'&size='+size+'&rotate='+rotate, 
        success: function(msg){
           	   //status.innerHTML="Сохранено!";
               eval(callback)          	   
        } 
      }) 
//public edit             
      if (byid('public_check').checked){
      $.ajax({
         type: "POST",
         url: "edit_public.php", 
         data:'id='+id+'&obj='+img+'&public='+public_value,
         success: function(msg) {
            if (size=="no" && rotate=="no"){ 
           	 //status.innerHTML="Сохранено!";
             eval(callback)          	   
            } 
         }
      });
     }
}  

function arrow_click(d,img){
  d=d.style
  update_settings_status()
  if (d.display=='block'){
    d.display='none'
    img.src='/img/downarrow.png'
  }  
  else{  
    d.display='block'
    img.src='/img/uparrow.png'
  }  
    
}


function update_settings_status(){
  str=""
  s_check=$('#size_check')
  r_check=$('#rotate_check')
  p_check=$('#public_check')
  if (s_check.attr('checked') && $('#size_edit').val()!="")
    str+="размер "+$('#size_edit').val()+"px"
  if (r_check.attr('checked')){
	   r=byid('rotate_select')
     n=r.selectedIndex
     r=r.options[n].text;
     
     if (str!="") str+=", "
     str+="поворот "+r
  }
  if (p_check.attr('checked')){
     if (str!="") str+=", "
     if (byid('public_select')!=undefined){
       r=byid('public_select')
       n=r.selectedIndex
       r=r.options[n].value;
       if (r==1) str+="добавить в каталог"
       else
         str+="удалить из каталога"  
     }
     else
      str+="добавить в каталог"
  }  
  if (str!="") str="("+str+")"
  $('#settings_status').html(str)
}


function byid(el){
  return document.getElementById(el)
}


function select_menu(id){
  el=byid(id)
  light_menu(el);
  el.onmouseout=new Function("unlight_menu('"+id+"',0)")
  
}

function emu_href(loc){
  if ($.browser.msie){
    var referLink = document.createElement('a');
    referLink.href = loc;
    document.body.appendChild(referLink);
    referLink.click();    
  }
  else
  location.href=loc
}

function unlight_menu(id,need){
  if (!need) return
  el=byid(id)
  el.style.backgroundColor=''
  el.childNodes[0].style.color='#999999'
  //el.style.borderColor='#e5e4e4'
  
}

function light_menu(el){
  //alert(el.style.borderBottom)
  el.childNodes[0].style.color='#666666'
  //el.style.backgroundColor='#5883C7'
  //el.style.borderColor='#5883C7'
  //FF6633
  //el.style.borderBottom='1px solid white'
  //el.style.backgroundColor=hcolor
//  alert(el.childNodes[0].style.color)
//  el.style.color='white'

}


function isNumberKey(id)
{
   setTimeout("check_keys('"+id.id+"','[^0-9]')",1)
   return true;
}

function check_keys(input,mask){
   orig=document.getElementById(input).value 
   s=document.getElementById(input).value
   r=new RegExp(mask, "gi")
   s=s.replace(r,"");
   s=s.replace(/ +/g," ");
   if (s!=orig)
    document.getElementById(input).value=s
//   alert(s);

}
