﻿
function Init() {
    InitFontSize();
    InitTabs();
    //ShowPub();
    InitLang();
}

function InitLang() {
    var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;
    var cookieLang = readCookie("varpt");
  
    //alert("cookieLang: " + cookieLang);
    //alert("userLang: " + userLang);

    if (userLang.toLowerCase() == 'pt-br' && cookieLang == null) {
        changeVar(1, true);
        $('input[id$="_rdb_VarPb"]').attr('checked', 'checked');
        //alert("changed BR");
    }
}

function ShowPub() {
    ShowPubOpenX();
    ShowPubImpresa();
}

function ShowPubOpenX() {

    var scriptPrincipal = "<sc" + "ript><!--//<![CDATA[" +
							   "var m3_u = (location.protocol=='https:'?'https://d1.openx.org/ajs.php':'http://d1.openx.org/ajs.php');\n" +
							   "var m3_r = Math.floor(Math.random()*99999999999);\n" +
							   "if (!document.MAX_used) document.MAX_used = ',';\n" +
							   "document.write (\"<scr\"+\"ipt type='text/javascript' src='\"+m3_u);\n" +
							   "document.write (\"?zoneid=35421\");\n" +
							   "document.write ('&amp;cb=' + m3_r);\n" +
							   "if (document.MAX_used != ',') document.write (\"&amp;exclude=\" + document.MAX_used);\n" +
							   "document.write (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));\n" +
							   "document.write (\"&amp;loc=\" + escape(window.location));\n" +
							   "if (document.referrer) document.write (\"&amp;referer=\" + escape(document.referrer));\n" +
							   "if (document.context) document.write (\"&context=\" + escape(document.context));\n" +
							   "if (document.mmm_fo) document.write (\"&amp;mmm_fo=1\");\n" +
							   "document.write (\"'><\/scr\"+\"ipt>\");\n" + 
							"//]]>--></scr" + "ipt>";

    //alert("PUB OpenX: " + scriptPrincipal);
    $("[id$='_bannerPrincipal']").html(scriptPrincipal);
    //$("[id$='_bannerOutras']").html("Banner Outras");
}

function ShowPubImpresa() {
    //alert("PUB Impresa");
}

function InitTabs() {

    var tabsID = document.getElementById("OutterTabs");
    if (tabsID != null) {
        tabsID.style.display = "block";
    }
}

/* INIT: Fonts */
function InitFontSize() {
    if (readCookie("DLPOFontSize") != null) {
        var elemChild = $('#DivDefinicao').find('div');
        for (i = 0; i < elemChild.length; i++) {
            var innerEl = elemChild[i];
            SetNodeSize(innerEl, 0, true);
        }
    }
}

function ChangeFontSize(step) {
    step = parseInt(step, 4);
    var elemChild = $('#DivDefinicao').find('div');
    for (i = 0; i < elemChild.length; i++) {
        var innerEl = elemChild[i];
        SetNodeSize(innerEl, step, false);
    }
}

function SetNodeSize(elem, step, isInit) {
    if (elem != null && elem.style != null && elem.tagName != "INPUT") {
        var curFont = parseInt(elem.style.fontSize, 10);
        if (isInit) 
        {
            if (isNaN(curFont))
                var fsize = readCookie("DLPOFontSize");
            if (fsize != null) {
                $(elem).css('font-size', fsize + 'px');
            }
        }
        else 
        {
            if (isNaN(curFont)) 
            {
                $(elem).css('font-size', (11 + step) + 'px');
                createCookie("DLPOFontSize", 11 + step, 30);
            }
            else 
            {
                if ((curFont + step) < 18 && (curFont + step) > 8) {
                    $(elem).css('font-size', (curFont + step) + 'px');
                    createCookie("DLPOFontSize", curFont + step, 30);
                }
            }
        }
    }
}
/* FIM: Fonts */

// Código em: http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}



//código em http://labnol.blogspot.com/2006/01/add-to-favorites-ie-bookmark-firefox.html
function AddBookmark() 
{
    title = "Dicionário Priberam da Língua Portuguesa";
    url = "http://www.priberam.pt/dlpo/";

    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url, "");
    } else if (window.external) { // IE Favorite
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) { // Opera Hotlist
        return true;
    }
}

// código de http://www.quirksmode.org/js/findpos.html
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	    do {
	        curleft += obj.offsetLeft;
	        curtop += obj.offsetTop;
	    } while (obj = obj.offsetParent);
	}
    return [curleft,curtop];
}

