// Protect original alert function.
// Not in robin.alert.js due to internet explorer incomptibility.
// Most likely due to IE-js variable scope being a bit different than
// the standard compliant browsers'. Functions defined later in the flow can't 
// be seen by earlier defined functions. More like C than PHP.
// Perhaps a JIT-thing?

var jsalert = window.alert;

function logi() { }

// load something trough ajax and evaluate all <script> tags
function ajaxload(url)
{
	var check = true;
	if(url.match('delete')) { check = ajaxconfirm(url, 'html'); }
	if(check)
	{
		return $.ajax
		(
			{
				url: url+"&ajax&html",
				async: false,
				dataType: "html",
				error: function(request, msg) { alert('ajaxload '+msg+': '+entities(request.responseText)); }
			}
		).responseText;
	}
}

// ajax debug :)
function debug(url) { alert( entities(ajaxload(url)) ); }

// get ajax url and evaluate callback trough javascript
function ajaxget(url)
{
	var check = true;
	if(url.match('delete')) { check = ajaxconfirm(url, 'script'); }
	if(check)
	{
		$.ajax
		(
			{
				type: "GET",
				url: url+'&ajax',
				dataType: "script",
				async: false,
				error: function(request, msg) { alert('ajaxget '+msg+': '+entities(request.responseText)); }
				//success: function(request) { eval(request.responseText); }
				//success: function(request) { }
			}
		);
	}
	return false;
}

// post ajax url and evaluate callback trough javascript
function ajaxpost(url, params)
{
	var check = true;
	if(url.match('delete')) { check = ajaxconfirm(url); }
	if(check)
	{
		if( url.charAt(url.length-1) == '/' )
		{
			url += '?ajax';
		}
		else
		{
			url += '&ajax';
		}
		$.ajax
		(
			{
				type: "POST",
				url: url,
				data: params,
				dataType: "script",
				async: false,
				error: function(request, msg) { alert('ajaxpost '+msg+': '+entities(request.responseText)); }
//				success: function(request) { eval(request.responseText); }
			}
		);
	}
	
	return false;
}

// these 2 functions are triggered if url contains word 'delete'
function ajaxconfirm(url, type)
{
	alert( ajaxnoconfirm('./?ajax&act=deleteConfirm&url='+escape(url)+'&type='+type) );
	return false;
}

// please don't use this on your scripts.... ?
function ajaxnoconfirm(url, type)
{
	return $.ajax
	(
		{
			url: url+"&"+type+'&ajax',
			async: false,
			dataType: type,
			error: function(request, msg) { alert('ajaxnoconfirm '+msg+': '+entities(request.responseText)); }
		}
	).responseText;
}

/*// update wanted field with data loaded from url
jQuery.load = function(url) {
	update(this, url);
};
//update wanted field with data loaded from url
$.load = function(url) {
	update(this, url);
};*/

//update wanted field with data loaded from url
function update(target, url)
{
	$(target).load(url+"&html");
	//setTimeout("updateCached(target, url);", 1);
	//return false;
}

function updateDirect(target, url)
{
	$(target).html($.ajax
	(
		{
			type: "GET",
			url: url+'&ajax',
			dataType: "html",
			async: false,
			error: function(request, msg) { alert('ajaxget '+msg+': '+entities(request.responseText)); }
			//success: function(request) { eval(request.responseText); }
			//success: function(request) { }
		}
	).responseText);
}

// getElementsById
function getElementsById(id)
{
	var merirosvo = new Array();
	var tuuba;
	var i;	
	while((tuuba = document.getElementById(id))!=null)
	{
		merirosvo.push(tuuba);
		tuuba.id = 'humppamaakarin kenka';
	}	
	var len;
	len = merirosvo.length;
	for(i=0; i<len; i++) { merirosvo[i].id = id; }
	return merirosvo;
}

// minimize/maximize/etc
function toggle(id) { $(id).toggle(); }
function toggleAll(id)
{
	ids = document.getElementsByName(id);
	for(i=0; i<ids.length; i++)
	{
		if(ids[i].style.display == 'none')
		{
			ids[i].style.display = '';
		}
		else
		{
			ids[i].style.display = 'none';
		}
	}
}
function toggleSlide(id) { $(id).slideToggle('fast'); }

// get filename from filepath
function stripFilename(s)
{
	s = s.split('\\');
	s = s[s.length - 1];
	return s;
}

// double digits
function dd(n) { if(n < 10) { return "0" + n; } else { return n; } }

// timestamp
function getTimestamp()
{
	time = new Date();
	date = dd(time.getDate()) + '.' + dd(time.getMonth()) + '.' + time.getFullYear();
	clock = dd(time.getHours()) + ':' + dd(time.getMinutes()) + ':' + dd(time.getSeconds());
	return  date + ' ' + clock;
}

// gotourl
// Goto oli rekister�ity keywordi operassa ja muissa selaimissa jotka k�ytt�v�t jotain tietty� javascriptin
// revisiota.
function gotourl(url) { document.location.href = url; return false; }

// reload
function reload() { window.location.reload(); }

// obj position
function rect(item)
{
	var tuut;

	tuut = new Object();

	tuut.x = tuut.top = 0;
	tuut.y = tuut.left = 0;
	tuut.bottom = 0;
	tuut.right = 0;
	
	var parent = item.offsetParent;
	
	tuut.top += Math.floor(item.offsetTop);
	tuut.left += Math.floor(item.offsetLeft);

	while (parent) 
	{
		
		tuut.top += Math.floor(parent.offsetTop);
		tuut.left += Math.floor(parent.offsetLeft);
		
		parent = parent.offsetParent;
	}

	tuut.x = tuut.top;
	tuut.y = tuut.top;
	tuut.wb = tuut.width = item.offsetWidth;
	tuut.hb = tuut.height = item.offsetHeight;

	tuut.right = tuut.left + Math.floor(item.offsetWidth);
	tuut.bottom = tuut.top + Math.floor(item.offsetHeight);
	tuut.parent = item;

	return tuut;
}

