function setDisplayById(id, mode){
	document.getElementById(id).style.display = mode;
}

function popUp(url, target, width, height) {
    var conf = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width="+width+", height="+height;
    window.open(url,target,conf);
}

function isInt(input){
	return ((!isNaN(input)&&parseInt(input)==input) || is_float(input));
}

function is_float( mixed_var ) {
	return(!isNaN(parseFloat(mixed_var * 1)));
}

function checkTime(i) {
	if (i<10) i="0" + i;
	return i;
}

function trim(str, charlist) {
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function copyValidChars(input1, input2) {
	var regex = /[^\w\s]+/g;
	// First input value
	var value = $('#'+input1).val();
	value = value.toLowerCase();
	// Check characters
	value = value.replace(regex, '');
	value = value.replace(/ /g, '-');
	// Append value to second input
	$('#'+input2).val(value);
}

function restrictCharacters(e) {
	restrictionType = /[^\w\s]+| /g;
	if (!e) var e = window.event
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);

	// if they pressed esc... remove focus from field...
	if (code==27) { this.blur(); return false; }

	// ignore if they are press other keys
	// strange because code: 39 is the down key AND ' key...
	// and DEL also equals .
	if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
		if (character.match(restrictionType) && character != '-') {
			return false;
		} else {
			return true;
		}

	}
}

function vote(idPoll){
	// Validate not empty vote
	if ($("#pollVote_"+idPoll+' input:checked').length > 0){
		// Ajax request
		var sendData = $("#pollVote_"+idPoll).serializeArray();
		$.ajax({
			// Configuration
			type       : "POST",
			url        : voteUrl,
			data       : sendData,
			cache      : false,
			dataType   : 'text',
			// Before sending request
			beforeSend : function(){
				$('#poll_loader_'+idPoll).show();
			},
			// Successful
			success   : function(response) {
				$('#poll_loader_'+idPoll).hide();
				if (response['msg'] != undefined) alert(response['msg']);
				$('#poll_'+idPoll).html(response);
			}
		});
		return false; // Return false so as not to send form
	} else {
		alert(EmptyVoteMsg);
		return false;
	}
}

function toggleFeatures() {
	$('#features_container').toggle('blind');
}

function defaultValueFields(){
	$('input[defVal]').each(function(){
		if($(this).val() == '')
                	$(this).val($(this).attr('defVal'));
		$(this).bind('focus', function(){
			if($(this).val() == $(this).attr('defVal')) $(this).val('');
		});
		$(this).bind('blur', function(){
			if($(this).val() == '') $(this).val($(this).attr('defVal'));
		})
	});
}

// To be laoded on load :P
$(document).ready(function() {
	defaultValueFields();
});

var MAX_DUMP_DEPTH = 10;

function dumpObj(obj, name, indent, depth) {
	  if (depth > MAX_DUMP_DEPTH) {
			 return indent + name + ": <Maximum Depth Reached>\n";
	  }
	  if (typeof obj == "object") {
			 var child = null;
			 var output = indent + name + "\n";
			 indent += "\t";
			 for (var item in obj)
			 {
				   try {
						  child = obj[item];
				   } catch (e) {
						child = "<Unable to Evaluate>";
				  }
				  if (typeof child == "object") {
						  output += dumpObj(child, item, indent, depth + 1);
				   } else {
						  output += indent + item + ": " + child + "\n";
				   }
			 }
			 return output;
	  } else {
			 return obj;
	  }
}


/* 
This function can be used before every ajax request response on it's complete state when login is needed.
When calling userLoggedIn with onlyDie params, you will be able to force login evaluating the response text 
(wich is always the same when ajax login is called)
*/
function userLoggedIn(response) {
	if (is_object(response) || response.indexOf('loginError') > -1) {
	// Convert to Json if not
		if (!is_object(response)) {
			var aux = response;
			var response;
			eval('response ='+aux+';');
		}
		if (response['loginError'] != undefined) {
			if (response['redirectTo'] != undefined){
				document.location.href = response['redirectTo'];
			} else {
				document.location.href = '/';
			}
			return false;
		}
	}
	return true;
}

function sleep(naptime){
      naptime = naptime * 1000;
      var sleeping = true;
      var now = new Date();
      var alarm;
      var startingMSeconds = now.getTime();
      while(sleeping){
         alarm = new Date();
         alarmMSeconds = alarm.getTime();
         if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
      }      
 }

function array_search( needle, haystack, argStrict ) {
    // Searches the array for a given value and returns the corresponding key if successful  
    // 
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/array_search
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'});
    // *     returns 1: 'surname'

    var strict = !!argStrict;
    var key = '';

    for(key in haystack){
        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ){
            return key;
        }
    }

    return false;
}

function is_object( mixed_var ){
    // Returns true if variable is an object  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/is_object
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

function exit( status ) {
    // !No description available for exit. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/exit
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
    // +   improved by: Philip Peterson
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null
    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    this.window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];
    
    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        this.window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
    }

    if (this.window.stop) {
        this.window.stop();
    }
    
    throw '';
}


function die( status ) {
    // !No description available for die. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/die
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    //  -   depends on: exit
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: die();
    // *     returns 1: null
    return this.exit(status);
}


function googleSearch(){
	var str = $('#site_search').val();
	document.location.href='http://www.google.com/search?q='+str;
}

function showWaitingModal(){
	$('#waiting').jqm({
		overlay : 80,
		modal   : true
	}); 
	$('#waiting').jqmShow();
}