// Código de http://www.dynamic-tools.net/toolbox/copyToClipboard/
function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
    } 
    else 
    {
        var clipboarddiv = document.getElementById('divclipboardswf');
        if (clipboarddiv == null) {
            clipboarddiv = document.createElement('div');
            clipboarddiv.setAttribute("name", "divclipboardswf");
            clipboarddiv.setAttribute("id", "divclipboardswf");
            document.body.appendChild(clipboarddiv);
        }
        clipboarddiv.innerHTML = '<embed src="clipboard.swf" FlashVars="clipboard=' +
        encodeURIComponent(text) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    }
    //alert('A ligação foi copiada para o Clipboard');
    return false;  
}


function LinkThis(LinkURL) {
    var elemImg = document.getElementById("LinkThis");
    var elemDiv = document.getElementById("linkDiv");

    //window.alert(findPos(elemImg)[0] + ", " + findPos(elemImg)[1] + " - " + LinkURL);
    elemDiv.style.display = 'block';
    elemDiv.style.position = 'absolute';
    elemDiv.style.left = findPos(elemImg)[0] + "px";
    elemDiv.style.top = (findPos(elemImg)[1] + 20) + "px";

    copyToClipboard(window.location.href);
}
function CloseLinkThis() {
    var elemDiv = document.getElementById("linkDiv");
    elemDiv.style.display = 'none';
}


function ScriptThis(ScriptText) {
    var elemImg = document.getElementById("ScriptThis");
    var elemDiv = document.getElementById("ScriptDiv");
    var elemTxt = document.getElementById("ScriptThisText"); 

    //window.alert(findPos(elemImg)[0] + ", " + findPos(elemImg)[1] + " - " + LinkURL);
    elemDiv.style.display = 'block';
    elemDiv.style.position = 'absolute';
    elemDiv.style.left = findPos(elemImg)[0] + "px";
    elemDiv.style.top = (findPos(elemImg)[1] + 20) + "px";

    elemTxt.value = ScriptText;
    //copyToClipboard(ScriptText);
    //window.alert(ScriptText);
}
function CloseScriptThis() {
    var elemDiv = document.getElementById("ScriptDiv");
    elemDiv.style.display = 'none';
}




function MostraCitacao() {
    var elemImg = document.getElementById("CitacaoImg");
    var elemDiv = document.getElementById("citacaoDiv");

    elemDiv.style.display = 'block';
    elemDiv.style.position = 'absolute';
    elemDiv.style.left = (findPos(elemImg)[0]) + "px";
    elemDiv.style.top = (findPos(elemImg)[1] + 20) + "px";
}
function CloseCitacao() {
    var elemDiv = document.getElementById("citacaoDiv");
    elemDiv.style.display = 'none';
}



function SendPage(CompleteURL) {
    window.open(CompleteURL, "SENDPAGE", "");
}

function getSel() {
    var txt = '';
    if (window.getSelection) {
        txt = window.getSelection();
    }
    else if (document.getSelection) {
        txt = document.getSelection();
    }
    else if (document.selection) {
        rng = document.selection.createRange();
        txt = rng.text;
        rng.moveStart('word', -2);
        if (rng.text.indexOf("-") > 0) {
            txt = rng.text;
        }
        else {
            rng = document.selection.createRange();
            rng.moveEnd('word', 2);
            if (rng.text.indexOf("-") > 0)
                txt = rng.text;
        }
        
        // HUGOS 2008-04-10:: So faz o trim no IE. No Firefox nao esta a funcionar por causa do replace()
        txt = trim(txt);

        //Hugos 2011-07-26: Corrige o problema dos aAO/dAO e pt/pb (#2487)
        txt = txt.split(" ", 1);
    }
    else return;
    //DEBUG: alert("Apanhou: " + txt);
    return txt;
}


function trim(str) {
    return str.replace(/^\s*|\s*$/g, "");
}


function SeleccionaEntrada(pal) {
    DefinePalavra(pal);
}

function DefinePalavra(pal) {
    if (pal == "")
        return;
    document.location.href = "default.aspx?pal=" + pal;
}
function encode_utf8(s) {
    return unescape(encodeURIComponent(s));
}


function showDiv(divID) {
    var elem = document.getElementById(divID);

    if (elem.style.display == "") {
        elem.style.display = "none";
    }
    else {
        elem.style.display = "";
    }
}

function autocompleter_formatitem(row, pos, num, s) {
    return '<div class="' + row[1] + '">' + row[0] + '</div>';
}

var autocomplete_id;
function flush_autocomplete()
{
    jQuery("#" + autocomplete_id).flushCache ();
}

