/* funcoes gerais */
$(document).ready(function() {
    /*ini super drop down*/
    $("li.btTopo01").hover(function() { abre('#dropcolchoes','.btTopo01'); }, function() { fecha('#dropcolchoes','.btTopo01'); });
    $("li.btTopo02").hover(function() { abre('#dropsommiers','.btTopo02'); }, function() { fecha('#dropsommiers','.btTopo02'); });
    $("li.btTopo03").hover(function() { abre('#dropalmofadas','.btTopo03'); }, function() { fecha('#dropalmofadas','.btTopo03'); });
    $("li.btTopo04").hover(function() { abre('#droptextil','.btTopo04'); }, function() { fecha('#droptextil','.btTopo04'); });
    $("li.btArtigos").hover(function() { abre('#sabiaQue','.btArtigos'); }, function() { fecha('#sabiaQue','.btArtigos'); });
    $("li.btSobreColchaonet").hover(function() { abre('#sobreOcolchao','.btSobreColchaonet'); }, function() { fecha('#sobreOcolchao','.btSobreColchaonet'); });

    $("#dropcolchoes").hover(function() { abre('#dropcolchoes','.btTopo01'); }, function() { fecha('#dropcolchoes','.btTopo01'); });
    $("#dropsommiers").hover(function() { abre('#dropsommiers','.btTopo02'); }, function() { fecha('#dropsommiers','.btTopo02'); });
    $("#dropalmofadas").hover(function() { abre('#dropalmofadas','.btTopo03'); }, function() { fecha('#dropalmofadas','.btTopo03'); });
    $("#droptextil").hover(function() { abre('#droptextil','.btTopo04'); }, function() { fecha('#droptextil','.btTopo04'); });
    $("#sabiaQue").hover(function() { abre('#sabiaQue','.btArtigos'); }, function() { fecha('#sabiaQue','.btArtigos'); });
    $("#sobreOcolchao").hover(function() { abre('#sobreOcolchao','.btSobreColchaonet'); }, function() { fecha('#sobreOcolchao','.btSobreColchaonet'); });
    /*fim super drop down*/
    
    $("img.helptelf").mouseover(function(){ removeClass('div.helptelf');return false; }).mouseout(function(){ addClass('div.helptelf'); });
    $("img.helpnif").mouseover(function(){ removeClass('div.helpnif');return false; }).mouseout(function(){ addClass('div.helpnif'); });
    $("img.helpcvv").mouseover(function(){ removeClass('div.helpcvv');return false; }).mouseout(function(){ addClass('div.helpcvv'); });
    $("input.escolhepagagamento3").click(function(){ escolhepagamento('.escolhepagagamento3'); });
    $("input.escolhepagagamento4").click(function(){ escolhepagamento('.escolhepagagamento4'); });
    $("input#novamoradadadosf1").click(function(){ $('.checkoutmoradaf').css({'display':'hide'}); });
    $("input#novamoradadadosf2").click(function(){ $('.checkoutmoradaf').css({'display':'block'}); });
    
    $("input.mudacodigopostal1").keypress(function (e) {
        var str = $("input.mudacodigopostal1").val();
        if ((str.length)>3) {
            $("input.mudacodigopostal2").focus();
        }
    });
    $("input.mudacodigopostal2").keypress(function (e) {
        var str = $("input.mudacodigopostal2").val();
        if ((str.length)>2) {
            $("input.localidade").focus();
        }
    });
    
    $("input.passoseguinteBiotipo").click(function(event){
        if ($("select.pesocomboguia").val()==0 || $("select.alturacomboguia").val()==0) {
            alert("Escolha o seu peso e altura");
            event.preventDefault(); //link wont go to destination now
        }
    });
});

function tabs(containeractivo,container,tab) {
    $(container).addClass('hide');
    $(containeractivo).removeClass('hide');
    $(tab).siblings().removeClass('activo');
    $(tab).addClass('activo');
}

