var pageHistory = new Array();

function loadPosition(url,position){
    new Ajax.Request(url + '&position=' + position, {
            method: "get",
            //parameters: { relt: ms},
            onSuccess: function(a) {
			   	if(position=='mainbody'){
            		pageHistory.push($(position).innerHTML);
            	}
            	updatePosition(position, a.responseText);
            }
    });
}

function updatePosition(position, htmlCode){
	$(position).innerHTML = htmlCode;
}

function goBack(){
	if(pageHistory.length){
		updatePosition('mainbody', pageHistory.pop());
	}else{
		history.go(-1);
	}
}

//Function printf(format_string,arguments...)
function printf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }    
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg); 
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg)); 
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg); 
      }
    converters['E'] = function(flags,width,precision,arg) 
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);        
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);        
      }  
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }
//Function printf() END

function showOverlayPic(imgLink,imgTitle){
	if(typeof lightwindow=='undefined')
		alert('Overlay window library not working');
	if(typeof overWindow=='undefined')
		overWindow = new lightwindow();
	overWindow.activateWindow({
		href: imgLink, 
		title: imgTitle, 
		author: '', 
		caption: '' 
	});
}

function preventAutocomplete() {
	var forms = document.getElementsByTagName( 'form' );
	if ( !forms || forms.length == 0 ) return;
	
	for ( var i = 0; i < forms.length; i++ ) {
		var iform = forms[ i ];
		iform.setAttribute( 'autocomplete', 'off' );
	}	
}

Event.observe( window, 'load', preventAutocomplete );

function checkClass( theclass ) {
	if ( typeof( eval( theclass ) ) == 'undefined' ) {
		window.alert( theClass + ' not loaded yet' );
		return false;
	}
	return true;
}

function loadcheck( theclass, property ) {
	if ( !eval( theclass + '.' + property ) ) {
		window.alert( theclass + ' not loaded yet' );
	}
}

function loading(){
	$(document.body).startWaiting('bigWaiting');
}

function loaded(){
	$(document.body).stopWaiting();
}
/* protoload 0.1 beta by Andreas Kalsch
 * last change: 09.07.2007
 *
 * This simple piece of code automates the creating of Ajax loading symbols.
 * The loading symbol covers an HTML element with correct position and size - example:
 * $('myElement').startWaiting() and $('myElement').stopWaiting()
 */
 
Protoload = {
	// the script to wait this amount of msecs until it shows the loading element
	timeUntilShow: 250,
	
	// opacity of loading element
	opacity: 0.8,

	// Start waiting status - show loading element
	startWaiting: function(element, className, timeUntilShow) {
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (className == undefined)
			className = 'waiting';
		if (timeUntilShow == undefined)
			timeUntilShow = Protoload.timeUntilShow;
		
		element._waiting = true;
		if (!element._loading) {
			var e = new Element('div');
			var theparent = (element.offsetParent || document.body);
			theparent.appendChild(element._loading = e);
			if ( theparent != document.body ) e.style.position = 'absolute';
			else {
				e.setStyle( { position: 'fixed', width: '100%', height: '100%', top: '0px', left: '0px' } );
			}
			try {e.style.opacity = Protoload.opacity;} catch(e) {}
			try {e.style.MozOpacity = Protoload.opacity;} catch(e) {}
			try {e.style.filter = 'alpha(opacity='+Math.round(Protoload.opacity * 100)+')';} catch(e) {}
			try {e.style.KhtmlOpacity = Protoload.opacity;} catch(e) {}
			
			e.style.zIndex = Protoload._zIndex;
			
			/*var zIndex = 0;
			if (window.UI)
				if (UI.zIndex)
					zIndex = ++UI.zIndex;
			if (!zIndex)
				zIndex = ++Protoload._zIndex;
			e.style.zIndex = zIndex;*/
		}
		element._loading.className = className;
		window.setTimeout((function() {
			if (this._waiting) {
				var left = this.offsetLeft, 
					top = this.offsetTop,
					width = this.offsetWidth,
					height = this.offsetHeight,
					l = this._loading;
					
				l.style.left = left+'px';
				l.style.top = top+'px';
				l.style.width = width+'px';
				l.style.height = height+'px';
				l.style.display = 'inline';
			}
		}).bind(element), timeUntilShow);
	},
	
	// Stop waiting status - hide loading element
	stopWaiting: function(element) {
		if (element._waiting) {
			element._waiting = false;
			element._loading.parentNode.removeChild(element._loading);
			element._loading = null;
		}
	},
	
	_zIndex: 1000000
};

if (Prototype) {
	Element.addMethods(Protoload);
	Object.extend(Element, Protoload);
}
/* */

// protoHover
// a simple hover implementation for prototype.js
// Sasha Sklar and David Still

(function() {
	// copied from jquery
	var withinElement = function(evt, el) {
		// Check if mouse(over|out) are still within the same parent element
		var parent = evt.relatedTarget;

		// Traverse up the tree
		while (parent && parent != el) {
			try {
				parent = parent.parentNode;
			} catch (error) {
				parent = el;
			}
		}
		// Return true if we actually just moused on to a sub-element
		return parent == el;
	};

	// Extend event with mouseEnter and mouseLeave
	Object.extend(Event, {
		mouseEnter: function(element, f, options) {
			element = $(element);

			// curry the delay into f
			var fc = (options && options.enterDelay)?(function(){window.setTimeout(f, options.enterDelay);}):(f);

			if (Prototype.Browser.IE) {
				element.observe('mouseenter', fc);
			} else {
				element.hovered = false;

				element.observe('mouseover', function(evt) {
					// conditions to fire the mouseover
					// mouseover is simple, the only change to default behavior is we don't want hover fireing multiple times on one element
					if (!element.hovered) {
						// set hovered to true
						element.hovered = true;

						// fire the mouseover function
						fc(evt);
					}
				});
			}
		},
		mouseLeave: function(element, f, options) {
			element = $(element);

			// curry the delay into f
			var fc = (options && options.leaveDelay)?(function(){window.setTimeout(f, options.leaveDelay);}):(f);

			if (Prototype.Browser.IE) {
				element.observe('mouseleave', fc);
			} else {
				element.observe('mouseout', function(evt) {
					// get the element that fired the event
					// use the old syntax to maintain compatibility w/ prototype 1.5x
					var target = Event.element(evt);

					// conditions to fire the mouseout
					// if we leave the element we're observing
					if (!withinElement(evt, element)) {
						// fire the mouseover function
						fc(evt);

						// set hovered to false
						element.hovered = false;
					}
				});
			}
		}
	});


	// add method to Prototype extended element
	Element.addMethods({
		'hover': function(element, mouseEnterFunc, mouseLeaveFunc, options) {
			options = Object.extend({}, options) || {};
			Event.mouseEnter(element, mouseEnterFunc, options);
			Event.mouseLeave(element, mouseLeaveFunc, options);
		}
	});
})();

 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

String.prototype.trim = function( chars ) {
	return ltrim( rtrim( this, chars ), chars );
};
