
var current = null;

var timerID = null;
var timeout = 2500;
var hide = false;
var change_enabled = true;

var new_value_changed = false;

function mm_over (index)
{
  if (!change_enabled) return;
  if (mm_ids == null) return;

  for (i=1; i<mm_ids.length; i++)
  {
     a = getElById('submenu_' + mm_ids[i]);
     showorhide(a, false, true);
  }
  if (!index) return;

  showorhide(getElById('submenu_' + index), true, true);

  obj = getElById('mm_id' + index)
//obj.style.filter="blendTrans(duration=1)";obj.filters.blendTrans.apply()
;
  obj.style.background='#ED6E00'
//obj.filters.blendTrans.play()
;

  hide = false;
}

function mm_out (index)
{
  if (!change_enabled) return;
  if (mm_ids == null) return;

  for (i=1; i<mm_ids.length; i++)
     getElById('mm_id' + mm_ids[i]).style.background='#CCCCCC';

  hide = true;

  timerID = setTimeout("mm_timecheck()", timeout);
}

function mm_timecheck ()
{
  if (hide) {
    mm_out ('');
    if (current != null) mm_over (current);
    hide = false;
  }
  clearTimeout(timerID);
  timerID = null;
}

function mm_hint_over ()
{
  hide = false;
}

function mm_hint_out ()
{
  hide = true;
//  timerID = setTimeout("mm_timecheck()", timeout);

}

function mm_start ()
{
  mm_out ('');
  mm_over (current);
}

function showorhide(object, visible, resize)
{
resize = false;
  if (visible) {
//$('#' + object.id).show('slow');

    object.style.visibility='visible';
    object.style.display='inline';
    if (resize) {
       object.style.width='auto';
       object.style.height='auto';
    }
  }else{
//$('#' + object.id).hide('fast');

    object.style.visibility='hidden';
    object.style.display='none';
    if (resize) {
       object.style.width='1px';
       object.style.height='1px';
    }
  }
}

function add_to_compare(item)
{
  item = 'compare' + item;
  var val = GetCookie (item);

  // битые флажки?
  if (getElById(item).checked == (val == 1)) Refresh ();

  if (val == null) val = 0;
  if (val == 0) {
     SetCookie (item, 1);
  }else{
     SetCookie (item, 0);
     ExpireCookie (item);
  }

  // ставим или сбрасываем флажок
  getElById(item).checked = (val == 0);

  // в зависимости от количества флажков - убираем либо показываем панель
  get_compare_list ();
  showorhide (div_compare, (compare_list_last != 0), true);
}

/* Функции поиска позиций, выбранных пользователем */
var compare_list = new Array;
var compare_list_last = 0;
function get_compare_list ()
{
   var str = document.cookie + ';';
   var len = str.length;
   var counter = 0;
   compare_list_last = 0;
   for (i = 0; i < len; i ++)
   {
      counter++;
        // защита от зацикливания
        if (i == 0 && counter != 1) break;
        if (counter > 70) break;

      //
      iend = str.indexOf ("=", i);
      inext = str.indexOf (";", i);

      // извлекаем название параметра
      paramname = str.substring(i, iend);
      if (paramname.substring (1,8) == 'compare') 
      if (str.substring(iend+1, inext) == '1')
          // Нашли и галочка включена
          compare_list [compare_list_last++] = paramname.substring (8);

      // переходим к следующему параметру
      i = inext;
   }
}

function something_in_compare ()
{
    get_compare_list ();
    return compare_list_last != 0;
}



function CookieBranding(name) {
  if (typeof foldersTree == "undefined") return name;
  if (typeof foldersTree.treeID == "undefined") return name;
  return name+foldersTree.treeID //needed for multi-tree sites. make sure treeId does not contain cookieCutter
}

