var IE = (document.all && document.getElementById && !window.opera);
var FF = (!document.all && document.getElementById && !window.opera);
var OP = (document.all && document.getElementById && window.opera);
var IE7 = (navigator.userAgent.indexOf('MSIE 7')>-1)?true:false;
var IE6 = (navigator.userAgent.indexOf('MSIE 6')>-1)?true:false;


function eMl(to, at) {
  document.write(to+'@'+at);
}

function IsNumeric(sText) {
  var ValidChars = "0123456789";
 
  for (i=0;i<sText.length; i++)  {  
    if(ValidChars.indexOf(sText.charAt(i)) == -1) 
      return false;
  }
  
  return true;
}

function hide(obj) {
  obj.style.display = 'none';
  return false;
}
function show(obj) {
  obj.style.display = 'block';
  return false;
}
function change(obj) {
  var block = 'block';
   
  if(FF) {
    switch(obj.tagName.toLowerCase()) {
      case 'table':
        block = 'table';
      break;
      case 'tr':
        block = '';
      break;
    }
  }
  /*cl(obj.tagName.toLowerCase());
  cl(block);
  cl(obj.style.display);*/

  if(obj.style.display == 'none')
    obj.style.display = block;
  else
    obj.style.display = 'none';
  return false;
}

/**
 *  Rozšiř HTMLElement o vlastní metody
 *  
 * @param {HTMLElement} element k rozšíření  
 */ 
$.extend = function(element) { 
  
  // poznámka že je již rozšířen
  element.__extended__ = true;
  
  element.sa = function(parametr, value) {
    
  switch( parametr.toLowerCase() ){
    
      case 'class':
        element.className = value; // narozdíl od setAtribute('class' / 'className',) funguje spolehlivě ve všech prohlížečích
        break;
      
      case 'onclick':
      case 'onmousedown':
      case 'onmouseup':
      case 'onmouseover':
      case 'onmouseout':
      case 'onmousemove':
        /**
         * Pokud je IE
         */         
        if(IE) {
          element[ parametr ] = function(event){          
            var e = getEvent(e);
            if((value.indexOf('(') && value.indexOf(')')) < 0) {
              return value.call(element, e);
            }
            else {
              eval(value);
            }
          }
        }else {
          // Jestli neobsahuje hranate zavorky
          if((value.indexOf('(') && value.indexOf(')')) < 0)
            element[ parametr ] = eval(value);
          else
            element.setAttribute(parametr, value);
        }
        break;

      case 'width':
      case 'height':
      case 'top':
      case 'left':
      case 'bottom':
      case 'right':
      case 'offsettop':
      case 'offsetleft':
      case 'offsetbottom':
      case 'offsetright':
      case 'offsetwidth':
      case 'offsetheight':
        element.style[parametr] = value + 'px';
        break;

      case 'zindex':
        element.style.zIndex = value;
        break;
      
      case 'style':
        if(IE) {
          var parse = value.split(';');
          
          for(var i=0;i<parse.length;i++) {
            try {
              var p = parse[i].split(':');
              element.style[p[0]] = p[1];
            }catch(e) {}  
          }
        }else {
          element.setAttribute(parametr,value);
        }
        break;

      case 'innerhtml':
        element.innerHTML = value;
      break;

      default:
        element.setAttribute(parametr,value);
        break;
    }
    
    // chain pattern
    return element;
  };
  
  element.setClassName = function( className ) {
    /**
     *  Pokud to tam jeste neni tak pridame
     */         
    if(element.className.indexOf(className) == -1)
      element.className += ' '+className;
      
    return element;
  };
  
  element.removeClassName = function( className ) {
    element.className = element.className.replace(className, '');
  
    return element;
  };
  
  element.nextObject = function() {
    var n = this;
    do n = n.nextSibling;
      while (n && n.nodeType != 1);
    return n;
  };
  
  element.previousObject = function() {
    var p = this;
    do p = p.previousSibling;
      while (p && p.nodeType != 1);
    return p;
  };
}

function htmlEntities(texto){
    //by Micox - elmicoxcodes.blogspot.com - www.ievolutionweb.com
    var i,carac,letra,novo='';
    for(i=0;i<texto.length;i++){
        carac = texto[i].charCodeAt(0);
        if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
            //se for numero ou letra normal
            novo += texto[i];
        }else{
            novo += "&#" + texto[i].charCodeAt(0) + ";";
        }
    }
    return novo;
}

Object.prototype.nextObject = function() {
  var n = this;
  do n = n.nextSibling;
    while (n && n.nodeType != 1);
  return n;
};  
Object.prototype.previousObject = function() {
  var p = this;
  do p = p.previousSibling;
    while (p && p.nodeType != 1);
  return p;
};
    

function remove(element) {
  element.parentNode.removeChild(element);
};


/**
 *  Fce vytvori element a vrati ho
 *
 *@param string t nazev noveho elementu
 *@return obj  novy element
 */              
function _cE(t) {
  return document.createElement(t);
}


function getMouseX (e) {
  if (e.pageX) { 
    return e.pageX;
  }else if (e.clientX) {
    return (e.clientX + document.body.scrollLeft);
  }
}
  
function getMouseY(e) {
  if (e.pageY) { 
    return e.pageY;
  }else if (e.clientY) {
    return (e.clientY + document.body.scrollTop);
  }
}




/**
 * Get element By id
 */ 
