window.onresize= global_search;

function global_search() {

 if (document.getElementById('global_search'))
   { var sp=document.getElementById('global_search');
    sp.style.left=(document.getElementById('header').offsetWidth-sp.offsetWidth-50);
    }
}

function GetIdCheckRecords(name_records){
    var List=document.getElementsByName(name_records);
    var k='';
    for (var i = 0; i < List.length; i++) {
         if (List[i].checked==true){
            if (k!=''){k=k+",";}
            k=k+"'"+List[i].id+"'";}
    }
    if (k==''){alert('Не выбраны данные для обработки'); return false;}
  return k;
}

function check_all(name_records,val){
   var List=document.getElementsByName(name_records);
    for (var i = 0; i < List.length; i++) {
        List[i].checked=val;
    }
}





function wait(text)
            {//debugger;
             if (!text){text="Подождите, идет обработка данных";}
               var main=this.document.body;
               var div_1=document.createElement('div');
			   div_1.id='wait_fon';
               div_1.className='fon';
			   div_1.style.height=main.scrollHeight;
			   main.appendChild(div_1);

			   var div=document.createElement('div');
               div.id='wait_div';
               div.className='centered';
               div.innerHTML="<p style='padding:5px;color:white;'><b>"+text+"</b></p>";
               div_1.appendChild(div);
               var img_p=parseInt(div.offsetWidth)/2-16;

               div.style.marginLeft=-img_p;
               var img=document.createElement('img');
               img.id='wait_img';
               img.src='/images/loading_002.gif';
               img.style.border=0;
               //img.align='left';
               img.hspace=img_p;
               img.vspace=5;
               div.appendChild(img);
               div_1.appendChild(div);
               //img.offsetTop=300;

          }
 function stop_wait(){
  var del_div = getElementsByClass('fon');       //                 document.getElementsByName('waitfon');
   for (var i=0; i<del_div.length; i++){
     del_div[i].parentNode.removeChild(del_div[i]);
    }

 }
////////////////////




function downloadpic(id, by, puty, ection)
{  //debugger;
 var p=document.getElementById('picture_'+id);
    doLoad({ picture: p, id: id, b: by, path: puty },'/inc/upload_pic.php',ection);
}

function htmlsimvol(stroka,new_str,old_str)
{
    while (stroka.indexOf(old_str)>=0) {stroka=stroka.replace(old_str,new_str);}
    return stroka;
}

function add_properties (temp_id_mas,el,id)
{
          if (el==2){tv[temp_id_mas].cena=document.getElementById('cena_'+id).value;}
          if (el==3){tv[temp_id_mas].description=document.getElementById('description_'+id).value;}
          if (el==4){
                 if (document.getElementById('TOP_'+id).checked==true)  {tv[temp_id_mas].top='Y';}
                 else{tv[temp_id_mas].top='N';}
          }
}
function nal_mas_el(id, el)// проверяет наличия в массиве значения элемента текущей записи
{
    var nal=0;
    var e =  document.getElementById(id);
    var temp_id_mas=tv.length;
    for (var ki=0;ki<=tv.length; ki++)
      {
          if (tv[ki])
           {
                if (tv[ki].id==id)
                {
                    nal=1;
                    if (el=='1'){ delete tv[ki];  e.checked=false;}    // если сняли галочку на чек-боксе
                    else { add_properties (ki,el,id); }
                    break;
                 }
            }
      }
     if (nal==0){
               tv[temp_id_mas]= {'id':id};
               add_properties (temp_id_mas,el,id);
               e.checked=true;
            }
}