function GetCookie(name)
{
  if (typeof GIVECLICKED != "undefined")
  if (GIVECLICKED == 0 && name == 'clickedFolder') return; // куки clickedFolder не отдаем

  name = CookieBranding(name)

  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);

    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function getCookieVal(offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
  endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function SetCookie(name, value)
{
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  //var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
  var path = "/"; //allows the tree to remain open across pages with diff names & paths

  name = CookieBranding(name)

  document.cookie = name + "=" + escape (value) +
  ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
  ((path == null) ? "" : ("; path=" + path)) +
  ((domain == null) ? "" : ("; domain=" + domain)) +
  ((secure == true) ? "; secure" : "");
}

function ExpireCookie (name)
{
  var expi = new Date();
  expi.setTime (expi.getTime() - 1);
  var cval = GetCookie (name);
  name = CookieBranding(name);
  document.cookie = name + "=" + cval + "; expires=" + expi.toGMTString() + "; path=/";
}

function getElById(idVal) {
  if (document.getElementById != null)
    return document.getElementById(idVal)
  if (document.all != null)
    return document.all[idVal]
  
  alert("Problem getting element by id")
  return null
}

function del_from_compare(item)
{
  SetCookie ('compare' + item, 0);
}

// Открытие нового окна
var wnd, timer;
function newwindow(url,WinName,capt,width,height,resize) {
//	window.status= '123';
   var w=690; if (width) w = width;
   var h=630; if (height) h = height;
   var r="no"; if (resize) r = resize;
   Win = open(url.replace('#','%23'), WinName, "scrollbars,width="+w+",height="+h+",resizable="+r+",toolbar=no,location=no,directories=no,status=no,menubar=no,left=200,top=100");
//   Win.menubar = 0;
   if (capt) 
	Win.title=capt;
   Win.focus();
   wnd = Win;
//   return Win;
}

function itemtocart (id)
{
	$("<div></div>").load('http://www.simm.ru/price?cart=add&id=' + id + '&showbar=');
}

function logout (itemsincart)
{
/*	itemsincart = $('#cart').is(':visible');

	if (itemsincart)
//	if (itemsincart != '') 
	if (!window.confirm('Ваша корзина также будет удалена.\r\nВы действительно хотите выйти?'))
		return false;*/

	$('<div></div>').load('http://www.simm.ru/user/login/?logout=1&noredir=');

	var url = window.location + "";
	if (url.substring (0,23) == 'http://www.simm.ru/user')
		url = 'http://www.simm.ru';

	window.location = url;

	return false;
}

function change_orgother()
{
	var orgother = $("#orgother").val();
	go_url_addparam ('orgother', orgother);
}

function change_org(selectid)
{
	// Если нужно сразу и выбрать
	if (selectid)
	{
		$("#org").val(selectid);
	}

	// Выбранная организация
	var org = $("#org").val();
	if (org == -1)
	{
		$("#orgother").attr('style','visibility:visible');//show();
		$("#orgother_save").attr('style','visibility:visible');//.show();
		return;
	}
	else
	{
		$("#orgother").val('');
		$("#orgother").attr('style','visibility:hidden');//.hide();
		$("#orgother_save").attr('style','visibility:hidden');//.hide();
	}

	// Если нужно выбрать, значит не переходим
	if (selectid) return;

	// Делаем переход
	go_url_addparam ('org', org);
}


function go_url_addparam (name, value)
{
	// Берем текущий адрес
	var loc = window.location + '';

	// Ищем организацию
	var pos;
	pos = loc.indexOf('org=');
	if (pos >= 0) loc = loc.substr(0,pos-1);
	pos = loc.indexOf('orgother=');
	if (pos >= 0) loc = loc.substr(0,pos-1);

	// Если уже есть знак ? в строке адреса, то добавляем со знака &
	if (loc.indexOf('?') >= 0)
	{
		//
		loc += '&';
	}
	else
	{
		// Если нет в конце палки, добавляем
		var lastchar = loc.substring(loc.length - 1);

		if (lastchar != '/') loc += '/';

		// 
		loc += '?';
	}

	// Заканчиваем генерацию нового адреса
	loc += name + '=' + value;

	// Делаем переход на новый адрес
	window.location = loc;
}

function on_sc2_firmselect ()
{
	//$("#FirmID").val();
	if ($("#FirmID").val() == -1)
		$("#orgother_div").attr('style','display:;');
	else	$("#orgother_div").attr('style','display:none;');
}
