var IE = !+"\v1";
var module = 'index';

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());
    }
  }
  url += "&rows="+Engine.rows();
  ajax.open('GET', url, true);
  ajax.send(null);
}
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);
}
function callHandle(url,json, callback, urllock){
  if(!urllock){
    var nowurl = url.replace('/ajax','').split('?')[0];;
    location.href = "#"+nowurl;
    if(_gaq && _gaq.push){
      _gaq.push(['_trackPageview', nowurl]);
    }
    Engine.page = location.href;
  }
  var obj;
  try{
    if(typeof(JSON) === "object" && typeof(JSON.parse) === "function")
      obj = JSON.parse(json);
    else
      eval("obj = "+json+";");
    if(obj.title) document.title = obj.title;
    if(obj.description){
      document.getElementById("sitedescription").content = obj.description.replace(/\<[^\>]*\>/g,'').substring(0,250);
    }
  }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...';
}

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;
}

var index_rows;
function mainer(){
  var ext = document.getElementById("main_ext");
  if(!ext) return;
  var index = document.getElementById("index");
  var inn = document.getElementById("in");
  var all = document.getElementById("all");
  var effect = {
    conf: {from: 0, to: 165, speed: 500},
    Pre: function(){
      index.style.bottom = this.from+"px";
      inn.style.bottom = this.from+"px";
      changeOpac(this.el, 0);
    },
    Run: function(){
      var now = this.from + this.ratio*this.to;
      index.style.bottom = now+"px";
      inn.style.bottom = now+"px";
    },
    Post: function(){
      index.style.bottom = this.to+"px";
      inn.style.bottom = this.to+"px";
    }
  };
  
  getIndex(function(){
    setTimeout(function(){
      var moved = false;
      window.onmousemove = function(){
        if(moved) return;
              moved = true;
        changeOpac(ext, 0);
        ext.style.display = 'block';
        RunEffect(ext, effect, {callback: function(e){
          RunEffect(e, "fadeIn", {speed: 500});
        }});
        window.onmousemove = function(){};
      };
    }, 2000);
  });
  
  index_rows = Engine.rows();
  window.onresize = function(){
    if(Engine.rows() != index_rows){
      getIndex();
      index_rows = Engine.rows();
    }
  }
}
function getIndex(cb){
  var ext = document.getElementById("main_ext");
  if(!ext) return;
  callMe("/index.php", function(o){
    ext.innerHTML = o.html;
    Engine.Hrefy();
    if(typeof(cb) == "function"){
      cb();
    }
  }, true);
}
AddLoad(function(){
  mainer();
});

function SendForm(form){
  var err = {};
  var val = {};
  var error = false;
  for(var i=0; i<form.elements.length; i++){
    var el = form.elements[i];
    if((el.type != "submit") && (el.value == el.defaultValue)){
      el.value = "";
    }
    el.blur();
    if(el.type != "submit"){
      if(!el.value){
        err[el.name] = true;
        error = true;
      }
      val[el.name] = el.value;
    }
  }
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  if(!reg.test(form.elements.email.value)){
    err.email = true;
    error = true;
  }
  if(!error){
    kropker.start(20);
    var post = "name="+val.name+"&email="+val.email+"&subject="+val.subject+"&body="+val.body;
    callMePost("/sendmail.php", post, function(o){
      if(o.ok){
        alert("Wiadomość została wysłana");
      }else{
        alert("Błąd. Spróbuj ponownie");
      }
      kropker.stop();
    }, true);
  }
  
  for(var i=0; i<form.elements.length; i++){
    var el = form.elements[i];
    if(el.type != "submit" && !el.value){
      el.value = el.defaultValue;
    }
    if(err[el.name]){
      el.className = "error";
    }else{
      el.className = "";
    }
  }
  return false;
}

var kropker = {
  el: null,
  run: false,
  now: 0,
  from: 0,
  speed: 20,
  Init: function(){
    this.el = document.getElementById("all");
  },
  start: function(speed){
    if(!this.el) return;
    this.speed = speed;
    this.from = Number(new Date());
    this.run = true;
    requestAnimFrame(function(){ kropker.step(); });
  },
  step: function(){
    if(!this.run) return;
    var t = Number(new Date()) - this.from;
    now = Math.round((t%(this.speed*10))/this.speed);
    this.el.style.backgroundPosition = "0 "+now+"px";
    requestAnimFrame(function(){ kropker.step(); });
  },
  stop: function(){
    if(!this.el) return;
    this.run = false;
    this.el.style.backgroundPosition = "0 0";
  },
  set: function(h){
    while(h<0) h+=100;
    h = h%10;
    this.el.style.backgroundPosition = "0 "+h+"px";
  }
};
AddLoad(function(){ kropker.Init(); });

function Hover(el, type){
  type = type=="in" ? "fadeIn" : "fadeOut";
  RunEffect(el, type);
}
