
//== DISABLED DYNAMIC THUMBNAILS ==
window.addEventListener ? window.addEventListener("load",checkImagesToReload,false)
                        : window.attachEvent("onload",checkImagesToReload);



var Dimension = function(w, h) {
    this.width = w;
    this.height = h;
}


/*
    Just in case prototype and scriptaculous didn't have time do load before these functions are called.
*/
var MyEffect = {

    BlindDown : function(element) {
        try {
            Effect.BlindDown(element);
        }
        catch (e) {
            document.getElementById(element).style.display = '';
        }

    },
    BlindUp : function(element) {
        try {
            Effect.BlindUp(element);
        }
        catch (e) {
            document.getElementById(element).style.display = 'none';
        }
    },
    Fade : function(element) {
        try {
            Effect.Fade(element);
        }
        catch (e) {
            document.getElementById(element).style.display = 'none';
        }

    },
    Appear : function(element) {
        try {
            Effect.Appear(element);
        }
        catch (e) {
            document.getElementById(element).style.display = '';
        }
    },
    show : function(element) {
        try {
            Element.show(element);
        }
        catch (e) {
            document.getElementById(element).style.display = '';
        }
    },
    hide : function(element) {
        try {
            Element.hide(element);
        }
        catch (e) {
            document.getElementById(element).style.display = 'none';
        }
    }
}


function reloadImage(imageId)
{
    var imageElement = $(imageId);
    var newImage = new Image();
    var source = imageElement.src;
    var noCacheIndex = source.indexOf("?nocache=");
    source = source.substring(0, noCacheIndex > 0 ? noCacheIndex : source.length) + "?nocache="+Math.random();
    newImage.onload = function() {
        imageElement.src = source;
        newImage.onload = function() {};
    };
    newImage.src = source;
}

function checkImagesToReload()
{
    var RELOAD_INTERVAL = 5000; // milliseconds
    var imagesToReload = document.getElementsByClassName("reloadedThumb");
    $A(imagesToReload).each(function(image) {
        // give an id to these images
        image.id = "reloadImg"+Math.random();
        var t = setInterval("reloadImage('"+image.id+"');", RELOAD_INTERVAL);
    });
}

/* Toggles the help */
function help(conteudo)
{
    if ($('iframeHelp').style.display == 'none') {
        var helpIF = document.getElementById('help');
        helpIF.src = 'ajuda/ajuda.jsp';
        setTimeout("loadHelpContent('"+conteudo+"');", 500);
        if (Effect) Effect.BlindDown('iframeHelp');
        else document.getElementById('iframeHelp').style.display = '';
    }
    else {
        closeHelp();
    }
    if ($('playerDiv') != null) {
        if (isVideoVisible()) hideVideoPlayer();
    }
    if ($('flashPlayer') != null) {
        Element.hide('flashPlayer');
    }
    if ($('homePlayer') != null) {
        Element.hide('homePlayer');
    }
    if ($('homeBanner') != null) {
        Element.hide('homeBanner');
    }
}

function loadHelpContent(content)
{
    if (content == null || content == "") {
        // load default
        content = "intro.html";
    }
    var doc = document.getElementById('help').contentWindow ? document.getElementById('help').contentWindow.document : document.getElementById('help').document;
    doc.getElementById("conteudo").src = content;
}

/* Closes the help */
function closeHelp()
{
    if (Effect) Effect.BlindUp('iframeHelp');
    else document.getElementById('iframeHelp').style.display = 'none';
    if ($('playerDiv') != null) {
        if (!isImageVisible()) showVideoPlayer();
    }
    if ($('homePlayer') != null) {
        Element.show('homePlayer');
    }
    if ($('flashPlayer') != null) {
        Element.show('flashPlayer');
    }
    if ($('homeBanner') != null) {
        Element.show('homeBanner');
    }
    return false;
}


/*
    Used to write flash objects into the page and prevent IE from requiring activation.
*/
function writeInPage(src)
{
    document.write(src);
}

/* This functions limits the number of digits in a textArea */
function checkSizeBody(textAreaId, maxSize)
{
    var textArea = ((document.getElementById) ? document.getElementById(textAreaId) : eval("document.all['" + textAreaId + "']"));

    if (textArea.value.length > maxSize)
    {
            textArea.value = textArea.value.substring(0, maxSize);
    }
}

