var openDiv = null;
var hiddenObjects = new Array();
var contentFrame = null;
var bottomMarker = null;
var browserMarker = null;
var topMarker = null;
var leftFrame = null;
var rightFrame = null;
var resizeTimer = null;

function resizeContents(noTimer){
    var height = 0;

    if (browserMarker == null) {
    	bottomMarker = document.getElementById('bottomMarker');
    	topMarker = document.getElementById('topMarker');
    	contentFrame = document.getElementById('contentFrame');
    	leftFrame = document.getElementById('leftFrame');
    	rightFrame = document.getElementById('rightFrame');
    	browserMarker = document.getElementById('browserMarker');
	}

	if (window.innerWidth) {//if browser supports window.innerWidth
        height = window.innerHeight;
    }
    else if (document.all) {//else if browser supports document.all (IE 4+)
       	height = document.body.clientHeight;
	}
	//alert(document.body.clientHeight);

	var browserMarkerPos = browserMarker.offsetTop;
	var bottomMarkerPos = bottomMarker.offsetTop;
	var topMarkerPos = topMarker.offsetTop;

	//alert(height + ", " + browserMarkerPos);
    if (height > browserMarkerPos) {
		var heightDelta = (browserMarkerPos - bottomMarkerPos) + 5;
    	contentFrame.style.height = (height - heightDelta - topMarkerPos) + 'px';
    	leftFrame.style.height = (height - heightDelta - topMarkerPos) + 'px';
    	rightFrame.style.height = (height - heightDelta - topMarkerPos) + 'px';
    }
	else {
		var heightDelta = (bottomMarkerPos - topMarkerPos);
		var currentHeight = Math.max(parseInt(contentFrame.style.height.replace(/px/, '')), parseInt(leftFrame.style.height.replace(/px/, '')), parseInt(rightFrame.style.height.replace(/px/, '')));
    	//alert('topMarker = ' + topMarkerPos + " , bottomMarker = " + bottomMarkerPos);

		if (isNaN(currentHeight)){
			contentFrame.style.height = heightDelta + 'px';
			leftFrame.style.height = heightDelta + 'px';
			rightFrame.style.height = heightDelta + 'px';
		}
		else {
			contentFrame.style.height = currentHeight + 'px';
			leftFrame.style.height = currentHeight + 'px';
			rightFrame.style.height = currentHeight + 'px';
		}
	}
    if (!noTimer) {
    	setTimeout("resizeContents()", 750);
    }
}


function showDiv(object, width, height){
    window.scrollTo(0, 0);

    var objects = document.getElementsByTagName('object');
    for (var i = 0; i != objects.length; i++) {
        if (objects[i].style.visibility != 'hidden') {
            objects[i].style.visibility = 'hidden';
            hiddenObjects[hiddenObjects.length] = objects[i];
        }
    }

    //centrar o popup na horizontal
    if (window.innerWidth) {
        document.getElementById(object).style.left = ((window.innerWidth / 2) - (width / 2)) + 'px';
    }
    else {
        document.getElementById(object).style.left = ((document.body.offsetWidth / 2) - (width / 2)) + 'px';
    }

    document.getElementById(object).style.top = '150px';

    document.getElementById('overlay_popup').style.display = 'block';
    document.getElementById(object).style.display = 'block';

    openDiv = object;
}

function showMessageDiv(object, text, title, width, height){
    window.scrollTo(0, 0);

    var objects = document.getElementsByTagName('object');
    for (var i = 0; i != objects.length; i++) {
        if (objects[i].style.visibility != 'hidden') {
            objects[i].style.visibility = 'hidden';
            hiddenObjects[hiddenObjects.length] = objects[i];
        }
    }

    if (window.innerWidth) {
        document.getElementById(object).style.left = ((window.innerWidth / 2) - (width / 2)) + 'px';
    }
    else {
        document.getElementById(object).style.left = ((document.body.offsetWidth / 2) - (width / 2)) + 'px';
    }

    document.getElementById(object).style.top = '150px';

    document.getElementById('overlay_popup').style.display = 'block';
    document.getElementById(object).style.display = 'block';

    document.getElementById(object + 'Title').innerHTML = title;
    document.getElementById(object + 'Text').innerHTML = text;

    openDiv = object;
}

