var IE = !+"\v1";

function callMe(url, callback, urllock){
  ajaxObject = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e){
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e){
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e){
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){
  try { return new XMLHttpRequest(); } catch(e){
  throw new Error( "This browser does not support XMLHttpRequest." );
  }}}}}};
  ajax = new ajaxObject();
  ajax.onreadystatechange = function(){
    if(ajax.readyState == 4){
      if(ajax.status == 200){
        callHandle(url,ajax.responseText,callback,urllock);
      }
    }
  };
  if(url.indexOf('time') == -1){
    if(url.indexOf('?') == -1){
      url += '?time='+Number(new Date());
    }else{
      url += '&time='+Number(new Date());
    }
  }
  ajax.open('GET', url, true);
  ajax.send(null);
  return ajax;
}
function callMePost(url, params, callback, urllock){
  ajaxObject = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e){
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e){
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e){
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){
  try { return new XMLHttpRequest(); } catch(e){
  throw new Error( "This browser does not support XMLHttpRequest." );
  }}}}}};
  ajax = new ajaxObject();
  ajax.onreadystatechange = function(){
    if(ajax.readyState == 4){
      if(ajax.status == 200){
        callHandle(url.replace('ajax/',''),ajax.responseText,callback,urllock);
      }
    }
  };
  ajax.open('POST', url, true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("Content-length", params.length);
  ajax.setRequestHeader("Connection", "close");
  ajax.send(params);
  return ajax;
}
function callHandle(url,json, callback, urllock){
  var obj;
  try{
    if(typeof(JSON) === "object" && typeof(JSON.parse) === "function")
      obj = JSON.parse(json);
    else
      eval("obj = "+json+";");
  }catch(e){
   obj = json;
  }
  if(typeof(callback) === "function"){
    callback(obj);
  }
}
function qqUploaded(id, filename, responseJSON){
  if(responseJSON && responseJSON.success){
    var el = document.getElementById(id);
    el.parentNode.innerHTML = (responseJSON.msg ? responseJSON.msg : filename).replace('&lt;','<').replace('&gt;','>');
  }
}
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function trim(str){
  s = str.replace(/^(\s)*/, '');
  s = s.replace(/(\s)*$/, '');
  return s;
}

function EmitSignal(signal, value, values){
  var els;
  for(var i=0; i<values.length; i++){
    els = document.getElementsByName("show["+signal+"_"+values[i]+"]");
    for(j=0;j<els.length;j++){
      els[j].style.display = (value==values[i]?'':'none');
    }
  }
}

var LoaderFunctions = [];
var LoaderLoaded = false;
var LoaderLastOnLoad = window.onload;
if(typeof(LoaderLastOnLoad) !== 'function')
  window.onload = FireLoader;
else
  window.onload = function(){LoaderLastOnLoad(); FireLoader();};
var LoaderLastContentLoaded = window.DOMContentLoaded;
if(typeof(LoaderLastContentLoaded) !== 'function')
  window.DOMContentLoaded = FireLoader;
else
  window.DOMContentLoaded = function(){LoaderLastContentLoaded(); FireLoader();};
function AddLoad(func){
  LoaderFunctions.push(func);
}
function FireLoader(){
  for(var i=0; i<LoaderFunctions.length; i++){
    LoaderFunctions[i]();
  }
  LoaderFunctions = [];
}

function ShowHide(id){
  var el = document.getElementById(id);
  if(el){
    if(el.style.display !== 'block'){
      el.style.display = 'block';
    }else{
      el.style.display = 'none';
    }
  }
}

function stop(e){
  if (!e) var e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}
function RegDebug(id){
  el = document.getElementById(id);
  if(!el) return;
  el.onclick = function(){ShowHide(id)};
  el.firstChild.onclick = stop;
}
AddLoad(function(){RegDebug('debugger'); RegDebug('transger'); });

var tKeys = '';
function Trans(){
  var el = document.getElementById("transger");
  if(el) el = el.firstChild;
  else return;
  if(!el.loaded){
    tKeys = el.innerHTML;
    el.innerHTML = 'Loading...';
    callMe("trans.php?keys="+tKeys, function(o){
      el.innerHTML = o.html;
    }, true);
    el.loaded = true;
  }
  ShowHide('transger');
}
function TransSubmit(form){
  var el, send=[], keys=[];
  for(var i=0; i<form.elements.length; i++){
    el = form.elements[i];
    if(!el.name) continue;
    keys.push(el.name);
    if(el.value == el.defaultValue) continue;
    send.push("trans["+el.name+"]="+el.value);
  }
  var el = document.getElementById("transger");
  if(el) el = el.firstChild;
  callMePost("trans.php?keys="+tKeys, send.join('&'), function(o){
    el.innerHTML = o.html;
    alert("Saved");
  }, true);
  el.innerHTML = 'Sending...';
}

