/**
 * Conta e mostra percentagem de caracteres num input
 */
function textCounter(field,counter,maxlimit,linecounter) {
    // text width//
    var fieldWidth =  parseInt(field.offsetWidth);
    var charcnt = field.value.length;        

    // trim the extra text
    if (charcnt > maxlimit) { 
        field.value = field.value.substring(0, maxlimit);
    } else { 
        // progress bar percentage
        var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
        document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";
        // document.getElementById(counter).innerHTML="Limite: "+percentage+"%"
        document.getElementById(counter).innerHTML=percentage+"%";
        // color correction on style from CCFFF -> CC0000
        setcolor(document.getElementById(counter),percentage,"background-color");
    }
}

function setcolor(obj,percentage,prop){
    obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";
}

/**
 * Abre nova janela
 */
function windowPopup(mypage,myname,w,h,scroll){
    var win= null;

    var winl = (screen.width-w)/2;
    var wint = (screen.height-h)/2;
    var settings  = 'height='+h+',';
    settings += 'width='+w+',';
    settings += 'top='+wint+',';
    settings += 'left='+winl+',';
    settings += 'scrollbars='+scroll+',';
    settings += 'resizable=yes';
    window.open(mypage,myname,settings);
}

/**
 * Submeter form
 */
function submitForm(formName) {
    document.getElementById(formName).submit();
}

/**
 * Submeter form com questao
 */
function questionSubmitForm(formName, question) {
    if (confirm(question)) {
        document.getElementById(formName).submit();
        return true;
    } else {
        return false;
    }
}

/**
 * Carrega a janela pai com um URL
 */
function loadInParent(url, closeSelf){
    self.opener.location = url;
    if (closeSelf) {
        self.close();
    }
}

/**
 * Verifica o tamanho
 */
function testLength(elementId, length, message) {
    var search = document.getElementById(elementId);
    if (search.value && search.value.length < length) {
        alert(message);
        return false;        
    }
    return true;
}

/**
 * Verifica se uma vari�vel � um array
 */
function isArray(a) {
    return (a && typeof a == 'object') && a.constructor == Array;
}

/**
 * Preenche uma combo box a partir de um array
*/
function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) {
    var i, j;
    var prompt;
    
    if ((itemArray == '0') || (itemArray == -1) || (itemArray == null)) {
        selectCtrl.disabled = true;
    } else {
        selectCtrl.disabled = false;
    }
    
    // empty existing items
    for (i = selectCtrl.options.length; i >= 0; i--) {
        selectCtrl.options[i] = null; 
    }
    prompt = (itemArray != null) ? goodPrompt : badPrompt;
    if (prompt == null) {
        j = 0;
    } else {
        selectCtrl.options[0] = new Option(prompt);
        j = 1;
    }
    if (itemArray != null) {
        // add new items
        for (i = 0; i < itemArray.length; i++) {
            selectCtrl.options[j] = new Option(itemArray[i][0]);
            if (itemArray[i][1] != null) {
                selectCtrl.options[j].value = itemArray[i][1]; 
            }
            j++;
        }
        // select first item (prompt) for sub list
        selectCtrl.options[0].selected = true;
    }
}

/**
 * Tranforma uma string noutra no formatado URL compativel
 */
function URLify(s, num_chars) {
    // changes, e.g., "Petty theft" to "petty_theft"
    // remove all these words from the string before urlifying
    removelist = ["a", "an", "as", "at", "before", "but", "by", "for", "from",
                  "is", "in", "into", "like", "of", "off", "on", "onto", "per",
                  "since", "than", "the", "this", "that", "to", "up", "via",
                  "with"];
    r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi');
    s = s.replace(r, '');
    s = s.replace(/[^-A-Z0-9\s]/gi, '');  // remove unneeded chars
    s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
    s = s.replace(/[-\s]+/g, '-');   // convert spaces to hyphens
    s = s.toLowerCase();             // convert to lowercase
    return s.substring(0, num_chars);// trim to first num_chars chars
}

 /* code from qodo.co.uk */
//create as many regular expressions here as you need:
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Z]/g;

function restrictCharacters(myfield, e, restrictionType) {
	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)) {
			return true;
		} else {
			return false;
		}
		
	}
}

String.prototype.replaceAll = function(pcFrom, pcTo){
	var i = this.indexOf(pcFrom);
	var c = this;
	
	while (i > -1){
		c = c.replace(pcFrom, pcTo); 
		i = c.indexOf(pcFrom);
	}
	return c;
}