function hideDiv(object){
    document.getElementById(object).style.display = 'none';

    if (document.getElementById('overlay_popup')) {
        document.getElementById('overlay_popup').style.display = 'none';
    }
    for (var i = 0; i != hiddenObjects.length; i++) {
        hiddenObjects[i].style.visibility = 'visible';
    }
    openDiv = null;
}

var lastChapter;

function toggle (objecto) {
	if (document.getElementById(objecto).style.display == 'none') {
		document.getElementById(objecto).style.display = 'block';
		lastChapter = objecto;
	} else {
		document.getElementById(objecto).style.display = 'none';
	}
}

var page = new Array();
var lastpage = new Array();
function abre(div){
    var prefixDiv = div.substring(0, div.indexOf('_', 0));
    var sufixDiv = div.substring(div.indexOf('_', 0) + 1, div.length);

    if (document.getElementById(div) != null) {
        if (document.getElementById(div).style.display == 'block') {
            document.getElementById(div).style.display = 'none';
        }
        else {
            document.getElementById(div).style.display = 'block';
        }
    }

    //fechar todas as divs do mesmo nivel
    if (prefixDiv != 'lasterpage') {
        if (prefixDiv == 'page') {
            for (i in page) {
                if (sufixDiv != page[i]) {
                    element = prefixDiv + '_' + page[i];
                    if (document.getElementById(element) != null) {
                        document.getElementById(element).style.display = 'none';
                    }

                }
            }
        }
        else
            if (prefixDiv == 'lastpage') {
                for (i in lastpage) {
                    if (sufixDiv != lastpage[i]) {
                        element = prefixDiv + '_' + lastpage[i];
                        if (document.getElementById(element) != null) {
                            document.getElementById(element).style.display = 'none';
                        }
                    }
                }
            }
    }
}

ultimoCapitulo = null;

function trocaMapa(objecto){
    if (document.getElementById(objecto).style.display != 'block') {
        document.getElementById(objecto).style.display = 'block';
        if (ultimoCapitulo != null){
            document.getElementById(ultimoCapitulo).style.display = 'none';
        }
        ultimoCapitulo = objecto;
    }
    else if (ultimoCapitulo != objecto){

        document.getElementById(objecto).style.display = 'none';
    }
}

ultimo = null;

function Mapa(objecto){
    if (document.getElementById(objecto).style.display != 'block') {
        document.getElementById(objecto).style.display = 'block';
        if (ultimo != null){
            document.getElementById(ultimo).style.display = 'none';
        }
        ultimo = objecto;
    }
    else if (ultimo != objecto){

        document.getElementById(objecto).style.display = 'none';
    }
}

function retrieveCountries(result){

	var divName = document.getElementById('CountryBox');

	for (var i = 0; i != result.length; ++i) {
		var item = document.createElement('p');

		item.className = "select";
		item.onmouseover = function(){
			this.className = 'selectOver';
		};
		item.onmouseout = function(){
			this.className = 'select';
		};

		item.onclick = function(){
			var inputName = document.getElementById('country');
			var inputIdentificator = document.getElementById('selectedCountry');
			inputIdentificator.value = this.zepp_id;
			inputName.innerHTML = this.innerHTML;
		};

		item.zepp_id = result[i].countryIdentificator;
		item.innerHTML = result[i].countryName;

		divName.appendChild(item);

	}
}

function retrieveFlavours(result){

	var divName = document.getElementById('FlavourBox');

	for (var i = 0; i != result.length; ++i) {
		var item = document.createElement('p');

		item.className = "select";
		item.onmouseover = function(){
			this.className = 'selectOver';
		};
		item.onmouseout = function(){
			this.className = 'select';
		};

		item.onclick = function(){
			var inputName = document.getElementById('flavour');
			var inputIdentificator = document.getElementById('selectedFlavour');
			inputIdentificator.value = this.zepp_id;
			inputName.innerHTML = this.innerHTML;
		};

		item.zepp_id = result[i];
		item.innerHTML = result[i];

		divName.appendChild(item);

	}
}

