String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
};

function previousElement(ele) {
  ele = ele.previousSibling;
  while (ele.nodeType != 1) {
    ele = ele.previousSibling;
  }
  return ele;
}

function switch_tags(id) {
  var e = $id('tags_' + id);
  var a = $id('link_' + id);
  if (e) {
    if (e.style.display == 'none') {
      e.style.display = '';
      a.innerHTML = "[&laquo;]";
    } else {
      e.style.display = 'none';
      a.innerHTML = "[&raquo;]";
    }
    e.parentNode.style.visibility = 'visible'
  }
}

function $id(id) {
  if (typeof id == 'string') {
    return document.getElementById(id);
  }
  return id;
}

// get window size
function windowHeight() {
  return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
}

function windowWidth() {
  return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
}

// get pixel position of an object
function getY(o) {
  var y = 0;
  if (o.offsetParent) {
    while (o.offsetParent) {
      y += o.offsetTop;
      o = o.offsetParent;
    }
  }
  return y;
}

function getX(o) {
  var x = 0;
  if (o.offsetParent) {
    while (o.offsetParent) {
      x += o.offsetLeft;
      o = o.offsetParent;
    }
  }
  return x
}

function setX(o, n) {
  o.style.left = n + 'px';
}

function setY(o, n) {
  o.style.top = n + 'px';
}

function footer() {
  var dif = 0;
  var h = windowHeight()
  var footer = $id('footer')
  var bottom = getY($id('bottom'))
  if ($id('sidebarbottom')) {
    var sidebar = getY($id('sidebarbottom'))
  } else {
    var sidebar = 0;
  }
  var fh = footer.clientHeight || footer.offsetHeight // todo: why does IE report 0 for clientHeight?
  if (sidebar > bottom) {
    if ((h - fh) < sidebar) {
      var dif = sidebar - bottom
    }
  }
  if (bottom != 0) {
    if (bottom < h - fh) {
      if (dif == 0) {
        if (/MSIE/.test(navigator.userAgent) && !window.opera) {
          bottom = bottom +5;
          footer.style.marginTop = ((h - fh)-bottom-15)+'px'
        } else {
          fh = fh +1;
          footer.style.marginTop = ((h - fh)-bottom-18)+'px'
        }
      } else {
        footer.style.marginTop = (dif)+'px'
      }
    } else {
      footer.style.marginTop = (dif)+'px'
    }
  }
  footer.parentNode.style.visibility = 'visible'
}

function email_validate(email) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
    return true;
  }
  return false;
}

Loader = function(Container, path, myParam) {
  timestamp = new Date();
  var url = 'http://' + window.location.hostname + '/' + path;
  var pars = myParam + '&t=' + timestamp.getTime();
  var myAjax = new Ajax.Updater(
    {
      success: Container
    }, 
    url,
    {
      method: 'get', 
      parameters: pars, 
      onSuccess: doSuccess,
      onComplete: reportComplete,
      onFailure: reportError
    }
  );
};

Loader2 = function(path, myParam) {
  timestamp = new Date();
  var url = 'http://' + window.location.hostname + '/' + path;
  var pars = myParam + '&t=' + timestamp.getTime();
  var myAjax = new Ajax.Request (
    url,
    {
      method: 'get', 
      parameters: pars,
      onComplete: function() {
        setHeight(Container);
        initMonthBar(Container);
        var oldColor = Element.getStyle($('f' + Container), 'backgroundColor')
        doBGFade($('f' + Container),[192,192,205],[245,245,245],oldColor,20,20,1);
      } 
    }
  );
};

doSuccess = function(request) {
  //alert(request.responseText);
  //new Insertion.Top($('maincontent'), request.responseText + 'Kuckuck');
}

reportComplete = function(request) {
}

reportError = function(request) {
  alert(request.responseText);
}

Date.prototype.getFullDays = function(m, y) {
  for(var x=28; x<=31; ++x) {
    if(new Date(y,m-1,x).getMonth() != new Date(y,m-1,1).getMonth()) {
      break;
    }
  }
  return x-1;
};


getRefDate = function() {
  var DateObj = new Date();
  var d = DateObj.getDate();
  var m = DateObj.getMonth() + 1;
  var y = DateObj.getFullYear();
  d = ((d < 10) ? '0' + d : d);
  m = ((m < 10) ? '0' + m : d);
  var RefDate = y + '-' + m + '-' + d;
  return RefDate;
}

