/**
 * 
 * JS-file for general functions required in the project.
 * 
 * @author Heikki Ylitalo <heikki.ylitalo@dimenteq.fi>
 */
var replaceObj = {
		"\"":	"____quot;"
		,"'":	"____apos;"
		,"&":	"____amp;"
		,"<":	"____lt;"
		,">":	"____gt;"
		,"¡":	"____iexcl;"
		,"¢": "____cent;"
		,"£": "____pound;"
		,"¤": "____curren;"
		,"¥": "____yen;"
		,"¦": "____brvbar;"
		,"§": "____sect;"
		,"¨": "____uml;"
		,"©": "____copy;"
		,"ª": "____ordf;"
		,"«": "____laquo;"
		,"¬": "____not;"
		,"­": "____shy;"
		,"®": "____reg;"
		,"¯": "____macr;"
		,"°": "____deg;"
		,"±": "____plusmn;"
		,"²": "____sup2;"
		,"³": "____sup3;"
		,"´": "____acute;"
		,"µ": "____micro;"
		,"¶": "____para;"
		,"·": "____middot;"
		,"¸": "____cedil;"
		,"¹": "____sup1;"
		,"º": "____ordm;"
		,"»": "____raquo;"
		,"¼": "____frac14;"
		,"½": "____frac12;"
		,"¾": "____frac34;"
		,"¿": "____iquest;"
		,"×": "____times;"
		,"÷": "____divide;"
		,"À": "____Agrave;"
		,"Á": "____Aacute;"
		,"Â": "____Acirc;"
		,"Ã": "____Atilde;"
		,"Ä": "____Auml;"
		,"Å": "____Aring;"
		,"Æ": "____AElig;"
		,"Ç": "____Ccedil;"
		,"È": "____Egrave;"
		,"É": "____Eacute;"
		,"Ê": "____Ecirc;"
		,"Ë": "____Euml;"
		,"Ì": "____Igrave;"
		,"Í": "____Iacute;"
		,"Î": "____Icirc;"
		,"Ï": "____Iuml;"
		,"Ð": "____ETH;"
		,"Ñ": "____Ntilde;"
		,"Ò": "____Ograve;"
		,"Ó": "____Oacute;"
		,"Ô": "____Ocirc;"
		,"Õ": "____Otilde;"
		,"Ö": "____Ouml;"
		,"Ø": "____Oslash;"
		,"Ù": "____Ugrave;"
		,"Ú": "____Uacute;"
		,"Û": "____Ucirc;"
		,"Ü": "____Uuml;"
		,"Ý": "____Yacute;"
		,"Þ": "____THORN;"
		,"ß": "____szlig;"
		,"à": "____agrave;"
		,"á": "____aacute;"
		,"â": "____acirc;"
		,"ã": "____atilde;"
		,"ä": "____auml;"
		,"å": "____aring;"
		,"æ": "____aelig;"
		,"ç": "____ccedil;"
		,"è": "____egrave;"
		,"é": "____eacute;"
		,"ê": "____ecirc;"
		,"ë": "____euml;"
		,"ì": "____igrave;"
		,"í": "____iacute;"
		,"î": "____icirc;"
		,"ï": "____iuml;"
		,"ð": "____eth;"
		,"ñ": "____ntilde;"
		,"ò": "____ograve;"
		,"ó": "____oacute;"
		,"ô": "____ocirc;"
		,"õ": "____otilde;"
		,"ö": "____ouml;"
		,"ø": "____oslash;"
		,"ù": "____ugrave;"
		,"ú": "____uacute;"
		,"û": "____ucirc;"
		,"ü": "____uuml;"
		,"ý": "____yacute;"
		,"þ": "____thorn;"
		,"ÿ": "____yuml;"
	};

