
/*$(document).ready(function() {
	fundos = Math.round(Math.random() * 3);
	fundos = fundos +1;

	$("body").css({ background:"url(/_css/bgcoral/bg2.jpg) no-repeat fixed top center"});
 });*/

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

function getQueryVariable(sQuery, sSeparator){
	if (location.search!=""){
		var x = location.search.substr(1).split(sSeparator);
		try{
			y = x[0].split("=");
			if(y[0]==sQuery && IsNumeric(y[1]) && y[1]!="") return y[1];
			else return null;
		}catch(er){ return null; }
	}
}

if(!Array.prototype.push){
	// To cover IE 5 Mac lack of the push method	
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
}

function getNode(nodeId){
	if(document.getElementById)
		return document.getElementById(nodeId);
	else if(document.all && document.all(nodeId))
		return document.all(nodeId);
	else if(document.layers && document.layers[nodeId])
		return document.layers[nodeId];
	else
		return false;
}

function show(object){
	getNode(object).style.display = 'inline';
}

function hide(object){
	getNode(object).style.display = 'none';
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}


function bookmark() {
	
	 title = document.title; 
	  // Blogger - Replace with <$BlogItemTitle$> 
	  // MovableType - Replace with <$MTEntryTitle$>
	
	 url = window.location;
	  // Blogger - Replace with <$BlogItemPermalinkURL$> 
	  // MovableType - Replace with <$MTEntryPermalink$>
	  // WordPress - <?php bloginfo('url'); ?>

	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;
	}
}




function noscroll(param,w,h,nome) {
        var nomearq=param;
        var windowvar = window.open(nomearq,nome,"scrollbars=no,location=no,directories=no,status=no,menubar=no,resizable=no,toolbar=no,width="+ w + ",height="+h );
}

function popscroll(param,w,h,nome) {
        var nomearq=param;
        var windowvar = window.open(nomearq,nome,"scrollbars=yes,location=no,directories=no,status=no,menubar=no,resizable=no,toolbar=no,width="+ w + ",height="+h );
}

function popTermoUso(param,w,h,nome,field) {
        var nomearq=param;
        if(nomearq.indexOf('?') > -1){
        	nomearq += "&field="+field;
        } else {
        	nomearq += "?field="+field;
        }
        var windowvar = window.open(nomearq,nome,"scrollbars=yes,location=no,directories=no,status=no,menubar=no,resizable=no,toolbar=no,width="+ w + ",height="+h );
}


function cadastraPost(){
	/*var urlCadastro = '';

	if (urlPost != undefined){
	  urlCadastro = urlPost;
	}
	else{
	  urlCadastro = window.location;
	}

      var categoria = getCategoria(urlCadastro);

	popscroll('/pcasite/postit/incluir.jsf?urlCadastro='+urlCadastro+'&categoria='+categoria,500,470,'postit');*/

	var urlCadastro = window.location.href;
	var categoria = getCategoria(urlCadastro);
	popscroll('/pcasite/postit/incluir.jsf?urlCadastro='+urlCadastro+'&categoria='+categoria,550,550,'postit');

}