var msTimer = null;
var msID = 0;
function MainSlide(id){
  var i=0;
  var a,b;
  while(a = document.getElementById("big_slide_"+i)){
    b = document.getElementById("small_slide_"+i);
    a.style.display = i==id ? "" : "none";
    b.className = "slider_mini"+(i==id?" active":"");
    i++;
  }
  msID = id;
  MainSlideDefer();
}
function MainSlideDefer(){
  if(msTimer) clearTimeout(msTimer);
  msTimer = setTimeout(function(){ MainSlideNext(); }, 5000);
}
function MainSlideNext(){
  msID++;
  if(!document.getElementById("big_slide_"+msID)){
    msID = 0;
  }
  MainSlide(msID);
}
AddLoad(function(){
  if(document.getElementById("big_slide_0")){
    MainSlideDefer();
  }
});
var mhsTimer = null;
var mhsID = 0;
function MainHotelSlide(id){
  var i=0;
  var a,b;
  while(a = document.getElementById("hotel_slide_"+i)){
    b = document.getElementById("small_hotel_"+i);
    a.style.display = i==id ? "" : "none";
    b.className = "miejsca_mini"+(i==id?" active":"");
    i++;
  }
  mhsID = id;
  MainHotelSlideDefer();
}
function MainHotelSlideDefer(){
  if(mhsTimer) clearTimeout(mhsTimer);
  mhsTimer = setTimeout(function(){ HotelSlideNext(); }, 5000);
}
function HotelSlideNext(){
  mhsID++;
  if(!document.getElementById("hotel_slide_"+mhsID)){
    mhsID = 0;
  }
  MainHotelSlide(mhsID);
}
AddLoad(function(){
  if(document.getElementById("hotel_slide_0")){
    MainHotelSlideDefer();
  }
});

function FancyOrder(url, el){
  url = ("."+url).replace(",sort_X",",sort_"+el.value).replace(",sort_new","");
  location.href = url;
}

function PagerPrev(el, page, pages, url){
  do{
    el = el.nextSibling;
  }while(el.nodeType != 1);
  var now = parseInt(el.getAttribute("rel"));
  var from = Math.max(now-10, 0);
  var to = Math.min(from+10, pages);
  PagerDraw(el, from, to, page, url);
}
function PagerNext(el, page, pages, url){
  do{
    el = el.previousSibling;
  }while(el.nodeType != 1);
  var now = parseInt(el.getAttribute("rel"));
  var to = Math.min(now+20, pages);
  var from = Math.max(to-10, 0);
  PagerDraw(el, from, to, page, url);
}
function PagerDraw(el, from, to, page, url){
  var inner = "", link;
  if(page < from) inner += "|";
  for(i=from; i<to; i++){
    if(i<page) inner += "|";
    if(i==page) inner += "<span class=\"now\">|";
    if(i!= page){
      if(i==0){
        link = url.replace(',page_X',"");
      }else{
        link = url.replace('page_X',"page_"+i);
      }
      inner += " <a class=\"gray\" href=\"."+link+"\">"+(i+1)+"</a> ";
    }else{
      inner += " "+(i+1)+" |</span> ";
    }
    if(i>page) inner += "|";
  }
  if(page >= to) inner += "|";
  el.innerHTML = inner;
  el.setAttribute("rel", from);
}

var scrollI = null;
var scrollH;
var inscrollH;
var scrollSpeed = 3;
function scroller(top, el, side){
  top = document.getElementById(top);
  el = document.getElementById(el);
  if(!top || !el) return;
  scrollH = top.offsetHeight;
  inscrollH = Math.max(el.offsetHeight-scrollH,0);
  scrollI = setInterval(function(){ scrollerer(el, side); }, 40);
}
function unscroller(){
  if(scrollI) clearInterval(scrollI);
}
function scrollerer(el, side){
  var now = parseInt(el.style.top)
  if(!now) now = 0;
  now += side*scrollSpeed;
  if(side == 1 && now >= 0){
    el.style.top = "0px";
    return;
  }
  if(side == -1 && now <= -inscrollH){
    el.style.top = -inscrollH+"px";
    return;
  }
  el.style.top = now+"px";
}