function ge(o1, o2) {
  var obj = document;
  var poss;
  
  if(typeof(o1) == 'object') {
    obj = o1;
    poss = o2;
  }else {
    poss = o1;
  }
    
  return obj.getElementById(poss);
}


/**
 * alias k console.log
 */
function cl(string) {
  try {
    return console.log(string);
  }catch(e){}
} 

/**
 * GET EVENT
 */ 
function getEvent(e) {
    if (!e) return window.event;
    return e;
}

/**
 *  INSERTAFTER
 */
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/**
 *  getElementsByClass
 */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (igc = 0, jgc = 0; igc < elsLen; igc++) {
		if ( pattern.test(els[igc].className) ) {
			classElements[jgc] = els[igc];
			jgc++;
		}
	}
	return classElements;
}


/**
 *  ADDEVENT
 */
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

function removeEvent( obj, type, fn ) {
  if (obj.detachEvent) {
    //obj[type+fn] = function(){ obj['e'+type+fn]( window.event ); }
    
    //obj.detachEvent( 'on'+type, obj[type+fn] );
    obj.detachEvent( 'on'+type, fn);
    //obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
} 



/**
 *  IN_ARRAY
 */

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

Array.prototype.toXHCon = Object.prototype.toXHCon = function(prefix) {
  var s = '';
  var k = '';
  
  if(!prefix) {
    prefix = '';
  }
  
  for(key in this) {
    if(prefix)
      k = prefix+'['+key+']'
    else
      k = key;

    if(typeof(this[key]) == 'string' || typeof(this[key]) == 'number') {
      s += k+'='+encodeURIComponent(this[key].toString())+'&';
    }
    else if(typeof(this[key]) == 'array' || typeof(this[key]) == 'object') {
      s += this[key].toXHCon(k);
    }
  }
  return s; 
}

Array.prototype.fromXHCon = Object.prototype.fromXHCon = function() {
  var val = this.split('&');
  var r = {};
  
  for(var i=0;i<val.length;i++) {
    var s = val[i].split('=');

    r[s[0]] = s[1];
  }
  
  return r;
}
String.prototype.reverse = function () {
  var x = '';
  for(var i=this.length-1;i>=0;i--) {
    x += this[i];
  }
  
  return x;
}



Object.prototype.inArray = Array.prototype.inArray = function (value) {  
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

Array.prototype.removeKey = function (removeKey) {
  var returnArr = new Array();
  var c = 0;

  for(key in this) {
    if(typeof(this[key]) != 'function') {
      if(key != removeKey) {
        returnArr[c++] = this[key];
      }
    }
  }
  return returnArr;
}

 
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.toNumber = function() {
  var s = this.toString();
  var m = new Array(0,1,2,3,4,5,6,7,8,9);
  var n = '';
  
  for(var i=0;i<s.length;i++) {
    switch (s.charAt(i)) {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        n += s.charAt(i);
      default :
       continue;
    }
  }
  return n*1;
}



function ReplaceTags(html) {
  return html.replace(/<\/?[^>]+>/gi, "");
}

/**
 *  COOKIE
 */  
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

/**
 * Náhrada document.getElementById
 * 
 * @param element {String / HTMLElement} id prvku nebo přímo reference na prvek 
 */   
function $( element ){

  // pokud se jedná od String s id prvku
  if(typeof element == "string"){
    element = document.getElementById( element );
    if(! element) return null;
  }
  
  // rozšiř prvek, pokud se tak již nestalo
    if(! element.__extended__ ){
      $.extend(element);
    }
  
  return element;
}

Object.prototype.getElements = function() {
  switch(this.tagName.toLowerCase()) {
  
    case 'form':
      var r = new Array();
      var temp = this.getElementsByTagName('input');
      for(var i=0;i<temp.length;i++) {
        r.push(temp[i]);
      }
      var temp = this.getElementsByTagName('select');
      for(var i=0;i<temp.length;i++) {
        r.push(temp[i]);
      }
      return r;
      
    break;
  }
}

Object.prototype.serialize = function() {
  switch(this.tagName.toLowerCase()) {
  
    case 'form':
      var obj = {};
      
      var temp = this.getElementsByTagName('input');
      for(var i=0;i<temp.length;i++) {
        if(temp[i].name)
          obj[temp[i].name] = temp[i].value;
      }
      
      var temp = this.getElementsByTagName('select');
      for(var i=0;i<temp.length;i++) {
        if(temp[i].name)
          obj[temp[i].name] = temp[i].value;
      }
      
      return obj.toXHCon();
      
    break;
  }
}




/**
 * Funkce rychle ziska vse jako getElementsByTagName
 */  
function $$() {
	var elements = new Array();
	var obj = document;
	
	if(arguments.length > 0) {
	  if(typeof arguments[0] == 'object') {
	    obj = arguments[0];
    }
  }
	
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = obj.getElementsByTagName(element);
		if (arguments.length == 1)
			return element;
		
		for (var k = 0; k < element.length; k++)
		  elements.push(element[k]);

	}
	return elements;
}




var onloadObserver = function() {
  var events = new Array();
  
  this.addEvent = function() {    
    var args = new Array();
    for(var i=1;i<arguments.length;i++) {
      args.push(arguments[i]);
    }
    
    
    events.push({'func': arguments[0], 'args': args});
  }
  
  this.run = function(obj) {
    for(var i=0;i<events.length;i++) {
      events[i].func.apply(events[i].func, events[i].args);
    }
  }
}

var observer = new onloadObserver;

window.onload = function (){
  observer.run();
}