function escolhepagamento(seleccao) {
    if (seleccao=='.escolhepagagamento4') {
        $('.nib').css({'display':'block'});
        $('.cartaocreditocontainer').css({'display':'none'});
        $('div.erros').css({'display':'none'});
    } else {
        $('.nib').css({'display':'none'});
        $('.cartaocreditocontainer').css({'display':'block'});
        $('div.erros').css({'display':'block'});
    }
}

function abre(area,link) {
    $('#superdropdowns div.superdrop').addClass('hide');
    $(area).removeClass('hide');
    $('#menuTopo ul li a').removeClass('activo');
    $(link+' a').addClass('activo');
}

function fecha(area,link) {
    $('#superdropdowns div.superdrop').addClass('hide');
    $(link+' a').removeClass('activo');
}

function removeClass(janela) {
    $(janela).removeClass('hide');
}
function addClass(janela) {
    $(janela).addClass('hide');
}

hs.graphicsDir = '/temas/default/js/highslide/graphics/';

/* spotlight */
$(function() {
    $('#spotlight').spotlight({ displayTime: 3, transition: ['fadeIn', 'slow'] });
});

/* spotlight */
(function($){$.fn.spotlight=function(options){if(this.length&&(spotlight=$.data(this[0],"spotlight"))){return spotlight;}return this.each(function(){$.data(this,"spotlight",new $.spotlight.init(this,options));});};$.spotlight={defaults:{featureItems:".spotlight_item",itemContent:".featured_content",feature:".spotlight_feature",featuredClass:"activo",displayTime:3,autoReStart:true,transition:null},init:function(element,settings){var self=this;this.settings=$.extend({},$.spotlight.defaults,settings);this.features=$(element).find(this.settings.featureItems);this.featureContainer=$(element).find(this.settings.feature);if(this.settings.transition){if(typeof this.settings.transition=="object"){this.settings.transitionSpeed=this.settings.transition[1];this.settings.transition=this.settings.transition[0];}this.transitionContainer=this.featureContainer.clone().css({position:"absolute",top:0,left:0,margin:0,border:0,overflow:"hidden"}).hide();}this.features.each(function(idx){var featured=$(this);featured.data("idx",idx);featured.data("featured",featured.find(self.settings.itemContent).remove().html());}).hover(function(){self.show($(this).data("idx"));},function(){self.restart();});this.featureContainer.hover(function(){self.stop();},function(){self.restart();});this.show(0);this.start();}};$.extend($.spotlight.init.prototype,{currentIdx:0,showing:null,running:false,interval:null,show:function(idx){this.stop();if(this.showing){this.showing.removeClass(this.settings.featuredClass);}this.showing=this.features.eq(idx);this.currentIdx=idx;this.showing.addClass(this.settings.featuredClass);if(this.featureContainer){if(this.transitionContainer){this.transitionTo(this.showing.data("featured"));}else{this.featureContainer.html(this.showing.data("featured"));}}},start:function(){var self=this;this.running=true;this.interval=setTimeout(function(){self.next(true);},this.settings.displayTime*1000);},stop:function(){this.running=false;clearTimeout(this.interval);},restart:function(){if(this.settings.autoReStart){this.start();}},next:function(override){if(this.running||override){var idx=this.currentIdx+1;if(idx>=this.features.size()){idx=0;}this.show(idx);if(this.running||override){this.start();}}},transitionTo:function(html){var self=this;this.transitionContainer.hide().html(html).appendTo(this.featureContainer);this.transitionContainer[this.settings.transition](this.settings.transitionSpeed,function(){self.featureContainer.html(html);});}});})(jQuery);