function toggleQuestion(id){
    var image = document.getElementById(id + '_img');
    var question = document.getElementById(id + '_question');
    var answer = document.getElementById(id + '_answer');

    if (answer.style.display == null || answer.style.display == 'none') {
        answer.style.display = 'block';
        image.src = 'images/bt_close_question.gif';
        question.style.color = '#e0003b';
    }
    else {
        answer.style.display = 'none';
        image.src = 'images/bt_open_question.gif';
        question.style.color = '#6e6e6e';
    }
}

function Centrar(pagina, titulo, w, h, scrollu, resize){
    LeftPosition = (screen.width) ? (screen.width - w) / 2 : 0;
    TopPosition = (screen.height) ? (screen.height - h) / 2 : 0;
    settings = 'height=' + h + ',width=' + w + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=' + scrollu + ',resizable=' + resize + '';
    win = window.open(pagina, titulo, settings)
}

function recoverPass(){
    document.getElementById('recoverPassForm').style.display = 'block';
    document.getElementById('loginBox').style.display = 'none';
}

function getXMLHttpRequest(){
    var httpRequest;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();
    }
    else
        if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                }
            }
        }

    return httpRequest;
}

function openPageHighlight(pageHighlightID){
    var httpRequest = getXMLHttpRequest();

    httpRequest.open('GET', 'stats.php?contentType=PageHighlight&contentID=' + pageHighlightID, true);
    httpRequest.send(null);
}

function openSearch(searchString){
    var httpRequest = getXMLHttpRequest();

    httpRequest.open('GET', 'stats.php?contentType=Search&contentID=' + escape(searchString), true);
    httpRequest.send(null);
}

function openBannerPage(bannerID, pageID, baseURL){
    if (baseURL == null)
        baseURL = '';

    var httpRequest = getXMLHttpRequest();

    httpRequest.open('GET', baseURL + 'stats.php?contentType=BannerPage&contentID=' + bannerID + '&pageID=' + pageID, true);
    httpRequest.send(null);
}

var navigate_to = null;
function showLogin(destino){
    navigate_to = destino;

    document.getElementById('login_form').style.display = 'block';
    document.getElementById('registo_form').style.display = 'none';
    document.getElementById('recuperar_form').style.display = 'none';

    showDiv('divLogin', 298, 177);
}

function submitForm(toSubmit){
    var httpRequest = getXMLHttpRequest();
    httpRequest.onreadystatechange = function(){
        receiveResponse(httpRequest, toSubmit);
    };

    var requestParameters = '';
    requestParameters += escape('__submited_action') + '=' + escape(toSubmit.__submited_action.value) + '&';
    if (toSubmit.username != null)
        requestParameters += escape('username') + '=' + escape(toSubmit.username.value) + '&';
    if (toSubmit.email != null)
        requestParameters += escape('email') + '=' + escape(toSubmit.email.value) + '&';
    if (toSubmit.password != null)
        requestParameters += escape('password') + '=' + escape(toSubmit.password.value) + '&';
    if (toSubmit.confpassword != null)
        requestParameters += escape('confpassword') + '=' + escape(toSubmit.confpassword.value) + '&';
    if (toSubmit.aceitar != null && toSubmit.aceitar.checked)
        requestParameters += escape('aceitar') + '=' + escape(toSubmit.aceitar.value) + '&';
    if (toSubmit.pageID != null)
        requestParameters += escape('pageID') + '=' + escape(toSubmit.pageID.value) + '&';

    httpRequest.open('POST', 'request.php', true);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    httpRequest.send(requestParameters);

    return false;
}

function logout(){
    navigate_to = null;
    var httpRequest = getXMLHttpRequest();
    httpRequest.onreadystatechange = function(){
        receiveResponse(httpRequest, null);
    };

    var requestParameters = escape('__submited_action') + '=' + escape('Entity:Logout');

    httpRequest.open('POST', 'request.php', true);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    httpRequest.send(requestParameters);
}

