// Получаем информацию о браузере
function getBrowserInfo() { 
 var t,v = undefined; 
 if (window.opera) t = 'Opera'; 
 else if (document.all) { 
  t = 'IE'; 
  var nv = navigator.appVersion; 
  var s = nv.indexOf('MSIE')+5; 
  v = nv.substring(s,s+1); 
 }  
 else if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) // проверка на Google Chrome
 {
   t = 'chrome';   
 } 
 else if(navigator.userAgent.toLowerCase().indexOf('safari') > -1) // проверка на Apple Safari
 {
   t = 'safari';
 }
 else if(navigator.appName)
 { 
   t = 'Netscape';   
 } 
 
 return {type:t,version:v}; 
} // end function getBrowserInfo() 
  
function bookmark(a)
{ 
 var url = window.document.location; 
 var title = window.document.title; 
 var b = getBrowserInfo();
 if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title); 
 else if (b.type == 'Opera') { 
  a.href = url; 
  a.rel = "sidebar"; 
  a.title = url+','+title; 
  return true; 
 } 
 else if (b.type == "Netscape") window.sidebar.addPanel(title, url, ""); 
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки."); 
 return false; 
}   

function SetHome(o) {
  o.style.behavior='url(#default#homepage)';
  o.setHomePage('http://freemarket.ua');  
  return false;
}

function format_number(pnumber,decimals){
     if (isNaN(pnumber)) { return 0};
     if (pnumber=='') { return 0};

     var snum = new String(pnumber);
     var sec = snum.split('.');
     var whole = parseFloat(sec[0]);
     var result = '';

     if(sec.length > 1){
          var dec = new String(sec[1]);
          dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
          dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
          var dot = dec.indexOf('.');
          if(dot == -1){
               dec += '.';
               dot = dec.indexOf('.');
          }
          while(dec.length <= dot + decimals) { dec += '0'; }
          result = dec;
     } else{
          var dot;
          var dec = new String(whole);
          dec += '.';
          dot = dec.indexOf('.');
          while(dec.length <= dot + decimals) { dec += '0'; }
          result = dec;
     }
     return result;
}

function SMessSubmit(){
  err = '';
  herss = false;

  if(document.forms.smf.amount.value < document.forms.smf.min_price.value){
    err += '\n   - Цена объявления не может быть меньше минимальной в выбраном разделе.';
    herss = true;
  }


  if((document.forms.smf.cat_end.value == 0) && (document.forms.smf.smtype.value == 8)){
    err += '\n   - Топ-объявление может быть размещено только в конечной рубрике.';
    herss = true;
  }

  if(document.forms.smf.title.value == ''){
    err += '\n   - Заголовок объявления не может быть пустым.';
    herss = true;
  }

  if(document.forms.smf.message.value == ''){
    err += '\n   - Текст объявления не может быть пустым.';
    herss = true;
  }

  if(document.forms.smf.title_url.value == ''){
    err += '\n   - Текст ссылки не может быть пустым.';
    herss = true;
  }

  if(!document.forms.smf.url.value.match(/^http:\/\/.*$/)){
    err += '\n   - Ошибочный или пустой URL ссылки.';
    herss = true;
  }


  if(document.forms.smf.del.checked){
     if(confirm("Вы действительно хотите удалить это объявление ?"))
       herss = false;
     else
       return false;
  }

  if(herss){
    alert('Во время заполнения формы были допущены следующие ошибки:\n' + err);
    return false;
  }else{
    document.forms.smf.bsubmit.disabled = true;
  }

};


function RenderSMess(){
   if(o = getEl('renderw')){
    t = document.forms.smf.smtype.value;
    if( t == 8 || t == 7 ){
       url = document.forms.smf.url.value;
       res = '<div class="smessTop"><a class="link" href="'+url+'" target=_blank>' + document.forms.smf.title.value + '</a><br>' +
             '<a class="desc" href="" target=_blank>' + document.forms.smf.message.value + '</a><br>';

       if(document.forms.smf.phone.value.length > 0 || document.forms.smf.adres.value.length > 0 ){
         res += '<a class="phone" href="'+url+'" target=_blank><img src="'+ GLOBAL_DIR +'/images/phone.gif" border=0 width=12 height=12 align="absmiddle"></a>' +
                '<a class="phone" href="'+url+'" target=_blank>Адрес и телефон</a>';
         if(document.forms.smf.url.value.length > 0){
           res += ' <span class="silver">|</span> ';
         }
       }

       res += '<a class="url" href="'+url+'" target=_blank>' + document.forms.smf.title_url.value + '</a></div>';
       o.innerHTML = res ;
    }
   }
};