createDiv = function(id, pos, size, classname, content) {
  var div = document.createElement('div');
  div.id = id;
  div.className = classname;
  div.style.top = pos[0] + 'px';
  div.style.left = pos[1] + 'px';
  div.style.width = size[0] + 'px';
  div.style.height = size[1] + 'px';
  div.innerHTML = content;
  return div;
}

function newlanguage(lang) {
  if (!lang) {
    return;
  }
  if (lang) {
    if ((lang == 'es') || (lang == 'cn')) {
//      lang = 'en';
//      alert('Sorry!\nThis Language is not complete translated yet ...');
    }
    setCookie('lang', lang, 365, '/');
    location.reload();
  }
}

function langselect(sbox) {
  var lang = sbox.value;
  if (lang) {
    setCookie('lang', lang, 365, '/');
    location.reload();
  }
}

function getCookie(name) {
  var c = new Object();
  var i = 0;
  var clen = document.cookie.length;
  while (i < clen) {
    var endstr = document.cookie.indexOf (";", i);
    if (endstr == -1) {
      endstr = document.cookie.length;
    }
    var v = unescape(document.cookie.substring(i, endstr));
    var key = v.substring(0, v.indexOf("=", 0));
    var val = v.substring(v.indexOf("=") + 1);
    c[key] = val;
    i = endstr + 2; // Leerzeichen nach ; überspringen
  }
  if(name) {
    return c[name];
  }
  return c;
}

function setCookie(name, value, days, path) {
  if(!days) {
    days = -1;
  }
  var expire = new Date();
  expire.setTime(expire.getTime() + 86400000 * days);
  document.cookie = name + "=" + escape(value) +  "; expires=" + expire.toGMTString() + ";" + (path ? 'path=' + path : '');
}

/*
showLoader = function() {
  Element.addClassName($('usernamestatus'), 'statusloading');
//  Element.show($('usernameloader'));
}

hideLoader = function() {
  Element.removeClassName($('usernamestatus'), 'statusloading');
//  Element.hide($('usernameloader'));
}

Ajax.Responders.register({
 onCreate : showLoader,
 onComplete : hideLoader
});

function check_register() {
  var pars = "";
  pars += 'username=' + $('regusername').value;
  pars += '&password=' + $('regpassword').value;
  pars += '&password2=' + $('regpassword2').value;
  pars += '&email=' + $('regemail').value;
  new Ajax.Request("http://" + window.location.hostname + "/ajax/check_register.php", {
    onCreate : showLoader,
    onComplete : hideLoader,
    onSuccess : function(resp) {
//      $('debug').innerHTML = "<pre>The response from the server is: " + resp.responseText + "</pre>";
      if (resp.responseText == 'OK') {
        $('usernamestatus').innerHTML = 'available';
        Element.removeClassName($('usernamestatus'), 'statuserr');
        Element.addClassName($('usernamestatus'), 'statusok');
      } else {
        $('usernamestatus').innerHTML = 'not available';
        Element.removeClassName($('usernamestatus'), 'statusok');
        Element.addClassName($('usernamestatus'), 'statuserr');
      }
    },
    onFailure : function(resp) {
      alert("Oops, there's been an error." + resp.responseText);
    },
    parameters : pars
  });
}

*/

/* 

Example Javascript Animation Techniques by Hesido.com;
4 different, reusable examples

*/
if (document.getElementById && document.getElementsByTagName) {
  if (window.addEventListener) {
    window.addEventListener('load', initAnims, false);
  } else if (window.attachEvent) {
    window.attachEvent('onload', initAnims);
  }
}

