function findNode(root,cb,all) {
 all = typeof(all) == 'boolean' && all;
 var results = [];
 var add = function(item) {
  if (item instanceof Array) {
   for (var i in item) results.push(item[i]);
  } else { results.push(item) }
 };
 if (!root.childNodes) return all ? [] : false;
 for (var c in root.childNodes) {
  var child = root.childNodes[c];
  var res = cb(child);
  if (res) if (all) { results.push(child) } else { return child; }
  res = findNode(child,cb,all);
  if (typeof(res) != 'boolean') if (all) { add(res) } else { return res; }
 }
 return all ? results : false;
}

function Part(name) {

 this.name = name;
 this.div = document.getElementById('part_'+name);

 this.exists = this.div ? true : false;
 if (!this.exists) return;

 this.content = document.getElementById('part_'+name+'_content');
 this.arrow = document.getElementById('part_'+name+'_arrow');

 if (!this.arrow) return; // frameless part

 var rx = /bt_(.*?)_(up|down)\.gif/i;
 var m = rx.exec(this.arrow.src);
 this.style = m[1];
 this.state = m[2];

 this.minimize = function() { this.toggle('down'); }
 this.restore = function() { this.toggle('up'); }

 this.reverse_state = function(state) {
  return state == 'up' ? 'down' : 'up';
 }

 this.display_state = function(state) {
  return { up: 'block', down: 'none' }[state];
 }

 this.toggle = function(new_state) {
  if (!new_state) new_state = this.reverse_state(this.state);
  this.arrow.src = this.arrow.src.replace(
    'bt_'+this.style+'_'+this.state,
    'bt_'+this.style+'_'+new_state
  );
  this.content.style.display = this.display_state(new_state);
  this.state = new_state;
  if (this.name.indexOf('ad_') != 0) // dont save ad toggles
  this.saveToggle(new_state);
 }

 this.saveToggle = function(state) {
  var c = new Cookies();
  c.set('part_'+this.name, state);
  c.save(true);
 }

 this.asyncLoad = function(wait_msg) {
  var name = this.name;
  var place = "part_" + name + "_dyn";
  var place_div = document.getElementById(place);
  if (wait_msg) place_div.innerHTML = wait_msg;
  var callback = function onDataLoad(data) {
   var obj = JSON.parse(data);
   var error_msg = "<span style='color: #BBB'>::error::</span>";
   var error = {msg:'',real:''}; 
   if (obj.error) error = {msg: 'Ошибка загрузки данных', real: obj.error};
   if (!error.real) {
    try {
     Jemplate.process(name+'.tpl', obj, '#'+place);
    } catch (e) { 
     error = {real:e.message, msg:'Ошибка обработки данных'} 
    }
   }
   if (error.real) place_div.innerHTML = error_msg.replace('::error::',
     error[location.search.indexOf('debug') > -1 ? 'real' : 'msg']);
  };
  Ajax.get('/beta/server.fcgi?part='+this.name,callback);
 }

}

function togglePart(event,part_name) {
 var part = new Part(part_name);
 if (part.exists) part.toggle();
}

function Cookies() { 
 this.jar = {};
 this.modified = [];
 this.chop = function(str) {
  str.replace(/\s+$/,'');
  str.replace(/^\s+/,'');
  return str;
 };
 this.parse = function() {
  var cookies = document.cookie.split(';');
  for (var n in cookies) {
   var cookie = cookies[n];
   var pair = cookie.split('=');
   var key = this.chop(pair[0]);
   var value = this.chop(pair[1]);
   this.jar[key] = value;
  }
 };
 this.keys = function() {
  var keys = [];
  for (var k in this.jar) keys.push(k);
  return keys;
 };
 this.set = function (key,value) { 
  this.jar[key] = value;
  this.modified.push(key);
 }
 this.save = function(expire) {
  if (expire) {
   var dt = new Date();
   dt.setFullYear( dt.getFullYear() + 1);
   var expire = dt.toGMTString();
   expire = "; expires=" + expire;
  } else {
   expire = '';
  }
  for (var i in this.modified) {
   var c = this.modified[i];
   var is_part = c.indexOf('part_') > -1;
   document.cookie = c + '=' + this.jar[c] + expire;
  }
  this.modified = [];
 };
 this.parse();
}