function edite(id,chek_box) /// id записи и признак поля
{
                    var regexp=/[^0-9\.]/;
                    var tex_t;
            if (chek_box==1){nal_mas_el(id, chek_box);}

            if (chek_box==2){ //Если редактировали поле цана проверяем их смысл(числа ли они)
                   tex_t =  document.getElementById('cena_'+id);

                    if (regexp.test(tex_t.value)){
                        kontrol_cana[kontrol_cana.length]=(id);
                        alert ('В данном поле могут быть только целые или десятичные числа разделенные точкой!');
                        tex_t.style.borderColor='#FF0000';
                        err_or=1;
                        document.getElementById ('check_'+id).checked=false;

                    }
                    else {  //tex_t.style.borderColor='#FF0000';
                            for (var inw=0; inw<kontrol_cana.length; inw++) {
                                  if (kontrol_cana[inw]==id) {
                                       kontrol_cana.splice(inw,1);
                                    }
                            }
                           nal_mas_el(id, chek_box);
                           tex_t.style.borderColor='#C0C0C0';
                           err_or=0;
                            document.getElementById ('check_'+id).checked=true;
                      }
           }

         if (chek_box==3){ //Если редактировали поле описание

                            tex_t =  document.getElementById('description_'+id);
                            if (tex_t.textLength<10){
                                kontrol_description[kontrol_description.length]=(id);
                                alert('Описание должно быть минимум 10 символов!');
                                tex_t.style.borderColor='#FF0000';
                                err_or=1;
                                document.getElementById ('check_'+id).checked=false;
                             }
                             else {
                                    for (var inw=0; inw<kontrol_description.length; inw++) {
                                         if (kontrol_description[inw]==id) {

                                            kontrol_description.splice(inw,1);
                                         }
                                      }
                                    err_or=0;
                                    nal_mas_el(id, chek_box);
                                    tex_t.style.borderColor='#C0C0C0';
                                    document.getElementById ('check_'+id).checked=true;
                              }
          }

         if (chek_box==4){ //Если редактировали поле TOP
                           nal_mas_el(id, chek_box);
                           document.getElementById ('check_'+id).checked=true;
         }
}
  //////////////////////////////////////

function mas_to_str(table)
{
     if (kontrol_cana.length!=0 || kontrol_description!=0){alert('Некоторые поля заполнены не правильно! \nОни выделены красным цветом!');  }
     else{
        var str='{ac:"sv",q: table,g: [';
        for (var k=0; k<tv.length; k++){
             if (tv[k]!=undefined){
                  str+='{"id":"'+tv[k].id+'"';
                  if (tv[k].description)
                  { var re = /\r\n|\n/gi;
                    tv[k].description=tv[k].description.replace(re, "<br>");
                     tv[k].description=htmlsimvol(tv[k].description,'&quot;','"');
                     str+=', "description":"'+tv[k].description+'"';
                   }
                    if (tv[k].cena){ str+=', "cena":"'+tv[k].cena+'"';}
                    if (tv[k].top){ str+=', "top":"'+tv[k].top+'"';}
                     str+='},';
             }
        }
        str+=']}';
        var myObject = eval('(' + str + ')');
      if (kontrol_cana==0 && kontrol_description==0){ doLoad(myObject,'/ajax_response/save_strings.php');}
     }
}

function del_el_s(tb) {
    if (tv.length>0)
      {var temp=new Array;
        for (var k=0; k<tv.length; k++){temp[k]=tv[k].id; }
        doLoad({ac:"dl",q:tb,g:temp},'/ajax_response/save_strings.php');
      }
}

    //////
function doLoad(value,url,ection,ection_k) {
     var req = new JsHttpRequest();
     req.onreadystatechange = function() {
       if (req.readyState == 4) {
             if (ection){eval(ection);}
              eval(req.responseText);
           if (ection_k)  {eval(ection_k);}
       }
    }
    req.open(null, url, true);
    req.send(value);
   // wait('Сохранение данных');
}

function doload_2(object,element,path,ection_start,ection_end)
{   //debugger;
   if (ection_start){eval(ection_start);}
         var req = new JsHttpRequest();
         req.onreadystatechange = function() {
            if (req.readyState == 4) {
                 if (document.getElementById(element) && req.responseText) {document.getElementById(element).innerHTML = req.responseText;}
                 if (req.responseJS){eval(req.responseJS);}
                 if (ection_end){eval(ection_end);}
            }
        }
        req.open(null, path, true);    //  debugger   ;
        req.send(object);
    }



  function sender(myJSONObject, file_back){
        wait("Подождите, идет обработка данных");
             var req = new JsHttpRequest();
             req.onreadystatechange = function() {
                if (req.readyState == 4) {
                 //alert (req.responseText);    // document.getElementById('debug').innerHTML = req.responseText;
                 eval(req.responseText);
                 var del_div=document.getElementById('wait_div');
                 stop_wait();
                }
            }
            req.open(null, file_back, true);
            req.send(myJSONObject);

          }

 function check_kol_simvol(max, id_txt, id_counter){
 var txt=document.getElementById(id_txt);
 var counter=document.getElementById(id_counter);
 var kol=txt.value.length;
 counter.value=max-kol;
 counter.value=max-kol-1;
 if (counter.value<0) counter.value=0;
 if (kol>=(max-1))
 {counter.value>=max;
 txt.value=txt.value.substring(0,max-1);
 }
}

 function show_windows(url,name,windowWidth,windowHeight)
    {
        myleft=(screen.width)?(screen.width-windowWidth)/2:100;
        mytop=(screen.height)?(screen.height-windowHeight)/2:100;
        properties = "width="+windowWidth+",height="+windowHeight+",scrollbars=yes, top="+mytop+",left="+myleft;
        window.open(url,name,properties);
    }

 function view_next_pic(path, mas, puty,pic,text_pic,flag)
 {
re=/_([\w]+)\.jpeg$/gi;
var text='';
var name=re.exec(path);
var kol=(mas.length-1);
for (var k=0;k<=mas.length;k++)
{
    if(mas[k][0]==name[1]) {

            if (k!=kol){
               if (flag=='next') k=k+1;}
            else {
                if(flag=='next')k=0;
                } name=mas[k][0];


        //if(k==kol) {name=mas[0][0];}
        //else {name=mas[k+1][0];}

        document.getElementById(pic).src=puty+name+'.jpeg';
        text=mas[k][1];
        if(mas[k][2]!=''){text+='<br><b>Автор:</b> '+mas[k][2];}
        document.getElementById(text_pic).innerHTML=text;

      break;
    }
}
var URL=path.replace(re, '');

 }