function getCategoria(urlStr) {
      var rgs =[
            [new RegExp(/.*?\/pcasite\/conteudocolaborativo\/(.*?)\/.*/),'#1'],
            [new RegExp(/.*?\/pcasite\/(pergunta)\/(.*?)\/.*/),'#1#2'],
            [new RegExp(/.*?\/pcasite\/(perfil)\/(.*?)\/.*/),'#1#2'],
            [new RegExp(/.*?\/decorar\/(.*?)\/.*/),'#1'],
            [new RegExp(/.*?\/construir\/(.*?)\/.*/),'#1'],
            [new RegExp(/.*?\/ondemorar\/(.*?)\/.*/),'#1'],
            [new RegExp(/.*?\/canais\/(.*?)\/.*/),'#1'],
            [new RegExp(/.*?\/materias\/(.*?)\/.*/),'#1'], 
            [new RegExp(/.*?\/materias\/(.*?).shtml/),'#1'],
            [new RegExp(/.*?\/podcast\/(.*?)\/.*/),'#1'],
            [new RegExp(/.*?\/(podcast)/),'#1'],
            [new RegExp(/.*?\/(blogs)/),'#1'],
            [new RegExp(/.*?\/blogs\/(.*?)\/.*/),'#1'], 
            [new RegExp(/.*?\/(forum)/),'#1'],
            [new RegExp(/.*?\/forum\/(.*?)\/.*/),'#1'], 
            [new RegExp(/.*?\/(noticias)/),'#1'],
            [new RegExp(/.*?\/noticias\/(.*?)\/.*/),'#1'], 
            [new RegExp(/.*?\/(video)/),'#1'],
            [new RegExp(/.*?\/video\/(.*?)\/.*/),'#1']
 
      ];
 
      for(var i=0;i<rgs.length;i++){
            var match = rgs[i][0].exec(urlStr);
            if(match != null){
                  
                  var categoria = rgs[i][1];
                  
                
                  var r = new RegExp(/#([0-9])/);
                  while(r.exec(categoria) != null){
                        var m = r.exec(categoria);
                        categoria = categoria.replace("#"+m[1],match[parseInt(m[1])]);
                  }
                  
                  i = rgs.length;
                  //Alert para exibir categoria
                  //alert(categoria);
                  return categoria;
            }
      }
      return "";
}

function goTo(target, current, total) {	
    if(!isNaN(target) && (target <= total && target > 0)) {		
		var oldUrl = location.href;		
		var urlParts = oldUrl.split("/");
		var fileName = urlParts[urlParts.length-1];		
		var fileNameParts = fileName.split(".");
		var fileExtension = fileNameParts[fileNameParts.length-1];
		fileNameParts[fileNameParts.length-1] = "";
		var fileNameWithoutExtension = fileNameParts.join(".");		
		var nextLocation = fileNameWithoutExtension.substring(0, fileNameWithoutExtension.length-2) + target + "." + fileExtension;
		location.href = nextLocation;
	}
    else {
        alert("Página inválida");
	}
	return;
}

function aumentaFonte() {
	var fontSizeString = $("#centroR2 p").css("font-size");
	try {
		var fontSizeNumber = fontSizeString.substring(0, fontSizeString.indexOf("px"));
		if(fontSizeNumber >= 16) return;
		else $("#centroR2 p").css("font-size", ++fontSizeNumber + "px");
	} catch(er) {}
}

function diminuiFonte() {
	var fontSizeString = $("#centroR2 p").css("font-size");							
	try {
		var fontSizeNumber = fontSizeString.substring(0, fontSizeString.indexOf("px"));						
		if(fontSizeNumber <= 12) return;
		else $("#centroR2 p").css("font-size", --fontSizeNumber + "px");
	} catch(er) {}
}

jQuery.cookie = function(name, value, options) {
	/*
		$.cookie('the_cookie'); // get cookie
		$.cookie('the_cookie', 'the_value'); // set cookie
		$.cookie('the_cookie', 'the_value', { expires: 7 }); // set cookie with an expiration date seven days in the future
		$.cookie('the_cookie', '', { expires: -1 }); // delete cookie
	*/
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// NOTE Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};	

jQuery.geogo = function(url) {
	if(window.location != url)
	{
		location.replace(url);
	}
};

jQuery.georedirect = function(finalLocation) {
	if(finalLocation != null)
	{	
		if(finalLocation == "Minas Gerais")
			$.geogo("http://casa.abril.com.br/regional/bh/index-regional.shtml");
		else /*if(finalLocation == "Nacional")*/
			$.geogo("http://casa.abril.com.br/geoindex.shtml");		
	}
};

jQuery.geolocalization = function(stateName, options) {		
	var autoredirect = null;
	var callback     = null;

	if(options)
	{
		autoredirect = (options.autoredirect === false) ? false : true;
		callback     = (options.callback) ? options.callback : null;
	}

	if(stateName != null)
		$.cookie('EstadoUsuario2', stateName, { path: "/" });
	
	var userStateAutomatic = $.cookie('EstadoUsuario');
	var userStateManual    = $.cookie('EstadoUsuario2');
	var finalLocation     = null;
	
	if(userStateManual == null)
	{
		if(userStateAutomatic == null)
		{			
			//retrieve user location via proxypass
			$.ajax({
				type: "GET",
				url: "http://casa.abril.com.br/ferramentas/geo/index.php",
				async: false,
				success: function(msg) {
					userStateAutomatic = $.cookie('EstadoUsuario');
					finalLocation      = userStateAutomatic;
				}
			});
		}
		else {
			finalLocation = userStateAutomatic;
		}
	}
	else
	{
		finalLocation = userStateManual;
	}
	
	if(finalLocation != null)
		finalLocation = finalLocation.replace("+", " ");

	if(autoredirect)
		$.georedirect(finalLocation);
	else if (callback)
		callback(finalLocation);
};

$(document).ready(function(){
	var location = $.geolocalization(null, {autoredirect: false, callback: function(location){
		if(location == "Minas Gerais")
			$("#publiregional").show();
	}});
});