function create_autocomplete(id) {
    /*jQuery("#" + id).autocomplete("PalavraAutoComplete.aspx", 
    { 
        minChars: 1, 
        selectFirst:false, 
        autoFill: false, 
        max: 15, 
        scroll: false, 
        onItemSelect: function() { Define(); } 
    })*/


    var varpt = readCookie ("varpt");
    autocomplete_id = id;
    jQuery("#" + id).autocomplete("PalavraAutoComplete.aspx", { minChars: 1, selectFirst:false, autoFill: false, max: 15, scroll: false,
             onItemSelect: function() { Define(); } ,
             extraParams: { langvar: function() { return readCookie('varpt') == '0' ? 'pt' : 'pb'; } }})
    .result(autocomplete_result).focus();
}

function autocomplete_result() {
    DefinePalavra(jQuery(this).val());
}


// Para carregar os anúncios no final da página
var adPositions = new Array;

// Write out the placeholder <div> and add an entry to the adPositions array to indicate that this ad position is present on the current page
function writeAdDiv(name, ad_width, ad_height) {
    // Write the placeholder <div>
    document.write('<div class="banner" id="'+name+'" style="width:'+ad_width+'px; height:'+ad_height+'px; line-height:' + ad_height + 'px;">&nbsp;</div>');
    // Add an item to the adPositions array
    adPositions[name] = name;
}


// DIV moving code
function OpenX_findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
    }
	return curleft;
}

function OpenX_findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
    }
	return curtop;
}

function OpenX_moveAbove(sourceObj,targetObj) {
    var height = 0;
    if (sourceObj.offsetHeight) {
        height = sourceObj.offsetHeight;
    } else if (sourceObj.clip && sourceObj.clip.height) {
        height = sourceObj.clip.height;
    } else if (sourceObj.style && sourceObj.style.pixelHeight) {
        height = sourceObj.style.pixelHeight;
    }
    
    if (window.XMLHttpRequest) {
        if (document.all) { //IE7
            if (height > 0) { targetObj.style.height = height; }

            if (Browser.Version() < 9) {
                sourceObj.style.left = OpenX_findPosX(targetObj);
                sourceObj.style.top = OpenX_findPosY(targetObj);
            } else {
                sourceObj.style.left = OpenX_findPosX(targetObj) + "px";
                sourceObj.style.top = OpenX_findPosY(targetObj) + "px";
            }
            
		} else { // Mozilla, etc
		    targetObj.style.paddingTop = 0; targetObj.style.paddingBottom = 0;

		    if (height > 0) { targetObj.style.height = height; }
		    sourceObj.style.left = OpenX_findPosX(targetObj) + "px";
		    sourceObj.style.top = OpenX_findPosY(targetObj) + "px";
		}
    } else { // IE6, older browsers
        if (height > 0) { targetObj.style.height = height; }
        
        sourceObj.style.left = OpenX_findPosX(targetObj);
        sourceObj.style.top = OpenX_findPosY(targetObj);
    }
	
	    

	//DEBUG OPENX:
    //document.write(sourceObj.id + ": " + sourceObj.style.left + "," + sourceObj.style.top + " || ");
    //document.write(targetObj.id + ": " + OpenX_findPosX(targetObj) + "," + OpenX_findPosY(targetObj) + " || ");
    //document.write("<br>");
}

// KUDOS: http://obvcode.blogspot.com/2007/11/easiest-way-to-check-ie-version-with.html
var Browser = {
    Version: function() {
        var version = 999; // we assume a sane browser
        if (navigator.appVersion.indexOf("MSIE") != -1)
        // bah, IE again, lets downgrade version number
            version = parseFloat(navigator.appVersion.split("MSIE")[1]);
        return version;
    }
}

function OpenX_positionDivs() {
    for (var zoneName in adPositions) {

        var offScreenZoneName = zoneName + '-Hidden';
        if (document.getElementById) {
            targetZoneDivID = document.getElementById(zoneName);
            sourceZoneDivID = document.getElementById(offScreenZoneName);
        } else if (document.all) {
            targetZoneDivID = document.all[zoneName];
            sourceZoneDivID = document.all[offScreenZoneName];
        } else if (document.layers) {
            targetZoneDivID = document.layers[zoneName];
            sourceZoneDivID = document.layers[offScreenZoneName];
        }

        if ((targetZoneDivID != null) && (sourceZoneDivID != null)) {
    		OpenX_moveAbove(sourceZoneDivID, targetZoneDivID);
        }
    }
}