function initAnims() {
  // Init fade animation without memory, single direction
//  var animElements = document.getElementById("fadercontainer").getElementsByTagName("p");
//  for(var i=0; i<animElements.length; i++) {
//    animElements[i].onmouseover = fadeBGCol;
//  }
  
  function fadeBGCol() {
    doBGFade(this,[255,100,20],[255,204,204],'rgb(255,204,204)',20,20,1);
  }

  // Init fade animation with memory, both directions
//  var animElements = document.getElementById("fadercontainermem").getElementsByTagName("p");
//  for(var i=0; i<animElements.length; i++) {
//    animElements[i].onmouseover = fadeBGColMem;
//    animElements[i].onmouseout = fadeBGColRestore;
//  }

  function fadeBGColMem() {
    if (!this.currentbgRGB) this.currentbgRGB = [255,204,204]; //if no mem is set, set it first;
    doBGFadeMem(this,this.currentbgRGB,[255,100,20],4,20,1);
  }

  function fadeBGColRestore() {
    if (!this.currentbgRGB) return;	//avoid error if mouseout an element occurs before the mosueover
    //(e.g. the pointer already in the object when onload)
    doBGFadeMem(this,this.currentbgRGB,[255,204,204],12,20,1);
  }

  // Init size animation with memory, both directions
//  var animElements = document.getElementById("resizercontainer").getElementsByTagName("p")
//  for(var i=0; i<animElements.length; i++) {
//    animElements[i].onmouseover = widthChange;
//    animElements[i].onmouseout = widthRestore;
//  }

  function widthChange() {
    if (!this.currentWidth) this.currentWidth = 150; //if no mem is set, set it first;
    doWidthChangeMem(this,this.currentWidth,170,10,10,0.333);
  }

  function widthRestore() {
    if (!this.currentWidth) return;	//avoid error if mouseout an element occurs before the mosueover
    //(e.g. the pointer already in the object when onload)
    doWidthChangeMem(this,this.currentWidth,150,10,10,0.5);
  }
	
  //	Init motion animation
  var moveIt = document.getElementById('moveit');
  if (moveIt != null) moveIt.onclick = moveToBottom;

  function moveToBottom() {
    if (!this.currentPos) this.currentPos = [15,15]; //if no mem is set, set it first;
    doPosChangeMem(this,this.currentPos,[Math.floor(Math.random()*230+15),Math.floor(Math.random()*145)+15],20,20,0.5);
    //move to a random position for demonstration
  }
}

//*******************

function doBGFade(elem,startRGB,endRGB,finalColor,steps,intervals,powr) {
//BG Fader by www.hesido.com
  if (elem.bgFadeInt) window.clearInterval(elem.bgFadeInt);
  var actStep = 0;
  elem.bgFadeInt = window.setInterval (
    function() {
      elem.style.backgroundColor = "rgb("+
        easeInOut(startRGB[0],endRGB[0],steps,actStep,powr)+","+
        easeInOut(startRGB[1],endRGB[1],steps,actStep,powr)+","+
        easeInOut(startRGB[2],endRGB[2],steps,actStep,powr)+")";
      actStep++;
      if (actStep > steps) {
        elem.style.backgroundColor = finalColor;
        window.clearInterval(elem.bgFadeInt);
      }
    },
    intervals)
}


//*******************

function doBGFadeMem(elem,startRGB,endRGB,steps,intervals,powr) {
//BG Fader with Memory by www.hesido.com
  if (elem.bgFadeMemInt) window.clearInterval(elem.bgFadeMemInt);
  var actStep = 0;
  elem.bgFadeMemInt = window.setInterval(
    function() {
      elem.currentbgRGB = [
        easeInOut(startRGB[0],endRGB[0],steps,actStep,powr),
        easeInOut(startRGB[1],endRGB[1],steps,actStep,powr),
        easeInOut(startRGB[2],endRGB[2],steps,actStep,powr)
      ];
      elem.style.backgroundColor = "rgb("+
        elem.currentbgRGB[0]+","+
        elem.currentbgRGB[1]+","+
        elem.currentbgRGB[2]+")";
      actStep++;
      if (actStep > steps) window.clearInterval(elem.bgFadeMemInt);
    },
    intervals)
}

//*******************

function doWidthChangeMem(elem,startWidth,endWidth,steps,intervals,powr) {
  //Width changer with Memory by www.hesido.com
  if (elem.widthChangeMemInt) window.clearInterval(elem.widthChangeMemInt);
  var actStep = 0;
  elem.widthChangeMemInt = window.setInterval(
    function() {
      elem.currentWidth = easeInOut(startWidth,endWidth,steps,actStep,powr);
      elem.style.width = elem.currentWidth+"px";
      actStep++;
      if (actStep > steps) window.clearInterval(elem.widthChangeMemInt);
    },
    intervals)
}