/*
    This function updates a "display" (inner html of a span or div) with the number of
    remaining chars that the user can type in a textArea or input.
    When the counter reaches 0, the text area or input will be blocked.

    @param textAreaId id of the textArea or input from which to count the characters
    @param displayId id of the element whose inner html will be updated with the remaining number of
        characters that can be typed (= maxNumber - chars in the text area)
    @param maxNumber the maximum number of characters that can be typed in the text area
    @param countFunction a function that will receive a String as parameter and return the number of chars that should be
        considered in it.
*/
function countdownChars(textAreaId, displayId, maxSize, countFunction)
{
    var textArea = document.getElementById(textAreaId);
    var display = document.getElementById(displayId);
    var numberOfChars = countFunction(textArea.value);

    if (numberOfChars > maxSize)
    {
        var cutValue = textArea.value;
        while (countFunction(cutValue) > maxSize) {
            cutValue = cutValue.removeLastChar();
        }
        textArea.value = cutValue;
        numberOfChars = countFunction(cutValue);
    }

    display.innerHTML = (maxSize - numberOfChars) < 0 ? 0 : maxSize - numberOfChars ;
}

/*
    Default count function. Counts 1 for each character.
    @param string a String whose characters will be counted
*/
function countAllChars(string)
{
    return string.length;
}

/*
    Count function for SMS : each line breaks is worth 2 chars
    @param string a String whose characters will be counted
 */
function countCharsForSMS(string)
{
    // Carriage returns and line feeds must be sent both in SMS. So each line feed counts for double char.
    var crlf = 0;
    var index;
    var substr = string;
    while ((index = substr.indexOf("\n")) != -1) {
        crlf ++;
        substr = substr.substring(index+1);
    }
    return string.length + crlf;
}


/*
    Count function for EMAIL : each line breaks should complete the line to 40 chars
    @param string a String whose characters will be counted
*/
function countCharsForEmail(string)
{
    if (string.indexOf("\n") == -1) return string.length;

    var lines = string.split(/\n/);
    var count = 0;

    for (var i=0; i<lines.length-1; i++)
    {
        count += getNextStep(lines[i].replace(/\r/,'').length, 40);
    }
    count += lines[lines.length-1].replace(/\r/,'').length;
    return count;
}

/*
    Returns the smallest multiple of step greater or equals than number
*/
function getNextStep(number, step)
{
    return (number == 0) ? step : step * Math.ceil(number/step);
}



/*
    Formats the content of a text area as a list whom elements are separated by a comma ',' or semicolon ';'.
    This function will insert a line break after each comma or semicolon.
    @param textAreaId id of the text area element that will be formatted
*/
function formatList(textAreaId)
{
    var textArea = document.getElementById(textAreaId);
    var content = textArea.value;
    textArea.value = content.replace(/\s/g,"").replace(/[,;]/g, ",\n");
}


/**
 * Returns a <code>substring(0, maxSize-suffix.length)</code> of the given String,
 * followed by <code>suffix</code>, only if its size is greater that maxSize.
 * If the suffix is itself larger than the maximum size, only a substring of the
 * given text will be return, without appending the suffix.
 */
String.prototype.smartCut = function(maxSize, suffix)
{
    if (maxSize < 0) return this;
    if (this == null) return "";
    var suf = suffix == null ? "" : suffix;
    if (this.length <= maxSize) return this;
    if (maxSize <= suf.length) return this.substring(0, maxSize);
    return this.substring(0, maxSize-suf.length) + suf;
}

/**
 * Returns a <code>substring(0, maxSize-suffix.length)</code> of the given String,
 * followed by <code>suffix</code>, only if its size is greater that maxSize.
 * If the suffix is itself larger than the maximum size, only a substring of the
 * given text will be return, without appending the suffix.
 * This method also make words that are longer that maxWordSize characters splittable, using "&shy;".
 */
String.prototype.smartCut2 = function(maxSize, suffix, maxWordSize)
{
    if (this == null) return "";
    var cut;
    if (maxSize < 0) cut = this;
    else {
        var suf = suffix == null ? "" : suffix;
        if (this.length <= maxSize) cut = this;
        else if (maxSize <= suf.length) cut = this.substring(0, maxSize);
        else cut = this.substring(0, maxSize-suf.length) + suf;
    }
    // split big words
    var last, res = cut;
    do {
        last = res;
        res = cutFirstLongWord(res, maxWordSize);
    }
    while (res != last);

    return res;
}