function Polled(form){
  var e = form.elements;
  for(var i=0; i<e.length; i++){
    if(e[i].name == "poll[answer]" && e[i].checked) return true;
  }
  return false;
}

var cyclic = [];
var cyclen;
var cycel;
var cycnow = 0;
var cyclock = false;
var cychref = null;
AddLoad(function(){
  cycel = document.getElementById("incyclic");
  if(!cycel) return;
  var cn = cycel.childNodes;
  for(var i=0; i<cn.length; i++){
    if(cn[i].nodeType == 3){
      cycel.removeChild(cn[i]);
      i--;
    }else{
      cyclic.push(cn[i]);
    }
  }
  cyclen = cyclic.length;
  var l = document.getElementById("inyoutube_left");
  var r = document.getElementById("inyoutube_right");
  cychref = document.getElementById("cyclic_href");
  if(cyclen <= 1){
    l.style.display = "none";
    r.style.display = "none";
  }else{
    l.onclick = function(){
      cycmove(-1);
      return false;
    };
    r.onclick = function(){
      cycmove(1);
      return false;
    };
  }
  cychref.href = cyclic[cycnow].href;
});
function cycmove(side){
  if(cyclock) return;
  cyclock = true;
  var from = cyclic[cycnow];
  cycnow = (cycnow+side+cyclen)%cyclen;
  var to = cyclic[cycnow];
  RunEffect(from, "move", {from: 0, to: -side*310});
  RunEffect(to, "move", {from: side*310, to: 0, callback: function(){
    from.style.display = "none";
    cyclock = false;
  }});
}

function FBlogin(){
  FB.getLoginStatus(function(response) {
    if (response.authResponse) {
      var me = document;
      callMe("/face.php", function(o){
        if(o.redir){
          var h = me.location.href;
          me.location.href = h;
        }else if(o.error){
          alert(o.error);
        }
      }, true);
    }else{
      FB.Event.subscribe('auth.login', function(response) {
        FBlogin();
      });
    }
  });
}

function trim(str){
  var str = str.replace(/^\s\s*/, ''),
  ws = /\s/,
  i = str.length;
  while (ws.test(str.charAt(--i)));
  return str.slice(0, i + 1);
}
function cleanTextNodes(e){
  if(e.cleaned) return;
  var cn = e.childNodes, i;
  for(i=0; i<cn.length; i++){
    if(cn[i].nodeType == 3){
      if(!trim(cn[i].data)){
        e.removeChild(cn[i]);
        i--;
      }
    }else{
      cleanTextNodes(cn[i]);
    }
  }
  e.cleaned = true;
}
function MailSelect(type){
  var wrap = document.getElementById("wiadomosci");
  var cn = wrap.childNodes, i, reg = /^blok_item/, reg2 = /unread$/;
  for(i=0; i<cn.length; i++){
    var el = cn[i];
    if(el.nodeType != 3 && reg.test(el.className)){
      cleanTextNodes(el);
      var check = el.firstChild.firstChild;
      switch(type){
        case "":
        case "none":
          check.checked = false;
          break;
        case "all":
          check.checked = true;
          break;
        case "read":
          check.checked = !reg2.test(el.className);
          break;
        case "unread":
          check.checked = reg2.test(el.className);
          break;
      }
    }
  }
}
function MailAction(type){
  if(!type) return;
  var wrap = document.getElementById("wiadomosci");
  var cn = wrap.childNodes, i, reg = /^blok_item/;
  var data = [];
  for(i=0; i<cn.length; i++){
    var el = cn[i];
    if(el.nodeType != 3 && reg.test(el.className)){
      cleanTextNodes(el);
      var check = el.firstChild.firstChild;
      if(check.checked) data.push(check.value);
    }
  }
  if(data.length) location.href = location.href+"?a="+type+"&ids="+data.join(",");
}