//*******************

function doPosChangeMem(elem,startPos,endPos,steps,intervals,powr) {
  //Position changer with Memory by www.hesido.com
  if (elem.posChangeMemInt) window.clearInterval(elem.posChangeMemInt);
  var actStep = 0;
  elem.posChangeMemInt = window.setInterval(
    function() {
      elem.currentPos = [
        easeInOut(startPos[0],endPos[0],steps,actStep,powr),
        easeInOut(startPos[1],endPos[1],steps,actStep,powr)
      ];
      elem.style.left = elem.currentPos[0]+"px";
      elem.style.top = elem.currentPos[1]+"px";
      actStep++;
      if (actStep > steps) window.clearInterval(elem.posChangeMemInt);
    },
    intervals)
}

//*******************

function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) {
  //Generic Animation Step Value Generator By www.hesido.com
  var delta = maxValue - minValue;
  var stepp = minValue+(Math.pow(((1 / totalSteps)*actualStep),powr)*delta);
  return Math.ceil(stepp)
}


function Size(elem, startWidth, endWidth, steps, intervals, powr) { 
  if (elem.widthChangeMemInt) {
	window.clearInterval(elem.widthChangeMemInt);
  }
  var actStep = 0;
  elem.widthChangeMemInt = window.setInterval (
    function() { 
      elem.currentWidth = easeInOut(startWidth,endWidth,steps,actStep,powr);
      elem.style.width = elem.currentWidth + "px";
      actStep++;
      if (actStep > steps) {
        window.clearInterval(elem.widthChangeMemInt);
      }
	},
    intervals)
}

function Size2(elem, elem2, startWidth, endWidth, steps, intervals, powr) { 
  if (elem.widthChangeMemInt) {
	window.clearInterval(elem.widthChangeMemInt);
  }
  var actStep = 0;
  elem.widthChangeMemInt = window.setInterval (
    function() { 
      elem.currentWidth = easeInOut(startWidth,endWidth,steps,actStep,powr);
      elem.style.width = elem.currentWidth + "px";
      elem2.style.marginLeft = elem.currentWidth + 4 +"px";
      actStep++;
      if (actStep > steps) {
        window.clearInterval(elem.widthChangeMemInt);
      }
	},
    intervals)
}

rand = function(n) {
  return (Math.floor(Math.random() * n + 1));
}

function fillSocials() {
  var links = $('bookmarks').getElementsByTagName('a');
  var url = encodeURIComponent(window.location.href);
  if (!url) url = "";
  var title = encodeURIComponent(document.title);
  if (!title) title = "";
  var description = encodeURIComponent(document.description);
  if (!description) description = "";
  for (var i=0; i<links.length; i++) {
    var link = links[i].href;
    link = link.replace(/PERMALINK/g, url);
    link = link.replace(/TITLE/g, title);
    link = link.replace(/DESCRIPTION/g, description);
    link = link.replace(/undefined/g, '');
    links[i].href = link;
  }
}

function mib_mouseover(el) {
  el.className = 'mashitembgover';
}

function mib_mouseout(el) {
  el.className = 'mashitembg';
}

function mif_mouseover(el) {
  el.className = 'mashitemfgover';
}

function mif_mouseout(el) {
  el.className = 'mashitemfg';
}

Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
	for(i = 1; i < this.length; i++){
		if(this[i][0] == this[i-1][0]){
			this.splice(i,1);
		}
	}
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){
	}
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

parsexml = function(xml) {
  var xmldoc = Try.these(
    function() {
      return new DOMParser().parseFromString(xml, 'text/xml');
    },
    function() {
      var xmldom = new ActiveXObject('Microsoft.XMLDOM');
      xmldom.loadXML(xml);
      return xmldom;
    }
  );
  return xmldoc;
}

loadViewport = function() {
  if (!$('rspacer')) {
    setTimeout("loadViewport()", 100);
  } else {
    Loader2('scripts/viewport.js', null);
  }
}


loadLightbox = function() {
  Try.these(
    function() {
      initLightbox();
    }
  );
}

Event.observe(window, 'load', loadLightbox, false);
Event.observe(window, 'load', loadViewport, false);
//loadViewport();