function restoreToggles() {
 var c = new Cookies();
 var cnt = 0;
 for (var k in c.jar) {
  if (k.indexOf('part_') > -1) {
   var state = c.jar[k];
   var part_name = k.substring(k.indexOf('part_')+5);
   var p = new Part(part_name);
   if (p.exists) { p.toggle( state ); cnt++ }
  }
 }
 return cnt;
}

function massClose(list) {
 for (var l in list) {
  var name = list[l];
  var p = new Part(name);
  if (p.exists) p.minimize();
 }
}

var search_default = 'http://search.uaportal.com/?';
var search_config = {
 net: [search_default,'',true],
 images: [search_default,'images',false],
 video: [search_default,'video',false],
 audio: [search_default,'audio',false],
 cat: ['http://uaportal.com/cgi_bin/search_catalog.cgi','cat',true],
 news: ['http://news.uaportal.com/pub/search','',false]
};

var region_map = {
  963: 318,
  141: 320,
  142: 321,
  960: 323,
  143: 317,
  977: 327,
  222: 328,
  144: 329,
  148: 330,
  145: 331,
  964: 332,
  965: 334,
  147: 340,
  962: 339,
  961: 341,
  966: 337,
  959: 327,
  146: 327,
  1110: 327,
  0: 0
};

function searchSubmit() {
 var f = document.forms['s_form'];
 var type = f.elements['type'].value;
 if (type == 'cat') {
  var r = f.elements['r'];
  try {
   var r_value = r.options[r.selectedIndex].value;
   r.options[r.selectedIndex].value = r_value == 187 ? 0 : region_map[r_value];
  } catch (e) {}
 }
}

function switchSearch(event,type,div) {
 if (window.event) event = window.event;
 var s_buttons = document.getElementById('search_buttons');
 for (var s in s_buttons.childNodes) {
  var button = s_buttons.childNodes[s];
  if (button.nodeName != 'DIV') continue;
  button.className = 'passive';
 }
 div.className = 'active';
 var config = search_config[type];
 var f = document.forms['s_form'];
 f.action = config[0];
 f.elements['type'].value = config[1];
 document.getElementById('geo').style.visibility = 
  config[2] ? 'visible' : 'hidden';
 try {
  event.preventDefault();
 } catch (e) {
  return event.returnValue = false;
 }
}

function initSearch() {
 var s_buttons = document.getElementById('search_buttons');
 for (var s in s_buttons.childNodes) {
  var button = s_buttons.childNodes[s];
  if (button.nodeName != 'DIV') continue;
  var type;
  for (var i in button.childNodes) {
   var a = button.childNodes[i];
   if (a.nodeName == 'A') {
    var qi = a.href.indexOf('?menu=');
    if (qi == -1) { type = 'net'; break; }
    type = a.href.substring(qi+6);
   }
  }
  var make_callback = function(type,div) {
   return function(event) { return switchSearch(event,type,div) };
  };
  button.onclick = make_callback(type,button);
 }
 document.forms['s_form'].reset();
}

var Parts;
function OnLoad() {
 for (var pi in Parts) {
  var part_name = Parts[pi];
  if (part_name.indexOf('ad_') == 0) continue;
  var part = new Part( part_name );
  if (!part.exists) continue;
  var part_header = findNode(part.div, function(node) {
   return node.nodeName == 'DIV' && node.className.indexOf('part_header') > -1;
  });

  part_header.className += ' clickable';
  part_header.onclick = function(part) {
   return function(event) { part.toggle(); }
  } (part);

  var links = findNode(
   part_header, 
   function(node) { return node.nodeName == 'A' },
   true
  );
  if (links.length > 0) for (var l in links) { //alert(l);
   links[l].onclick = function(event) {
    window.event ? window.event.cancelBubble = true : event.stopPropagation();
   }; }

 }
}

function __go(event,place) {
var t = event.srcElement || event.target; if (t.tagName != 'A') return;
if (t.href && t.href.indexOf('http://go.uaportal')==-1)
 t.href = "http://go.uaportal.com/?u="+escape(t.href) + '&f='
  + escape(location.href) + (place ? '&p='+place : '');
}