function receiveResponse(httpRequest, submitedForm){
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            if (httpRequest.responseText == 'ok') {
                if (navigate_to == null || navigate_to == '') {
                    window.location.reload(true);
                }
                else {
                    window.location.href = navigate_to;
                }
            }
            else {
                if (submitedForm != null) {
                    var htmlElement = document.getElementById(submitedForm.id + '_error');
                    if (htmlElement) {
                        htmlElement.innerHTML = httpRequest.responseText;
                        htmlElement.style.display = 'block';

                        var x = htmlElement.getElementsByTagName("script");
                        for (var i = 0; i < x.length; i++) {
                            eval(x[i].innerHTML);
                        }
                    }
                    else {
                        alert(httpRequest.responseText);
                    }
                }
                else {
                    alert(httpRequest.responseText);
                }
            }
        }
        else {
            alert(httpRequest.responseText);
            alert('There was a problem with the request.');
        }
    }
}

function sinopse(scheduleRecordLink){
    var httpRequest = getXMLHttpRequest();
    httpRequest.onreadystatechange = function(){
        receiveSinopse(httpRequest);
    };

    httpRequest.open('GET', scheduleRecordLink + '&version_id=1', true);
    httpRequest.send(null);
}

function receiveSinopse(httpRequest){
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            var htmlElement = document.getElementById('detalheProgramacao');
            if (htmlElement) {
                htmlElement.innerHTML = httpRequest.responseText;
            }

            showDiv('detalheProgramacao', 637, 300);
        }
        else {
            alert(httpRequest.responseText);
        }
    }
    else {
    }
}

/* função que altera a source de uma imagem */
function changeImgSource(target, newSource){
    document.getElementById(target).src = newSource;
}

/* função que altera o valor de um elemento */
function setFilePath(target, value){
    document.getElementById(target).value = value;
}

/* funcao que preenche os dados do postal para envio */
function fillPostcard(){
    document.getElementById('senderName').value = document.getElementById('preSenderName').value;
    document.getElementById('friendName').value = document.getElementById('preFriendName').value;
    document.getElementById('friendEmail').value = document.getElementById('preFriendEmail').value;
    document.getElementById('message').innerHTML = document.getElementById('preMessage').value;
}


function setHeader(header, section){

    targetHeader = document.getElementById(header);

    if (screen.width <= 1024) {
        targetHeader.style.backgroundImage = 'url(images/header/1024/' + section + '/1.jpg)';
    }
    else
        if (screen.width <= 1152) {
            targetHeader.style.backgroundImage = 'url(images/header/1152/' + section + '/1.jpg)';
        }
        else
            if (screen.width <= 1280) {
                targetHeader.style.backgroundImage = 'url(images/header/1280/' + section + '/1.jpg)';
            }
            else
                if (screen.width <= 1440) {
                    targetHeader.style.backgroundImage = 'url(images/header/1440/' + section + '/1.jpg)';
                }


}

function getResolution(){
    var today = new Date();
    var the_date = new Date("December 31, 2023");
    var the_cookie_date = the_date.toGMTString();
    var the_cookie = "users_resolution=" + screen.width + "x" + screen.height;
    var the_cookie = the_cookie + ";expires=" + the_cookie_date;
    document.cookie = the_cookie
	location.reload(true);
}



var TimeToFade = 1000.0;

function fade(eid)
{
  var element = document.getElementById(eid);
  if(element == null)
    return;

  if(element.FadeState == null)
  {
    if(element.style.opacity == null
        || element.style.opacity == ''
        || element.style.opacity == '1')
    {
      element.FadeState = -2;
    }
    else
    {
      element.FadeState = 2;
    }
  }

  if(element.FadeState == 1 || element.FadeState == -1)
  {
    element.FadeState = element.FadeState == 1 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
  }
  else
  {
    element.FadeState = element.FadeState == 2 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade;
    setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
  }
}

function animateFade(lastTick, eid)
{
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;

  var element = document.getElementById(eid);

  if(element.FadeTimeLeft <= elapsedTicks)
  {
    element.style.opacity = element.FadeState == 1 ? '1' : '0';
    element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 1 ? '100' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    return;
  }

  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;

  element.style.opacity = newOpVal;
  element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

  setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function isEmailAddr(email){
	var str = email
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)){
		testresults = true;
	}else{
		testresults = false;
	}
	return (testresults);
}