/* galeria */
(function($){var $$;$$=$.fn.galleria=function($options){if(!$$.hasCSS()){return false;}$.historyInit($$.onPageLoad);var $defaults={insert:".galleria_container",history:true,clickNext:true,onImage:function(image,caption,thumb){},onThumb:function(thumb){}};var $opts=$.extend($defaults,$options);for(var i in $opts){if(i){jQuery.galleria[i]=$opts[i];}}var _insert=($($opts.insert).is($opts.insert))?$($opts.insert):jQuery(document.createElement("div")).insertBefore(this);var _div=$(document.createElement("div")).addClass("galleria_wrapper");var _span=$(document.createElement("span")).addClass("caption");_insert.addClass("galleria_container").append(_div).append(_span);return this.each(function(){$(this).addClass("galleria");$(this).children("li").each(function(i){var _container=$(this);var _o=$.meta?$.extend({},$opts,_container.data()):$opts;_o.clickNext=$(this).is(":only-child")?false:_o.clickNext;var _a=$(this).find("a").is("a")?$(this).find("a"):false;var _img=$(this).children("img").css("display","none");var _src=_a?_a.attr("href"):_img.attr("src");var _title=_a?_a.attr("title"):_img.attr("title");var _loader=new Image();if(_o.history&&(window.location.hash&&window.location.hash.replace(/\#/,"")==_src)){_container.siblings(".active").removeClass("active");_container.addClass("active");}$(_loader).load(function(){$(this).attr("alt",_img.attr("alt"));var _thumb=_a?_a.find("img").addClass("thumb noscale").css("display","none"):_img.clone(true).addClass("thumb").css("display","none");if(_a){_a.replaceWith(_thumb);}if(!_thumb.hasClass("noscale")){var w=Math.ceil(_img.width()/_img.height()*_container.height());var h=Math.ceil(_img.height()/_img.width()*_container.width());if(w<h){_thumb.css({height:"auto",width:_container.width(),marginTop:-(h-_container.height())/2});}else{_thumb.css({width:"auto",height:_container.height(),marginLeft:-(w-_container.width())/2});}}else{window.setTimeout(function(){_thumb.css({marginLeft:-(_thumb.width()-_container.width())/2,marginTop:-(_thumb.height()-_container.height())/2});},1);}_thumb.attr("rel",_src);_thumb.attr("title",_title);_thumb.click(function(){jQuery.galleria.activate(_src);});_thumb.hover(function(){$(this).addClass("hover");},function(){$(this).removeClass("hover");});_container.hover(function(){_container.addClass("hover");},function(){_container.removeClass("hover");});_container.prepend(_thumb);_thumb.css("display","block");_o.onThumb(jQuery(_thumb));if(_container.hasClass("active")){jQuery.galleria.activate(_src);}_img.remove();}).error(function(){_container.html('<span class="error" style="color:red">Error loading image: '+_src+"</span>");}).attr("src",_src);});});};$$.nextSelector=function(selector){return $(selector).is(":last-child")?$(selector).siblings(":first-child"):$(selector).next();};$$.previousSelector=function(selector){return $(selector).is(":first-child")?$(selector).siblings(":last-child"):$(selector).prev();};$$.hasCSS=function(){$("body").append($(document.createElement("div")).attr("id","css_test").css({width:"1px",height:"1px",display:"none"}));var _v=($("#css_test").width()!=1)?false:true;$("#css_test").remove();return _v;};$$.onPageLoad=function(_src){var _wrapper=$(".galleria_wrapper");var _thumb=$('.galleria img[@rel="'+_src+'"]');if(_src){if(jQuery.galleria.history){window.location=window.location.href.replace(/\#.*/,"")+"#"+_src;}_thumb.parents("li").siblings(".active").removeClass("active");_thumb.parents("li").addClass("active");var _img=$(new Image()).attr("src",_src).addClass("replaced");_wrapper.empty().append(_img);_wrapper.siblings(".caption").text(_thumb.attr("title"));jQuery.galleria.onImage(_img,_wrapper.siblings(".caption"),_thumb);if(jQuery.galleria.clickNext){_img.css("cursor","pointer").click(function(){jQuery.galleria.next();});}}else{_wrapper.siblings().andSelf().empty();$(".galleria li.active").removeClass("active");}jQuery.galleria.current=_src;};$.extend({galleria:{current:"",onImage:function(){},activate:function(_src){if(jQuery.galleria.history){$.historyLoad(_src);}else{$$.onPageLoad(_src);}},next:function(){var _next=$($$.nextSelector($('.galleria img[@rel="'+jQuery.galleria.current+'"]').parents("li"))).find("img").attr("rel");jQuery.galleria.activate(_next);},prev:function(){var _prev=$($$.previousSelector($('.galleria img[@rel="'+jQuery.galleria.current+'"]').parents("li"))).find("img").attr("rel");jQuery.galleria.activate(_prev);}}});})(jQuery);jQuery.extend({historyCurrentHash:undefined,historyCallback:undefined,historyInit:function(callback){jQuery.historyCallback=callback;var current_hash=location.hash;jQuery.historyCurrentHash=current_hash;if(jQuery.browser.msie){if(jQuery.historyCurrentHash===""){jQuery.historyCurrentHash="#";}$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=current_hash;}else{if(jQuery.browser.safari){jQuery.historyBackStack=[];jQuery.historyBackStack.length=history.length;jQuery.historyForwardStack=[];jQuery.isFirst=true;}}jQuery.historyCallback(current_hash.replace(/^#/,""));setInterval(jQuery.historyCheck,100);},historyAddHistory:function(hash){jQuery.historyBackStack.push(hash);jQuery.historyForwardStack.length=0;this.isFirst=true;},historyCheck:function(){if(jQuery.browser.msie){var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentDocument||ihistory.contentWindow.document;var current_hash=iframe.location.hash;if(current_hash!=jQuery.historyCurrentHash){location.hash=current_hash;jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,""));}}else{if(jQuery.browser.safari){if(!jQuery.dontCheck){var historyDelta=history.length-jQuery.historyBackStack.length;if(historyDelta){jQuery.isFirst=false;var i;if(historyDelta<0){for(i=0;i<Math.abs(historyDelta);i++){jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());}}else{for(i=0;i<historyDelta;i++){jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());}}var cachedHash=jQuery.historyBackStack[jQuery.historyBackStack.length-1];if(cachedHash!==undefined){jQuery.historyCurrentHash=location.hash;jQuery.historyCallback(cachedHash);}}else{if(jQuery.historyBackStack[jQuery.historyBackStack.length-1]===undefined&&!jQuery.isFirst){if(document.URL.indexOf("#")>=0){jQuery.historyCallback(document.URL.split("#")[1]);}else{current_hash=location.hash;jQuery.historyCallback("");}jQuery.isFirst=true;}}}}else{current_hash=location.hash;if(current_hash!=jQuery.historyCurrentHash){jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,""));}}}},historyLoad:function(hash){var newhash;if(jQuery.browser.safari){newhash=hash;}else{newhash="#"+hash;location.hash=newhash;}jQuery.historyCurrentHash=newhash;if(jQuery.browser.msie){var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=newhash;jQuery.historyCallback(hash);}else{if(jQuery.browser.safari){jQuery.dontCheck=true;this.historyAddHistory(hash);var fn=function(){jQuery.dontCheck=false;};window.setTimeout(fn,200);jQuery.historyCallback(hash);location.hash=newhash;}else{jQuery.historyCallback(hash);}}}});

/* timer */
$.fn.extend({everyTime:function(interval,label,fn,times,belay){return this.each(function(){$.timer.add(this,interval,label,fn,times,belay);});},oneTime:function(interval,label,fn){return this.each(function(){$.timer.add(this,interval,label,fn,1);});},stopTime:function(label,fn){return this.each(function(){$.timer.remove(this,label,fn);});}});$.event.special;$.extend({timer:{global:[],guid:1,dataKey:"$.timer",regex:/^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,powers:{ms:1,cs:10,ds:100,s:1000,das:10000,hs:100000,ks:1000000},timeParse:function(value){if(value==undefined||value==null){return null;}var result=this.regex.exec($.trim(value.toString()));if(result[2]){var num=parseFloat(result[1]);var mult=this.powers[result[2]]||1;return num*mult;}else{return value;}},add:function(element,interval,label,fn,times,belay){var counter=0;if($.isFunction(label)){if(!times){times=fn;}fn=label;label=interval;}interval=$.timer.timeParse(interval);if(typeof interval!="number"||isNaN(interval)||interval<=0){return;}if(times&&times.constructor!=Number){belay=!!times;times=0;}times=times||0;belay=belay||false;var timers=$.data(element,this.dataKey)||$.data(element,this.dataKey,{});if(!timers[label]){timers[label]={};}fn.timerID=fn.timerID||this.guid++;var handler=function(){if(belay&&this.inProgress){return;}this.inProgress=true;if((++counter>times&&times!==0)||fn.call(element,counter)===false){$.timer.remove(element,label,fn);}this.inProgress=false;};handler.timerID=fn.timerID;if(!timers[label][fn.timerID]){timers[label][fn.timerID]=window.setInterval(handler,interval);}this.global.push(element);},remove:function(element,label,fn){var timers=$.data(element,this.dataKey),ret;if(timers){if(!label){for(label in timers){this.remove(element,label,fn);}}else{if(timers[label]){if(fn){if(fn.timerID){window.clearInterval(timers[label][fn.timerID]);delete timers[label][fn.timerID];}}else{for(var fn in timers[label]){window.clearInterval(timers[label][fn]);delete timers[label][fn];}}for(ret in timers[label]){break;}if(!ret){ret=null;delete timers[label];}}}for(ret in timers){break;}if(!ret){$.removeData(element,this.dataKey);}}}}});$(window).bind("unload",function(){$.each($.timer.global,function(index,item){$.timer.remove(item);});});

/* multidestaque */

tempoLoop = "10s";
limite = 8;

nivel1 = "#multidestaques";
nivel2d = ".multidestaques";
nivel2n = "#paginacao";

$(document).ready(function(){
    loopDestaques(tempoLoop);
});

function pausaLoop() {
    stopLoopDestaques();
    $('#player .playli').removeClass('activo');
    $('#player .pauseli').addClass('activo');
}

function playLoop() {
    loopDestaques(tempoLoop);
    $('#player .playli').addClass('activo');
    $('#player .pauseli').removeClass('activo');
}

function slideDestaques(destaque) {
    getNumDestaques = $(nivel1+" "+nivel2n+" li:last-child").attr("class").substring(12,14);
    actual = "."+($(nivel1+" "+nivel2n+" li."+destaque).attr("class")).substring(8,14);
    if (getNumDestaques.substring(0,1)==0) numDestaques = getNumDestaques.substring(1,2); else numDestaques = getNumDestaques.substring(0,2);
    if (actual.substring(4,5)==0) posicao = actual.substring(5,6); else posicao = actual.substring(5,7);
    
    paginas = Math.ceil(numDestaques/limite);
    posicaoPagina = Math.ceil(posicao/limite);
    limitePagina  = posicaoPagina*limite;
    
    for (var i=0; i<=getNumDestaques; i++) {
        posicaoi = Math.ceil(i/limite);
        if (i<=9) numero = '0'+i; else numero = i;
        if (posicaoi==posicaoPagina) {
            $(nivel1+" "+nivel2n+" li.pos"+numero).css({'display':'block'});
        } else {
            $(nivel1+" "+nivel2n+" li.pos"+numero).css({'display':'none'});
        }
    }
} 

function trocaDestaques(destaque) {
    //.a2
    //if (destaque.substring(8,9)==' ') destaque = destaque.substring(0,8);
    $(destaque+'g').siblings().addClass("fechado");
    $(destaque+'g').removeClass("fechado"); //novo
    $(nivel1+" "+nivel2d+" .fechado").css({"display":"none"});
    $(nivel1+" "+nivel2d+" "+destaque+"g").fadeIn("1000");
    $(nivel1+" "+nivel2d+" "+destaque+"g").css({"display":"block"});
    $(nivel1+" "+nivel2n+" li").removeClass("activo");
    $(nivel1+" "+nivel2n+" li"+destaque).addClass("activo");
    slideDestaques(destaque);
}

function escolheDestaque(destaque) {
    stopLoopDestaques();
    loopDestaques(tempoLoop);
    trocaDestaques(destaque);
}

function loopDestaques(tempo){
    $(nivel1).everyTime( tempo,function(){ avancar(); });
}

function stopLoopDestaques(){
    $(nivel1).stopTime();
}

function recuar() {
    stopLoopDestaques();
    loopDestaques(tempoLoop);
    $(nivel1+" "+nivel2n+" li").removeClass("anterior");
    if ($(nivel1+" "+nivel2n+" li:first-child").hasClass("activo")) {
        anterior = $(nivel1+" "+nivel2n+" li:last-child").addClass("anterior");
    } else {
        anterior = $(nivel1+" "+nivel2n+" li.activo").prev().addClass("anterior");
    }
    destaque = "."+($(nivel1+" "+nivel2n+" li.anterior").attr("class")).substring(0,2);
    trocaDestaques(destaque);
}

function avancar() {
    stopLoopDestaques();
    loopDestaques(tempoLoop);
    $(nivel1+" "+nivel2n+" li").removeClass("seguinte");
    if ($(nivel1+" "+nivel2n+" li:last-child").hasClass("activo")) {
        seguinte = $(nivel1+" "+nivel2n+" li:first-child").addClass("seguinte");
    } else {
        seguinte = $(nivel1+" "+nivel2n+" li.activo").next().addClass("seguinte");
    }
    destaque = "."+($(nivel1+" "+nivel2n+" li.seguinte").attr("class")).substring(0,2);
    trocaDestaques(destaque);
}

function expandeFaqs(botao) {
    //$(botao).siblings().removeClass('activo');
    $(botao).toggleClass('activo');
}

function IsNumeric(sText) {
    var ValidChars = "0123456789 .";
    var IsNumber=true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

/* ------------------------INI XHR------------------------ */
function obtainXmlHttp() {
    var xmlhttp = false;
    /*@cc_on@*/
    /*@if (@_jscript_version>=5)
        try {
            xmlhttp = new ActiveXObjecto("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
    @end @*/
    
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}
/* ------------------------FIM XHR------------------------ */

/* ------------------------PRINT PREVIEW------------------------ */ 
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent( function(){ add_print_link( 'nav' ) } );

function add_print_link( id ){
  if( !document.getElementById ||
      !document.getElementById( id ) ) return;

  // add extra functions to page tools list
  var print_page = document.getElementById( id );

  // create print link
  var print_function = document.createElement('p');
  print_function.className = 'print-link';
  print_function.onclick = function(){ print_preview(); return false; };
  print_function.appendChild( document.createTextNode( 'Print the Page' ) );

}

function print_preview() {
    //popupWin = window.open('<?=$_SERVER["REQUEST_URI"]?>', 'open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0');
    // Switch the stylesheet
    setActiveStyleSheet('Print Preview');
    // Create preview message
    add_preview_message();
    // Print the page
    window.print();
}

function add_preview_message(){
var main_content = document.getElementById('areaconteudogca');
var main_body = main_content.parentNode;

	if (document.getElementById){
		
		var preview_message = document.createElement('div');
		preview_message.id = 'preview-message';
	
		// Create Heading
		var preview_header = document.createElement('h3');
		var preview_header_text = document.createTextNode('');
		preview_header.appendChild(preview_header_text);
		
		// Create paragraph
		var preview_para = document.createElement('p');
		var preview_para_text = document.createTextNode('');
		
		var cancel_function_link = document.createElement('a');
			cancel_function_link.onclick = function(){ cancel_print_preview(); return false; };
			cancel_function_link.setAttribute('href', '#');	
		var cancel_function_link_text = document.createTextNode('Voltar ao site');
		cancel_function_link.appendChild(cancel_function_link_text);
		preview_para.appendChild(preview_para_text); //
		preview_para.appendChild(cancel_function_link);
		
		// Put it all toegether
		preview_message.appendChild(preview_header); 
		preview_message.appendChild(preview_para);
		main_body.insertBefore(preview_message, main_content);

	}
}

function cancel_print_preview() {
	// Destroy the preview message
	var print_preview = document.getElementById('preview-message');
	var main_body = print_preview.parentNode;
	main_body.removeChild(print_preview);
	
	// Switch back stylesheet
	setActiveStyleSheet('default');
}

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
}
/* ------------------------FIM PRINT PREVIEW------------------------ */