/**
 * Split the first word from <code>s</code> that have more than <code>maxWordSize</code> characters (with a hyphen and a space).
 * <br/>Can be called recursively to cut ALL long words of a String, comparing the returned String and the last one as the stop condition.
 * @param s a String
 * @param maxWordSize the maximum size of a the first part of the resulting word, including the hyphen
 * @return s, with the first "long" word cut, if there was such a word.
 */
function cutFirstLongWord(s, maxWordSize)
{
    var reg = new RegExp("([áéíóúàèìòùâêîôûãõñ\\w]{"+(maxWordSize)+"})([áéíóúàèìòùâêîôûãõñ\\w]+)", "g");
    return s.replace(reg,"$1&shy;$2");
}


/*
    Adds trim() function to strings
*/
String.prototype.trim = function()
{
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};


/*
    Removes the last character of a String
*/
String.prototype.removeLastChar = function() {
    return this.substring(0, this.length-1);
}

String.prototype.startsWith = function(prefix) {
    return (this.indexOf(prefix) === 0);
}

String.prototype.endsWith = function(suffix) {
    var index = this.length - suffix.length;
    if (index < 0) {
      return false;
    }
    return (this.lastIndexOf(suffix, index) == index);
}

/*
    IE does not implement the Node as prototypable... Must create global functions.
*/

/**
    Removes all the children of a Node.
    @param container a Node
*/
var removeAllChildren = function(container)
{
    var last;
    while (last = container.lastChild) container.removeChild(last);
}

/**
    Sets the given text as the content of the Node.
    All previous content (children) will be removed
    @param container a Node
    @param text some text
*/
var setTextContent = function(container, text)
{
    removeAllChildren(container);
    /*
    * The old (but more correct) version :
    *   container.appendChild(document.createTextNode(text));
    * did not escape special chars like &nbsp; or &shy;
    */
    container.innerHTML = text;
}


/**
    Returns the Dimension that a rectangle with aspect ratio of "ratio" should have
     to be displayed at its maximum size and fit into availableDimension.
*/
function getProportionalDimension(ratio, availableDimension)
{
    if (ratio <= 0) return availableDimension;

    var resizedHeight = availableDimension.height;
    var resizedWidth = availableDimension.width;

    var availableRatio = availableDimension.width / availableDimension.height;
    if (availableRatio < ratio) {
      resizedHeight = availableDimension.width / ratio;
    } else {
      resizedWidth = availableDimension.height * ratio;
    }

    return new Dimension(resizedWidth, resizedHeight);
}

//abre pagina como os comentarios sem paginacao para impressao
function printComments(filter, order, systemUrl){
    
    systemUrlOpen = systemUrl + "AdminCommentsStatus.do?print=true&filter="+ filter + "&order="+ order;

    commentsWindow = window.open(systemUrlOpen, 'commentsWindow', 'titlebar=yes, menubar=yes, toolbar=no, resizable=yes, scrollbars=yes, status=no,width=800,height=600');
    
}

//abre popup com o termo de responsabilidade
function openUserAgreement1(systemUrl){

    systemUrlOpen = systemUrl + "UserAgreement1.do";

    commentsWindow = window.open(systemUrlOpen, 'agreementWindow1', 'titlebar=yes, menubar=yes, toolbar=no, resizable=yes, scrollbars=yes, status=no,width=850,height=600');

}

//abre popup com o termo de responsabilidade
function openUserAgreement2(systemUrl){

    systemUrlOpen = systemUrl + "UserAgreement2.do";

    commentsWindow = window.open(systemUrlOpen, 'agreementWindow2', 'titlebar=yes, menubar=yes, toolbar=no, resizable=yes, scrollbars=yes, status=no,width=850,height=600');

}



function CheckAll(numElem) { 
   
   for (var i=0;i<numElem;i++) {
        var x = $('chec'+i);        
        var all = document.getElementById("selall");
        x.firstChild.nextSibling.checked = all.checked;
        
   }
    if (all.checked){    
        var elem = document.getElementById("checar");
        elem.innerHTML = "Desmarcar todos";
        
    } else {
        var elem = document.getElementById("checar");
        elem.innerHTML = "Marcar todos";
        
    }
}