function SetSMtype(){
  t = document.forms.smf.smtype.value;
  switch(t){
    case '6':
      getEl('sm_comment').innerHTML = 'Отображаеться в виде иконки в дереве каталога напротив закреплённой рубрики, а так же с краткой подписью справа от заголовка выбранной рубрики.';
    break;
    case '7':
      getEl('sm_comment').innerHTML = 'Отображается в правой колонке указанной рубрики на всех её подразделах (описания, объявления, продавцы, авторы...). Если выбрана неконечная рубрика, то объявление так же будет показываться во всех её дочерних рубриках.';
    break;
    case '8':
      getEl('sm_comment').innerHTML = 'Отображается всегда над списком бесплатных объявлений на всех страницах с объявлениями в выбранной рубрике <span class="red">(обязательно необходимо выбрать конечные рубрики)</span>';
    break;
  }
  RenderSMess();
}

function change_price(t){
  switch(t){
    case 'inc':
       document.forms.smf.amount.value = Math.round(parseFloat(document.forms.smf.amount.value)*100+1)/100;
    break;
    case 'dec':
       if(document.forms.smf.amount.value > document.forms.smf.min_price.value){
         document.forms.smf.amount.value = Math.round(parseFloat(document.forms.smf.amount.value)*100-1)/100;
       }

   break;
  }
  getEl('price_show').innerHTML = format_number(document.forms.smf.amount.value, 2);

}





//////////////////////////////////////////////////////////////////////////////////////////

