var sess_id = getCookie('PHPSESSID');

jQuery(document).ready(function(){
  
  //alert(  );
  
  jQuery('#jsOFF_header').hide(); //спрятать
  jhref();
});


function myragon(){
  url_arr = ['http://xn---2011-3veup2ab9baa1cdpr8e2i.xn--p1ai/','http://click.ad1.ru/?r=39443','http://click.ad1.ru/?r=39444','http://click.ad1.ru/?r=39445','http://click.ad1.ru/?r=39446','http://click.ad1.ru/?r=39447','http://click.ad1.ru/?r=39448','http://click.ad1.ru/?r=39449'];
  url_arr_lehgth = url_arr.length;
  
  randomNum = Math.floor(Math.random() * url_arr_lehgth) - 1;
  
  document.location.href = url_arr[randomNum]; // 'http://xn---2011-3veup2ab9baa1cdpr8e2i.xn--p1ai/';
  return true;
}

function jhref(){
  //alert('111');
  $('a').each(function(index, item){
	var jhref = '';
    if( jhref = $(item).attr('jhref') ){
      $(item).attr('onClick',jhref).removeAttr("href").removeAttr("jhref");
    }
  });
  blink();
  return true;
}
function blink(id){ /* моргает в углу экрана */
  if(id===undefined || id=="") id="ajax_blink";
  var ajax_blank = document.getElementById(id);
  if(ajax_blank){
	ajax_blank.style.display="block";
	setTimeout( function() {
	  ajax_blank.style.display="none";
	},200); // half seconds
	return true;
  }else{
	return false;
  }
}



function redirectPage(url){
  /*
  location="http://gs.ua/a";
  document.location.href="http://gs.ua/a";
  location.replace("http://gs.ua/a");
  window.location.reload("http://gs.ua/a");
  document.location.replace("http://gs.ua/a");
  */
  if(url==0 || url=="" || url===undefined)
	if(browser()=="Opera") window.location=location;
	else window.location.reload(location);
  else
	document.location.href=url;
  
  return true;
}

function php_json(params){ // преобразование в json вид
  if(typeof(params) == 'string'){
	params=params.split(':').join('":"');
	params=params.split(',').join('","');
	params='"'+params+'"';
	params = jQuery.parseJSON('{'+params+'}');
  }else if(typeof(params) != 'object'){
	params=0;
  }
  
  return params;
}

function strip_tags (input, allowed) {
  allowed = (((allowed || "") + "")
	.toLowerCase()
	.match(/<[a-z][a-z0-9]*>/g) || [])
	.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
	var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
	commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
  return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
	return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
  });
}

function ajax_php_insert( what, data, insert, upd_id ){
  if( $('#'+upd_id).length ) ch = '#'+upd_id;
  else if( $('.'+upd_id).length ) ch = '.'+upd_id;
  else ch = 'input[name='+upd_id+']';
  
  if(what=='get'){
	if(insert=='html')         res = jQuery(ch).html();
	else if(insert=='select')  res = jQuery(ch+' option:selected').attr('value');
	else if(insert=='checkbox'){
	  res = jQuery(ch).attr('checked');
	  if(res == 0 || res == false) res = false;
	  else res = true;
	}else                       res = jQuery(ch).val();
  }else if(what=='put'){
	if(insert=='html')         jQuery(ch).html(data);
	else if(insert=='select')  jQuery(ch+' option:selected').attr("value",data);
	else if(insert=='checkbox' && data.f!=undefined){
	  if(data.f == 0 || data.f == false) data.f = false;
	  else data.f = true;
	  jQuery(ch).attr('checked',data.f);
	}else                       jQuery(ch).val(data);
	res = true;
  }else if(what=='colour'){
	jQuery(ch).css("color",data);
	res = true;
  }
  
  return res;
}
function ajax_php( p ){
  
  var res = {};
  //alert( p );
  p = php_json(p);
  
  if(p.val_v==undefined)
	p.val_v = ajax_php_insert( 'get', 0, p.insert, p.upd_id );
  //alert( p.val_v );
  
  jQuery.ajax({
	//async:false,
	type: 'post',
	dataType: 'json',
	url: HTTP_HOST_S+'mine/api_smarty.php?json=yes&callback=?',
	data: p,
	beforeSend: function(a){
	  ajax_php_insert( 'colour', 'red', p.insert, p.upd_id );
	},
	success: function(data){
	  res = data;
	  ajax_php_insert( 'put', data, p.insert, p.upd_id );
	},
	complete: function(a,b){
	  ajax_php_insert( 'colour', 'green', p.insert, p.upd_id );
	  
	  if(p.upd_url == 1) window.location = location;
	  if(p.sm_compl == 1){
		sm={};
		if(p.text==undefined) sm.text = 'успешно';
		else sm.text = p.text;
		if(p.width==undefined) sm.width = 120;
		else sm.width = p.width;
		if(p.height==undefined) sm.height = 70;
		else sm.height = p.height;
		if(p.time==undefined) sm.time = 500;
		else sm.time = p.time;
		if(p.loc==undefined) sm.loc = '';
		else sm.loc = p.loc;
		
		showModal(sm.text, sm.width, sm.height, sm.time, sm.loc);
	  }
	}
  });
  
  return res;
}

