/**
 * $Id: functions.js 168 2010-06-27 15:33:07Z Jose Roberto A $
**/
function sprintf(){
    if (!arguments || arguments.length < 1 || !RegExp) {
        return;
    }
    var str = arguments[0];
    var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
    var a = b = [], numSubstitutions = 0, numMatches = 0;
    while (a = re.exec(str)) {
        var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
        var pPrecision = a[5], pType = a[6], rightPart = a[7];
        numMatches++;
        if (pType == '%') {
            subst = '%';
        }
        else {
            numSubstitutions++;
            if (numSubstitutions >= arguments.length) {
                alert('Error! Not enough function arguments (' +
                (arguments.length - 1) +
                ', excluding the string)\n' +
                'for the number of substitution parameters in string (' +
                numSubstitutions +
                ' so far).');
            }
            var param = arguments[numSubstitutions];
            var pad = '';
            if (pPad && pPad.substr(0, 1) == "'") {
                pad = leftpart.substr(1, 1);
            }
            else 
                if (pPad) {
                    pad = pPad;
                }
            var justifyRight = true;
            if (pJustify && pJustify === "-") 
                justifyRight = false;
            var minLength = -1;
            if (pMinLength) 
                minLength = parseInt(pMinLength);
            var precision = -1;
            if (pPrecision && pType == 'f') {
                precision = parseInt(pPrecision.substring(1));
            }
            var subst = param;
            switch (pType) {
                case 'b':
                    subst = parseInt(param).toString(2);
                    break;
                case 'c':
                    subst = String.fromCharCode(parseInt(param));
                    break;
                case 'd':
                    subst = parseInt(param) ? parseInt(param) : 0;
                    break;
                case 'u':
                    subst = Math.abs(param);
                    break;
                case 'f':
                    subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) /
                    Math.pow(10, precision) : parseFloat(param);
                    break;
                case 'o':
                    subst = parseInt(param).toString(8);
                    break;
                case 's':
                    subst = param;
                    break;
                case 'x':
                    subst = ('' +
                    parseInt(param).toString(16)).toLowerCase();
                    break;
                case 'X':
                    subst = ('' +
                    parseInt(param).toString(16)).toUpperCase();
                    break;
            }
            var padLeft = minLength - subst.toString().length;
            if (padLeft > 0) {
                var arrTmp = new Array(padLeft + 1);
                var padding = arrTmp.join(pad ? pad : " ");
            }
            else {
                var padding = "";
            }
        }
        str = leftpart + padding + subst + rightPart;
    }
    return str;
}

/**
 * @deprecated Não compativel com documentação
 */
function fazerBusca(){
	function get(id){
		return document.getElementById(id);
	}
	function googlecustom(){
		get('s').name='q';
		get('searchform').action="http://www.google.com.br/custom";
	}
	get('hds').name='';
	get('hds').value='';
	var usegoogle=get('usegoogle').checked;
	if(get('ss2').checked||get('ss3').checked){
		if (!usegoogle) {
			get('s').name = 's';
			
			if (get('ss2').checked) {
				get('searchform').action = "/dicas";
			}
			else {
				get('searchform').action = "/noticias";
			}
		}
		else {
			googlecustom();
			get('s').name='';
			get('hds').name='q';
			if (get('ss2').checked) {
				get('hds').value = 'inurl:dicas ' + get('s').value;
			}
			else {
				get('hds').value = 'inurl:noticias ' + get('s').value;
			}
		}
	}
	else if(get('ss4').checked){
		if (!usegoogle) {
			get('s').name = 'keywords';
			get('searchform').action = "/forum/search.php";
		}
		else {
			googlecustom();
			get('s').name='';
			get('hds').name='q';
			get('hds').value='inurl:forum '+ get('s').value;
		}
	}
	else{
		googlecustom();
	}
}

function time(){
	var date=new Date();
	return date.getTime();
}

function modal(message, title, html)
{
	if(title == null) title = 'Erro encontrado!';
	$('#modal').dialog('close');
	
	if(html == true)
	{
		$('#modal').html(message);
	}
	else
	{
		$('#modal').text(message);
	}
	
	$('#modal')
		.dialog('option', 'title', title)
		.dialog('open')
}

function validate_comment_form(id)
{
	try{
		var form = $('#'+id);
		$('#modal').dialog('close')
		
		if(form.find('input[name=email]').length)
		{
			if(form.find('input[name=email]').val().length == 0)
			{
				modal(too_short_email);
				return false;
			}
		}
		
		if(form.find('input[type=radio][name=type]').length > 0)
		{
			if(!form.find('input[type=radio][name=type][value=comment]').is(':checked')
				&& !form.find('input[type=radio][name=type][value=question]').is(':checked')
			)
			{
				modal(select_comment_type);
				return false;
			}
		}
		
		if(form.find('textarea[name=message]').val().length == 0)
		{
			modal(too_few_chars);
			return false;
		}
	}
	catch(e){alert("Exception: "+e);}
}

function window_size()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  return {width: myWidth, height: myHeight};
}

function popup(url, width, height, name)
{
	if (!name)
	{
		name = '_popup';
	}

	window.open(url.replace(/&amp;/g, '&'), name, 'height=' + height + ',resizable=yes,scrollbars=yes,width=' + width);
	return false;
}

function jumpto()
{
	var page = prompt('{LA_JUMP_PAGE}:', '{ON_PAGE}');
	var perpage = '{PER_PAGE}';
	var base_url = '{A_BASE_URL}';

	if (page !== null && !isNaN(page) && page > 0)
	{
		document.location.href = base_url.replace(/&amp;/g, '&') + '&start=' + ((page - 1) * perpage);
	}
}

/**
* Find a member
*/
function find_username(url)
{
	popup(url, 870, 570, '_usersearch');
	return false;
}

/**
* Mark/unmark checklist
* id = ID of parent container, name = name prefix, state = state [true/false]
*/
function marklist(id, name, state)
{
	var parent = document.getElementById(id);
	if (!parent)
	{
		eval('parent = document.' + id);
	}

	if (!parent)
	{
		return;
	}

	var rb = parent.getElementsByTagName('input');
	
	for (var r = 0; r < rb.length; r++)
	{
		if (rb[r].name.substr(0, name.length) == name)
		{
			rb[r].checked = state;
		}
	}
}

function selectCode(a)
{
   // Get ID of code block
   var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];

   // Not IE
   if (window.getSelection)
   {
      var s = window.getSelection();
      // Safari
      if (s.setBaseAndExtent)
      {
         s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
      }
      // Firefox and Opera
      else
      {
         var r = document.createRange();
         r.selectNodeContents(e);
         s.removeAllRanges();
         s.addRange(r);
      }
   }
   // Some older browsers
   else if (document.getSelection)
   {
      var s = document.getSelection();
      var r = document.createRange();
      r.selectNodeContents(e);
      s.removeAllRanges();
      s.addRange(r);
   }
   // IE
   else if (document.selection)
   {
      var r = document.body.createTextRange();
      r.moveToElementText(e);
      r.select();
   }
}