// focus first form element of first form
/*function focusForm()
{
	if
	(
	 	document.forms &&
		document.forms.length &&
		document.forms[0].elements[0] &&
		document.forms[0].elements[0].type != null
	)
	{
		document.forms[0].elements[0].focus();
	}
}*/

// encode html
function encodeHtml(str)
{
	str = escape(str);
	str = str.replace(/\//g,"%2F");
	str = str.replace(/\?/g,"%3F");
	str = str.replace(/=/g,"%3D");
	str = str.replace(/&/g,"%26");
	str = str.replace(/@/g,"%40");
	return str;
}

// format html to readable text
function entities( inText )
{
	outText = ReplaceAll( inText, "&", "&amp;" );
	outText = ReplaceAll( outText, "<", "&lt;" );
	outText = ReplaceAll( outText, ">", "&gt;" );
	return ( outText );
}

// validate input url
function formatURL(target, text)
{
	target = document.getElementById(target);
	target.value = text.replace(/[^a-zA-Z0-9-_./]/g, '').toLowerCase();
}

//validate input username
function formatUsername(target, text)
{
	target = document.getElementById(target);
	target.value = text.replace(/[^a-zA-Z0-9-_.@/]/g, '').toLowerCase();
}

// Find and replace a string in another string, with optional case-sensitivity.
// inText is the text in which to do the search;
// inFindStr is the string to find;
// inReplStr is the string to substitute into inText in place of inFindStr; and
// inCaseSensitive is a boolean value (defaults to false).
function ReplaceAll( inText, inFindStr, inReplStr, inCaseSensitive )
{
	var searchFrom = 0;
	var offset = 0;
	var outText = "";
	var searchText = "";
	if ( inCaseSensitive == null ) { inCaseSensitive = false; }
	if ( inCaseSensitive )
	{
		searchText = inText.toLowerCase();
		inFindStr = inFindStr.toLowerCase();
	}
	else
	{
		searchText = inText;
	}
	offset = searchText.indexOf( inFindStr, searchFrom );
	while ( offset != -1 )
	{
		outText += inText.substring( searchFrom, offset );
		outText += inReplStr;
		searchFrom = offset + inFindStr.length;
		offset = searchText.indexOf( inFindStr, searchFrom );
	}
	outText += inText.substring( searchFrom, inText.length );
	return ( outText );
}

// center something
    (function($){
      $.fn.positionCenter = function(options) {
        var pos = {
          sTop : function() {
            return window.pageYOffset || document.documentElement && document.documentElement.scrollTop ||	document.body.scrollTop;
          },
          wHeight : function() {
            return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
          }
        };
        return this.each(function(index) {
          if (index == 0) {
            var $this = $(this);
            var elHeight = $this.outerHeight();
            var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
            $this.css({
              position: 'absolute',
              margin: '0',
              top: elTop,
              left: (($(window).width() - $this.outerWidth()) / 2) + 'px'
            });
          }
        });
      };
    })(jQuery);

// vertically center something in the viewport
( function($)
{
	$.fn.vCenter = function(options) {
		var pos = {
			sTop : function() {
				return window.pageYOffset || $.boxModel && document.documentElement.scrollTop || document.body.scrollTop;
			},
			wHeight : function() {
				/* removed: $.browser.opera || - for opera fix */
				if ( $.browser.safari ) {
					return window.innerHeight;
/*				} else if ( ($.browser.safari && parseInt ($.browser.version) > 520) ) {
					return window.innerHeight - (($(document).height() > window.innerHeight) ? getScrollbarWidth() : 0);*/
				} else {
					return $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
				}
			}
		};
		return this.each(function(index) {
			if (index == 0) {
				var $this = $(this);
				var elHeight = $this.height();
				$this.css({
					position: 'absolute',
					marginTop: '0',
					top: pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2)
				});
			}
		});
	};
})(jQuery);

function isset(variable_name)
{
	try
	{
		if (typeof(eval(variable_name)) != undefined)
		if (eval(variable_name) != null)
		return true;
	} catch(e) { }
	return false;
}

var newwindow;
function popup(url)
{
	var width = screen.width * 0.60;
	var height = screen.height * 0.60;
	newwindow = window.open(url,'name','width='+width+',height='+height+',resizable=yes,scrollbars=yes,status=yes');
	if (window.focus) { newwindow.focus(); }
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode( plaintext )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +			// Numeric
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
			"abcdefghijklmnopqrstuvwxyz" +
			"-_.!~*'()";			// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";			// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

function deleteElement( name )
{
	var cell = document.getElementById(name);
	if ( cell & cell.hasChildNodes() )
	{
	    while ( cell.childNodes.length >= 1 )
	    {
		cell.removeChild( cell.firstChild );       
	    } 
	}
}

/*jQuery.fn.swap = function(b) {
    b = jQuery(b)[0];
    var a = this[0];

    var t = a.parentNode.insertBefore(document.createTextNode(''), a);
    b.parentNode.insertBefore(a, b);
    t.parentNode.insertBefore(b, t);
    t.parentNode.removeChild(t);

    return this;
};*/

jQuery.fn.swap = function(b) {
    b = jQuery(b)[0];
    var a = this[0],
        a2 = a.cloneNode(true),
        b2 = b.cloneNode(true),
        stack = this;

    a.parentNode.replaceChild(b2, a);
    b.parentNode.replaceChild(a2, b);

    stack[0] = a2;
    return this.pushStack( stack );
};

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
  {
    return "";
  }
  else
  {
    return results[1];
  }
}