function Display(a){
   function SetCookie (name,value,expires,path,domain,secure) {
     document.cookie = name + "=" + escape (value) +
       ((expires) ? "; expires=" + expires.toGMTString() : "") +
       ((path) ? "; path=" + path : "") +
       ((domain) ? "; domain=" + domain : "") +
       ((secure) ? "; secure" : "");
   }

   try{document.getElementById("Window").style.display=a;} catch(e){}
   try{document.getElementById("WindowTable").style.display=a;} catch(e){}
   try{document.getElementById("Window1").style.display=a;} catch(e){}
   try{document.getElementById("WindowTable1").style.display=a;} catch(e){}

         	if (a == 'none'){
                      var today = new Date();
                      var expire = new Date();

                      expire.setTime(today.getTime() + 3600000*24*1);

                      SetCookie ("addvert_no","1",expire,"/");

                }
}
function Display_load(){
			Display('');
		 	setTimeout("Display('none')",60000);

		 }

   function Mail_to_user(uid, goodsid){
  	window.open(GLOBAL_DIR+'/mail-to-user/'+uid+'/'+goodsid+'/','', 'menubar=no, scrollbars=no, location=no, toolbar=no, status=no, resizable=no, width=370, height=470, left=0, top=0');
   }

   function Complain(id){
    	window.open(GLOBAL_DIR+'/complain/'+id,'', 'menubar=no, scrollbars=no, location=no, toolbar=no, status=no, resizable=no, width=600, height=460, left=0, top=0');
   }


   function browseIt()
   {
   	this.ver = navigator.appVersion.toLowerCase();
   	this.agent = navigator.userAgent.toLowerCase();
   	this.dom = document.getElementById ? 1 : 0;
   	this.opera = (navigator.userAgent.indexOf("opera")>-1 && document.getElementById) ? 1 : 0;
   	this.opera7 = (this.opera && parseInt(navigator.appVersion) >= 7);
   	this.ie = (this.ver.indexOf("msie") > -1 && this.dom && !this.opera) ? 1 : 0;
   	this.macOS = this.agent.indexOf("mac") > -1;
   	this.mac = (this.macOS && parseInt(this.ver) >= 7) ? 1 : 0;
   	this.moz = (this.agent.indexOf("gecko")>-1)
   	this.ns6 = (this.dom && this.agent.indexOf("netscape")>-1 && parseInt(this.ver) >= 5) ? 1 : 0;
   	this.b = (this.ie || this.ns6 || this.opera7 || this.mac || this.moz || this.dom);
   	return this;
   }

   var px = window.opera ? "" : "px";
   var b = new browseIt();


   function makeObj(obj)
   {
   	this.elem = document.getElementById(obj);
      	this.css = this.elem ? this.elem.style : null;
   	return this;
   }


   function showFloatForm(act, formAct)
   {
   	var oTmp = new makeObj("mainFloatForm");
   	var oTmp1 = new makeObj("floatForm");
   	if (!oTmp.elem || !oTmp1.elem)
   		return true;
   	var oTmpW = 250;

   	//var sW = (!b.ie) ? self.innerWidth : self.document.body.offsetWidth;

        if (window.innerWidth) {
           win_size_X = window.innerWidth;
        } else if (document.documentElement && document.documentElement.clientWidth) {
           win_size_X = document.documentElement.clientWidth;
        } else if (document.body && document.body.clientWidth) {
           win_size_X = document.body.clientWidth;
        }

        sW = win_size_X;

   	oTmp.css.width = oTmp1.css.width = oTmpW + px;
   	//alert(sW);
        oTmp.css.left =(sW - oTmpW)/2 + px;
   	oTmp.css.top = document.body.scrollTop + parseInt(sW * 0.13);
   	if (act) {
   		oTmp.css.display = 'none';
   		//toggleDisplay('SELECT', 'visible');
   		//toggleDisplay('OBJECT', 'visible');
   		//toggleDisplay('EMBED', 'visible');
   	} else {
   		if(b.ns6 && !b.opera) return true;
   		oTmp.css.display = 'block';
   		//toggleDisplay('SELECT', 'hidden');
   		//toggleDisplay('OBJECT', 'hidden');
   		//toggleDisplay('EMBED', 'hidden');
   			//document.forms.login.url.value = formAct ? formAct : '';
   		setTimeout("document.forms.login.login.focus();", 100);
   	}
   
   	return false;
   }


   function my_hyst_clear(){
	var today = new Date();
	var expire = new Date();
        document.getElementById("MyHist").innerHTML = 'идёт очистка...';
	span = document.getElementById("outerScript");
	span.innerHTML = 'идёт очистка...<s'+'cript></'+'script>';
	var s = span.getElementsByTagName("script")[0];
	s.language = "JavaScript";

	if (s.setAttribute)
           s.setAttribute('src', '/modules/history/db_history_clear.php?upd='+today.getTime());
        else
           s.src = '/modules/history/db_history_clear.php?upd='+today.getTime();

        SetCookie ("hist_m","none",expire,"/");
        SetCookie ("hist_g","none",expire,"/");
        SetCookie ("hist_j","none",expire,"/");
        SetCookie ("hist_k","none",expire,"/");
   }



   function SetCookie (name,value,expires,path,domain,secure) {
        document.cookie = name + "=" + escape (value) +
          ((expires) ? "; expires=" + expires.toGMTString() : "") +
          ((path) ? "; path=" + path : "") +
          ((domain) ? "; domain=" + domain : "") +
          ((secure) ? "; secure" : "");
      }


   function my_hist_act(som,obj) {

      var today = new Date();
      var expire = new Date();
      expire.setTime(today.getTime() + 3600000*24*30);

      if (document.getElementById) {
       var temp = document.getElementById(som).style;
       if (temp.display == "block") {
          temp.display = "none";
          obj.firstChild.src = GLOBAL_DIR+"/images/css_images/menu_close.gif";
          SetCookie (som,"none",expire,"/");

        }else {
              temp.display = "block";
              obj.firstChild.src = GLOBAL_DIR+"/images/css_images/menu_open.gif";
              SetCookie (som,"block",expire,"/");

          }
       return false;
       } else {
       return true;
      }
   }

function check(checked){
  var ELE_NAME_ARRAY = new Array('mess_array[]');
  setCheckedFlag(document.Data,ELE_NAME_ARRAY,checked);
  document.Data.all_check.checked = checked;
  document.Data.all_check2.checked = checked;

}

function check1(checked){
  var ELE_NAME_ARRAY = new Array('mess_array[]');
  setCheckedFlag(document.Data1,ELE_NAME_ARRAY,checked);
}


function setCheckedFlag(formObj,eleNameArr,checkedFlag){
  for(var i=0;i<formObj.elements.length;i++){
     var ele = formObj.elements[i];
     for(var j=0;j<eleNameArr.length;j++){
       if(ele.name == eleNameArr[j]){
          ele.checked = checkedFlag;
          break;
       }
     }
  }
}
function add_checked_to_compare(obg_form){
  var ELE_NAME_ARRAY = new Array('mess_array[]');
  var str = '';
  if(!obg_form) formObj = document.Data; else formObj = obg_form;
  for(var i=0;i<formObj.elements.length;i++){
     var ele = formObj.elements[i];
     for(var j=0;j<ELE_NAME_ARRAY.length;j++){
       if(ele.name == ELE_NAME_ARRAY[j]){
          if (ele.checked==true) str = str + ele.value + '/';
          break;
       }
     }
  }
  if (str!='')
    location.href='/compare/'+str;
}