function prettyWord(param) {
	param = param.replace(/_/g, " ");
	param = param.replace(/%20/g, " ");
	param = param.replace(/%C3%B6/g, "ö");
	param = param.replace(/%C3%9C/g, "Ü");
	param = param.replace(/%C3%96/g, "Ö");
	param = param.replace(/%C3%A4/g, "ä");
	param = param.replace(/%C3%84/g, "Ä");
	param = param.replace(/%C3%A5/g, "å");
	param = param.replace(/%C3%85/g, "Å");
	param = param.replace(/%C3%BC/g, "ü");
	param = param.replace(/%C3%9C/g, "Ü");
	
	param = param.replace(/%c3%B6/g, "ö");
	param = param.replace(/%c3%96/g, "Ö");
	param = param.replace(/%c3%A4/g, "ä");
	param = param.replace(/%c3%84/g, "Ä");
	param = param.replace(/%c3%A5/g, "å");
	param = param.replace(/%c3%85/g, "Å");
	param = param.replace(/%c3%BC/g, "ü");
	param = param.replace(/%c3%9C/g, "Ü");
	
	param = param.replace(/%C3%b6/g, "ö");
	param = param.replace(/%C3%96/g, "Ö");
	param = param.replace(/%C3%a4/g, "ä");
	param = param.replace(/%C3%84/g, "Ä");
	param = param.replace(/%C3%a5/g, "å");
	param = param.replace(/%C3%85/g, "Å");
	param = param.replace(/%C3%bc/g, "ü");
	param = param.replace(/%C3%9C/g, "Ü");
	
	param = param.replace(/%c3%b6/g, "ö");
	param = param.replace(/%c3%96/g, "Ö");
	param = param.replace(/%c3%a4/g, "ä");
	param = param.replace(/%c3%84/g, "Ä");
	param = param.replace(/%c3%a5/g, "å");
	param = param.replace(/%c3%85/g, "Å");
	param = param.replace(/%c3%bc/g, "ü");
	param = param.replace(/%c3%9c/g, "Ü");
	return param;
}

function safeEncode(text) {
	$.each(replaceObj, function(key, value){
		var re = new RegExp(key, 'g');
		text = text.replace(re, value);
	});
	return text;
}

$.fn.jqwait = function(time, type) {
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            $(self).dequeue();
        }, time);
    });
};

function wait(msecs)
{
	var start = new Date().getTime();
	var cur = start;
	while(cur - start < msecs)
	{
		cur = new Date().getTime();
	}	
} 

function clearText(field) {
	if( field.value == field.defaultValue ) {
		field.value = '';
		$(field).css({"color": "black"});
	}
}

function defaultText(field) {
	if( field.value == '' ) {
		field.value = field.defaultValue;
		$(field).css({"color": "#888888"});
	}
}

function objectKeys(obj) {
    var keys = [];
    for(var key in obj) {
        keys.push(key);
    }
    return keys;
}

Array.prototype.swap=function(a, b) {
	var tmp=this[a];
	this[a]=this[b];
	this[b]=tmp;
};

function partition(array, begin, end, pivot) {
	var piv=array[pivot];
	array.swap(pivot, end-1);
	var store=begin;
	var ix;
	for(ix=begin; ix<end-1; ++ix) {
		if(array[ix]<=piv) {
			array.swap(store, ix);
			++store;
		}
	}
	array.swap(end-1, store);
	return store;
}

function qsort(array, begin, end) {
	if(end-1>begin) {
		var pivot=begin+Math.floor(Math.random()*(end-begin));
		pivot=partition(array, begin, end, pivot);
		qsort(array, begin, pivot);
		qsort(array, pivot+1, end);
	}
}

function quickSort(array) {
	qsort(array, 0, array.length);
}

function object2String(obj) {
    var val, output = "";
    if (obj) {    
        output += "{";
        for (var i in obj) {
            val = obj[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += i + ":" + array2String(val) + ",";
                    } else {
                        output += i + ":" + object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += i + ":'" + escape(val) + "',";
                    break;
                default:
                    output += i + ":" + val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "}";
    }
    return output;
}

function array2String(array) {
    var output = "";
    if (array) {
        output += "[";
        for (var i in array) {
            val = array[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += array2String(val) + ",";
                    } else {
                        output += object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += "'" + escape(val) + "',";
                    break;
                default:
                    output += val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "]";
    }
    return output;
}


function string2Object(string) {
    eval("var result = " + string);
    return result;
}

function string2Array(string) {
    eval("var result = " + string);
    return result;
}

function empty(mixed_var) {
    // !No description available for empty. @php.js developers: Please update the function summary text file.
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/empty
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // +   input by: Stoyan Kyosev (http://www.svest.org/)
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    var key;
 
    if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
        return true;
    }
 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
 
    return false;
}
/**
 * jquery.timers
 * license: WTFPL
 */
jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});



function fb(attr) {
	console.log(attr);
}