function formating_url_pic(URL) {
re=/(_s)\./;
URL=URL.replace(re, ".");
re=/(\/s\/)/;
URL=URL.replace(re, "/");
return  URL;
}
   ////  РАЗОБРАТЬСЯ - дубликат
      function send_masage(url,name,windowWidth,windowHeight,ConTent)
    {
        myleft=(screen.width)?(screen.width-windowWidth)/2:100;
        mytop=(screen.height)?(screen.height-windowHeight)/2:100;
        properties = "width="+windowWidth+",height="+windowHeight+",scrollbars=yes, top="+mytop+",left="+myleft;
        var new_win=window.open(url,name,properties);
        //pause(1000);
        //new_win.close;

    }

        function print(url,name,windowWidth,windowHeight,ConTent)
    {
        myleft=(screen.width)?(screen.width-windowWidth)/2:100;
        mytop=(screen.height)?(screen.height-windowHeight)/2:100;
        properties = "width="+windowWidth+",height="+windowHeight+",scrollbars=yes, top="+mytop+",left="+myleft;
        var new_win=window.open('',name,properties);
        new_win.document.write('<font color="C0C0C0">Melok.com.ua</b> - Комплекс товаров и услуг</font><br><br><br>'+ConTent);
        new_win.print();
    }

    function pause(millisecondi)
{
    var now = new Date();
    var exitTime = now.getTime() + millisecondi;

    while(true)
    {
        now = new Date();
        if(now.getTime() > exitTime) return;
    }
}

	function pop_up(path,w_width, w_height) {
    tinyMCE.openWindow({
        file : path,
        title : "File Browser",
        width : w_width,
        height : w_height,
        close_previous : "no"
    }, {
        window : win,
        input : field_name,
        resizable : "yes"
       // inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
        //editor_id : tinyMCE.selectedInstance.editorId
    });
    return false;
  }
  function send_selected(from, path_to_send, names, pr, ection) {
   var y=0;
   var object='{from:from, a_id:[';
   var elements = document.getElementsByName(names);
   for (var i=0; i<elements.length; i++){
       if (elements[i].checked==true){
            object=object+"'"+elements[i].attributes['link'].nodeValue+"',";  y=y+1;
       }
    }
    if (y>0){
            object =object+'], pr:pr}';
            object = eval('(' + object + ')');
          doLoad(object,path_to_send,ection);
    } else alert ("Вы ничего не выбрали !");
  }

function selectionText(inputObject)
{
 if (inputObject.selectionStart) {inputObject.setSelectionRange(0,inputObject.value.length);}
 if (inputObject.createTextRange) { var r = inputObject.createTextRange(); r.select(); }
}


                            //newNameInput
          function js_show_blok(s,h) {

          //object
			ss = document.getElementById(s).style;
			hh = document.getElementById(h).style;

			if (ss.display == 'block' ) {
				ss.display = 'none';
				hh.display = 'block';
			} else if ( ss.display == 'none' ) {
				ss.display = 'block';
				hh.display = 'none';
			}
			return false;
		}

        function show_blok(s,h) {
                var ss,hh;
                  if (typeof(s)=='object'){
                      for(var i=0; i<s.length;i++){
                        ss = document.getElementById(s[i]);
                            if (ss){ss.style.display='block';}
                       }
                  }
                   else{ss = document.getElementById(s); if (ss){ss.style.display='block';}}
                    if (typeof(h)=='object'){
                      for(var i=0; i<h.length;i++){
                        hh = document.getElementById(h[i]);
                            if (hh){hh.style.display='none';}
                       }
                  }
                   else{hh = document.getElementById(h);
                   if (hh){
                   hh.style.display='none';}}

		}


        function range_content(s,p,top,show, now, bl,control_path,f_start,f_end,div_elem)
        {      //debugger;
                var MyObj={act:'range'};
                MyObj['s']=document.getElementById(s).value;
                MyObj['p']=document.getElementById(p).value;

                var top=document.getElementById(top);
                if (top.checked==true) {MyObj['top']='Y';}else {MyObj['top']='N';}


                var bl=document.getElementById(bl);
                if (bl) {if (bl.checked==true) {MyObj['black_list']='Y';}else {MyObj['black_list']='N';}}

                var show=document.getElementById(show);
                if (show.checked==true) {MyObj['show']='Y';}else {MyObj['show']='N';}

                var now=document.getElementById(now);
                if (now.checked==true) {MyObj['new']='Y';}else {MyObj['new']='N';}
                doload_2(MyObj,div_elem,control_path,f_start,f_end);

        }
  function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;

	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}