function add_checked_to_compare_ajax(obg_form){
  var ELE_NAME_ARRAY = new Array('mess_array[]');
  var str = new Array();
  k=1;
  if(!obg_form) formObj = document.Data; else formObj = obg_form;
  for(var i=0;i<formObj.elements.length;i++){
     var ele = formObj.elements[i];
     for(var j=0; j<ELE_NAME_ARRAY.length; j++){
       if(ele.name == ELE_NAME_ARRAY[j]){
          if (ele.checked == true && ele.value != "") str[k++] =  ele.value;
          break;
       }
     }
  }

    return str;
}

function sr () {
	re = /^\s*$/;

	if (re.test(document.Search.key.value)){
		alert("Введите ключевоке слово поиска!");
		document.Search.key.focus();
		return;
	}

	document.Search.submit();
}

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   interger  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not

 Example: <tr onmouseover="setPointer(this, 7, 'over', '#CCCCCC', '#CCFFCC', '#FFCC99');" onmouseout="setPointer(this, 7, 'out', '#CCCCCC', '#CCFFCC', '#FFCC99');" onmousedown="setPointer(this, 7, 'click', '#CCCCCC', '#CCFFCC', '#FFCC99');">
 */


function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor != null) {
      if (currentColor.indexOf("rgb"))
      if (currentColor.indexOf("rgb") >= 0 )
      {
          var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                       currentColor.indexOf(')'));
          var rgbValues = rgbStr.split(",");
          currentColor = "#";
          var hexChars = "0123456789ABCDEF";
          for (var i = 0; i < 3; i++)
          {
              var v = rgbValues[i].valueOf();
              currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
          }
      }
  
      // 4. Defines the new color
      // 4.1 Current color is the default one
      if (currentColor == ''
          || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
          if (theAction == 'over' && thePointerColor != '') {
              newColor              = thePointerColor;
          }
      }
      else
      if (currentColor.toLowerCase() == thePointerColor.toLowerCase() ) {
          if (theAction == 'out') {
              newColor              = theDefaultColor;
          }
      }
      // 4.1.3 Current color is the marker one
      else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        /*  if (theAction == 'click') {
              newColor              = (thePointerColor != '')
                                    ? thePointerColor
                                    : theDefaultColor;
          }  */
      } // end 4
    }
    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

function ajax(go_,for_,to_) {
  var today = new Date();
  jQuery.getScript(GLOBAL_DIR+'/ajax/'+go_+'/'+for_+'/'+to_+'&g='+today.getTime());
}

var my_eval = function(code) {
    if (window.execScript) return window.execScript(code, 'javascript');
    else return window.eval(code);
}

function tracTrans(id){  
  var r = Math.round((Math.random() * (10000000 - 1)));
  var url = GLOBAL_DIR + '/trackTrans.php?id=' + id + '&r=' + r;
  makeRequest(url);
}

function makeRequest(url) {
  var http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
  } 
  else if (window.ActiveXObject) { // IE
    try {
    http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {}
    }
  }
  if (!http_request) {
    alert('Не вышло  Невозможно создать экземпляр класса XMLHTTP ');
    return false;
  }
  http_request.onreadystatechange = function() { alertContents(http_request); };
  http_request.open('GET', url, true);
  http_request.send(null);
}

function alertContents(http_request) {
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {  
      dvi = document.getElementById('tracTrans');
      dvi.innerHTML = '';
      try {
        my_eval(http_request.responseText);
      }
      catch (e) {}
    } 
    else {
    alert('С запросом возникла проблема.');
    }
  }
}

function InsertHTML(el, html) {
    el.innerHTML=html;
    scripts = el.getElementsByTagName("script");
    head = document.getElementsByTagName('head')[0];
    for(i=0 ; i<scripts.length ; i++) {
        eval (scripts[i].innerHTML);
        var script = document.createElement('script');
        script.src = scripts[i].src;
        head.appendChild(script);
    }
}

function conv_trans() {
  var today = new Date();        
  jQuery.get(GLOBAL_DIR+"/conv.html?g="+today.getTime(), onAjaxSuccess);
 
  function onAjaxSuccess(data)  {            
    InsertHTML(document.getElementById("convTrans"), data);
    //console.log(data);            
  }          
}