function showModal(text, width1, height1, time, loc){ // showModal('text', 150, 90, 500, '')
	
  if(text=='') text='Ok!';
  if(width1==0) width1=230;
  if(height1==0) height1=200;
  width2=width1-4;
  height2=height1-4;
  text='<div id="basic-modal-content" style="overflow:auto; width:'+width2+'px; height:'+height2+'px;"> '+text+' </div>';

  jQuery.modal.close(); 
  jQuery.modal( text, {zIndex: 3202, closeHTML:"<a title='Close' class='modalCloseImg' style='cursor:pointer;'><img src='"+HTTP_HOST+"images/x.png'></a>", containerCss:{ height:height1, width:width1 }, overlayClose:true});

  if(time!=0){
	setTimeout( function() {
	  jQuery.modal.close();
		if(loc !== undefined && loc !='') window.location = loc; 
	},time); // half seconds
  }
}

function getCookie(name) {
  var prefix = name + "=";
  var cookieStartIndex = document.cookie.indexOf(prefix);
  if (cookieStartIndex == -1) return null;
  var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
  if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
  return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

sWind = {};

function jQuery_window( url, widht, height, title, val  ){
  ChBn=0;ChEnd=0;
  if((url == '' || url == 0) && sWind[val] != undefined){ // окно существует И url == NULL
	FooterContent = sWind[val].getFooterContent();
	ChBn = FooterContent.indexOf('|',0)+1;
	ChBn = FooterContent.indexOf('|',ChBn)+1; // after second
	ChEnd = FooterContent.length;
	url1 = FooterContent.substring(ChBn,ChEnd);
  }else{  // окно НЕ существует И/ИЛИ url != NULL
	url1 = url;
  }
  
  //alert('--'+sWind[val]+'--'+url+'--'+url1+'--'+val+'--'+ChBn+'--'+ChEnd+'--');
  
  FootCont = '<a style="cursor:pointer;" onClick="jQuery_window( 0, 0, 0, \'обновить\', \''+val+'\' );">upd</a>|<a style="cursor:pointer;" onClick="close_jQuery_window(\''+val+'\');">closed</a>|';
  
  html = '';
  jQuery.ajax({
    url: url1,
    success: function(data) {
      if( sWind[val]!=undefined ) { // окно существует  url=='' &&
		sWind[val].setTitle(title); // заменяем тайтл
        sWind[val].setContent(data); // заменяем контент
		sWind[val].setFooterContent(FootCont+url1); // заменяем контент подвала
      }else{ // открываем новое
        sWind[val] = jQuery.window({
          resizable: true,  
          title: title,
          //url: HTTP_HOST_S+"mine/products.php?"+val,
          content: data,
          footerContent: FootCont+url1,
          width: widht,
          height: height,
		  maxWidth: 0,
		  maxHeight: 0,
          x: 2,
          y: 2
        });
      }
	  return sWind[val];
    }
  });
}

function close_jQuery_window( val ){
  if( sWind[val] != null ) {
    sWind[val].close();
	sWind[val] = null;
  }
  window.location.reload();
  //document.location=document.location;
}
/*
Если нужно добавить вышеприведенное действие во все текстовые поля на странице, то можно воспользоваться следующей функцией:

function setTextBoxes() {
  var txtFields = document.getElementsByTagName('input');
  var textareaFields = document.getElementsByTagName('textarea');
  for(var i = 0, len = txtFields.length; i < len; i++) {
    if(txtFields[i].type == 'text' || txtFields[i].type = 'password') {
      txtFields[i].onfocus = function(){ this.select(); }
    }
  }
  for(var i = 0, len = textareaFields.length; i < len; i++) {
    textareaFields[i].onfocus = function(){ this.select(); }
  }
}
*/

function change_cur( val ){
  var val = parseJSON( val );
  
  return 
}

function debug_sort_direction( val, params ){
  val = val.split("_");
  if(val[1] == 'up' || val[1] == 'UP') res['direction'] = 'DESC';
  if(val[1] == 'down' || val[1] == 'DOWN') res['direction'] = 'ASC';
  if(val[0] == 'date') res['sort'] = 'date_added';
  if(val[0] == 'name') res['sort'] = 'name';
  if(val[0] == 'cost') res['sort'] = 'Price';
  
  return params;
}

function get_search_params( params ){

  params['by_optionID'] = (jQuery("#warehouse").attr('checked')==true)?'3':'0';
  params['sort'] = jQuery("#sort_name_cost_date option:selected").attr('value');
  params['PerPage'] = jQuery("#PerPage option:selected").attr('value');
  params['bid'] = jQuery("#asic_opt option:selected").attr('value');
  params['categoryID'] =  jQuery("#categoryID option:selected").attr('value');
  params["price_from"] = jQuery('#cat_val').attr("minSel");
  params["price_to"] = jQuery('#cat_val').attr("maxSel");
  
  return params;
}

function browser(){
  var ua = navigator.userAgent;
  
  if (ua.search(/MSIE/) > 0) return 'Internet_Explorer';
  if (ua.search(/Firefox/) > 0) return 'Firefox';
  if (ua.search(/Opera/) > 0) return 'Opera';
  if (ua.search(/Chrome/) > 0) return 'Google_Chrome';
  if (ua.search(/Safari/) > 0) return 'Safari';
  if (ua.search(/Konqueror/) > 0) return 'Konqueror';
  if (ua.search(/Iceweasel/) > 0) return 'Debian_Iceweasel';
  if (ua.search(/SeaMonkey/) > 0) return 'SeaMonkey';
  if (ua.search(/Gecko/) > 0) return 'Gecko';  // Браузеров очень много, все вписывать смысле нет, Gecko почти везде встречается
  return 'Search_Bot';  // а может это вообще поисковый робот
}