function captcha_pic_relpad(element)
{
    var xmas = new Date();
    if (!element){var element=document.getElementById('captcha_pic');}
    element.src='/inc/secpic.php?r='+xmas.getSeconds();

}

function BodyOnLoad(){
    var fan=$("a.jqv");
    if (fan){
         fan.fancybox({
        "hideOnContentClick": true,
        "frameWidth":400,
        "frameHeight":500
    });
 }
      var fan=$("a.mailsend");
        if (fan){
             fan.fancybox({
            "hideOnContentClick": true,
            "frameWidth":450,
            "frameHeight":550
        });
     }

    var sp=$("#global_search");
    //if (sp){sp.css({display:"block",left:screen.width-335});}


    (function()
    {
    var f = document.getElementById('login_form');

    if (f && f.login) { var login = f.login;

    var b = function() { if (login.value == '') { login.style.background = '#FFFFFF url(/images/login.gif) left no-repeat'; } };
    var f = function() { login.style.background = '#ffffff'; }; login.onfocus = f; login.onblur = b; }
    }
    )();


     (function()
    {
    var f = document.getElementById('login_form');
    if (f && f.password) { var password = f.password;
    var r = function() { if (password.value == '') { password.style.background = '#FFFFFF url(/images/pas.gif) left no-repeat'; } };
    var y = function() { password.style.background = '#ffffff'; }; password.onfocus = y; password.onblur = r; }
    }
    )();
}

function check_email(email){

 var Reg_str = new RegExp("^[0-9a-z_-]([.]?[0-9a-z_-])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,4}$","ig");
 if (Reg_str.test(email)) return true; else {return false;}
}

function mail_check(nod){
        if (!check_email(nod.value)) {nod.className='field_error'; return false;}
        else  {nod.className='comment_text_field'; return true;}
}


function tel_check(nod){ nod.value=trim(nod.value);
 var Reg_str = new RegExp("[^0-9) (-]","ig");
 if (Reg_str.test(nod.value)){nod.className='field_error'; return false;}
 else {nod.className='comment_text_field'; return true;}
}


function addBookmark(url, title)
{
 if (!url) url = location.href;
 if (!title) title = document.title;

 //Gecko
 if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
 //IE4+
 else if (typeof window.external == "object") window.external.AddFavorite(url, title);
 //Opera7+
 else if (window.opera && document.createElement)
 {
   var a = document.createElement('A');
   if (!a) return false; //IF Opera 6
   a.setAttribute('rel','sidebar');
   a.setAttribute('href',url);
   a.setAttribute('title',title);
   a.click();
 }
 else return false;

 return true;
}

function center(text)
{  //if (!text){text="Подождите, идет обработка данных";}
   var main=this.document.body;
   var div_1=document.createElement('div');
   div_1.id='wait_fon';
   div_1.className='fon';
   div_1.style.height=main.scrollHeight;
   main.appendChild(div_1);

   var div=document.createElement('div');
   div.id='wait_div';
   div.className='cd';   //debugger;
   div.innerHTML=text;
   div_1.appendChild(div);
   var img_p=parseInt(div.offsetWidth)/2-16;
   div.style.marginLeft=-img_p;

   var img=document.createElement('img');
}

 function get_info(x,el){ 	doload_2({'act':x},el,'/ajax_response/get_info.php5','wait()','stop_wait()'); }
function buy(act,tb,id,frm){
	var shop_div=document.getElementById ('shop');
	if (shop_div){shop_div.style.display='block';}
doload_2({'act':act,'tb':tb,'id':id,'frm':frm},'buy_div','/ajax_response/buy.php5','wait();','stop_wait();');
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
  /*
  if (!document.all) {
     document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
  }
  */