var Stars = {
  el: null,
  w: 95,
  r: 0,
  Init: function(){
    if(this.el = document.getElementById("starVote")){
      this.el.onclick = function(){ Stars.vote(); return false; }
      this.el.firstChild.onmouseover = function(e){ Stars.hover(e) };
      this.el.firstChild.onmouseout = function(e){ Stars.unhover(e) };
    }
  },
  vote: function(){
    if(this.r){
      var url = this.el.getAttribute("rel").replace("vote_X","vote_"+this.r);
      location.href = url;
    }
  },
  hover: function(e){
    var el = this.el.firstChild;
    el.onmousemove = function(e){ Stars.move(e); };
    Stars.move(e);
  },
  move: function(e){
    e = e || window.event;
    var x = e.pageX-10;
    var el = this.el;
    do{
      x -= el.offsetLeft;
    }while(el = el.offsetParent);
    var r = Math.floor(5*x/this.w)+1;
    if(this.r != r){
      this.el.firstChild.src = "/image/layout/gfx/stars"+r+"B.png";
      this.r = r;
    }
  },
  unhover: function(e){
    var el = this.el.firstChild;
    el.onmousemove = function(){ };
  }
}
AddLoad(function(){ Stars.Init(); });

function submitFormPKT(){
  if(document.forms.pkt_szukaj.klucz.value == "") {
    document.forms.pkt_szukaj.klucz.value = "-";
  }
  var path = '-' + '/q_' + encodeURIComponent(document.forms.pkt_szukaj.klucz.value) + '/1/?edsacid=' +  encodeURIComponent(document.forms.pkt_szukaj.kto.value);
  window.open('http://www.pkt.pl/firmy/' + path, '_blank'); 
  document.getElementById("klucz").value = "";
  return false;
}

/* Wrappers */
// function getStyle(el, rule){
//   var val = "";
//   if(document.defaultView && document.defaultView.getComputedStyle){
//     val = document.defaultView.getComputedStyle(el, "").getPropertyValue(rule);
//   }else if(el.currentStyle){
//     rule = rule.replace(/\-(\w)/g, function(m, p){
//       return p.toUpperCase();
//     });
//     val = el.currentStyle[rule];
//   }
//   return val;
// }
function getStyle(el,styleProp){
  if (el.currentStyle){
    styleProp = styleProp.replace(/\-(\w)/g, function(m, p){
      return p.toUpperCase();
    });
    var y = el.currentStyle[styleProp];
  }else if (window.getComputedStyle){
    var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
  }
  return y;
}

function MeasureText(text, par){
  var el = document.createElement('span');
  el.style.visibility = 'hidden';
  el.style.zIndex = '-10';
  el.style.position = 'absolute';
  el.style.fontFamily = getStyle(par, 'font-family');
  var fs =  getStyle(par, 'font-size');
  if(fs.indexOf('%')) fs = '14px';
  el.style.fontSize = fs;
  el.style.fontWeight = getStyle(par, 'font-weight');
  el.innerHTML = text;
  document.body.appendChild(el);
  var wid = el.offsetWidth;
  document.body.removeChild(el);
  return wid;
}
var WrapInterval = 25;
var WrapWait = 500;
var WrapSpeed = {};
WrapSpeed[1] = 500;
WrapSpeed[-1] = 50;

function Wrap(el){
  if(el.wrapper) return;
  if(!el.textWidth) el.textWidth = MeasureText(el.innerHTML, el);
  if(el.textWidth > el.offsetWidth){
    el.parentNode.onmouseout = function(){UnWrap(el);};
    el.lastWrap = Number(new Date());
    el.wrapSide = -1;
    el.wrapper = setInterval(function(){
      var now = parseFloat(el.style.textIndent);
      if(!now) now = 0;
      var time = Number(new Date());
      if(time <= el.lastWrap) return;
      var tt = time - el.lastWrap;
      el.lastWrap = time;
      var wrap = now + el.wrapSide * (WrapSpeed[el.wrapSide]*tt/1000);
      if(wrap <= el.offsetWidth-el.textWidth){
        el.wrapSide = 1;
        wrap = el.offsetWidth-el.textWidth;
        el.lastWrap = time+WrapWait;
      }else if(wrap >= 0){
        el.wrapSide = -1;
        wrap = 0;
        el.lastWrap = time+WrapWait;
      }
      el.style.textIndent = wrap+'px';
    }, WrapInterval);
  }
}
function UnWrap(el){
  clearInterval(el.wrapper);
  el.style.textIndent = '0px';
  el.wrapper = null;
}
