$(function() { 
  BrowserDetect.init();
  if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6" && (window.location.href.indexOf("default.aspx") > -1 || window.location.href.indexOf(".aspx") == -1))
  {
    $("#divDestaquesNoticiasHome").css("width","300px");
    $("#divDestaquesBlogsHome").css("width","300px");
    
    
    $($("#comunidade_forum div.comColumn")[0]).css("margin-left","0px");
    $($("#comunidade_blogs div.comColumn")[0]).css("margin-left","0px");   
  }
  //ViewNoticias();

  $("#form_comentarios").validate({
    rules: {
      txt_name: "required",
      txt_email: {required: true, email: true},
      txt_titulo: "required",
      txt_texto: "required"
    },
    messages: {
      txt_name: "*",
      txt_email: {
        required: "*",
        email: "*" },
      txt_titulo: "*",
      txt_texto: "*"
    }  
  });   
  qs = new Querystring();
  if (qs.get("imprimir") == null)
  {
    //esconder ou mostrar o top + vistos e as outras noticias
    path = window.location.pathname.toString();
    if (path != "/" && path.toLowerCase() != "/default.aspx")
    {
      //fora homepage
      if (qs.get("channelid") != null && qs.get("channelid") != "")
      {
        //RenderPartial("channelproperties",qs.get("channelid"),"","TemplateIdMasterpageOutrasNoticias","UltimasNoticias",$("#divOutrasNoticias").empty()[0].id,"");
        //$("#divOutrasNoticias").show(); 
        //$("#topLidosMain").show();     
      }
    }
    else
    {
      //na homepage
      //$("#divOutrasNoticias").hide(); 
      //$("#topLidosMain").hide();        
    }

    //verificar se algum menu vem expandido via URL (menu)
    auxMenu = qs.get("menu");
    if (auxMenu != null && auxMenu != "")
    {
      ExploreMenu(auxMenu,"","");
    }
    ShowMenuState(""); 
  }
});

//por o título da página de acordo com a página onde se está
function setPageTitle()
{
  if ($("#pageTitle").length > 0 && $("#pageTitle").val().length > 0)
    document.title += " - "+$("#pageTitle").val();    
}

function ViewDestaque(channelid,contentid,img,titulo,lead)
{
  $("#destaqueCentralLink")[0].href = "artigodetalhe.aspx?channelid="+channelid+"&contentid="+contentid;
  $("#destaqueCentralTitulo")[0].href = "artigodetalhe.aspx?channelid="+channelid+"&contentid="+contentid;
  $("#destaqueCentralTitulo")[0].innerHTML = titulo;
  $("#destaqueCentralImagem").unbind("click");
  $("#destaqueCentralImagem").bind("click",function() { gotoUrl('artigodetalhe.aspx?channelid='+channelid+'&contentid='+contentid); });
  //setTimeout("$('#destaqueCentralImagem').css('background-image','url("+img+")');", 100);
  $("#destaqueCentralImagem").css('background-image','url('+img+')');
}

function ViewDestaqueCanal(channelid,contentid,img,titulo,lead)
{
  $("#destaqueCentralLinkCanal")[0].href = "artigodetalhe.aspx?channelid="+channelid+"&contentid="+contentid;
  $("#destaqueCentralTituloCanal")[0].href = "artigodetalhe.aspx?channelid="+channelid+"&contentid="+contentid;
  $("#destaqueCentralTituloCanal")[0].innerHTML = titulo;
  $("#destaqueCentralImagemCanal").unbind("click");
  $("#destaqueCentralImagemCanal").bind("click",function() { gotoUrl('artigodetalhe.aspx?channelid='+channelid+'&contentid='+contentid); });  
  //setTimeout("$('#destaqueCentralImagemCanal').css('background-image','url("+img+")');", 100);
  //$("#destaqueCentralImagemCanal").css('background-image','url('+img+')');
  //$("#destaqueCentralImagemCanal").css("background-image",""+img+"");
  $('#destaqueCentralImagemCanal').css('background-image','url("'+img+'")'); 
}

function ChangeMainImg(imgId, w, h, srcPrincipal, titulo, channelid, contentid)
{

var width =(+w);
var height = (+h);
//var srcMainImg = document.getElementById("destaqueCentralImagemCanal").src;
var srcMainImg = document.getElementById("destaqueCentralImagemCanal").style.backgroundImage;
var srcThumbImg = srcPrincipal;

//w = 292
//h = 213

document.getElementById("destaqueCentralImagemCanal").style.backgroundImage = "url("+srcThumbImg+")";

document.getElementById("destaqueCentralLinkCanal").href = "artigodetalhe.aspx?channelid=" + channelid + "&contentid=" + contentid;
document.getElementById("destaqueCentralTituloCanal").href = "artigodetalhe.aspx?channelid=" + channelid + "&contentid=" + contentid;
document.getElementById("tituloDestaque").innerHTML = titulo;

}
			
//quando entramos em algum canal, mostra o estado no menu
function ShowMenuState(channelid)
{
  p = this.path.toString().substr(1);
  
  if (p == "blogs.aspx") p = "blogsposts.aspx";
  
  if (channelid == "")
  {
    qs = new Querystring();
    channelid = qs.get("channelid");
  }
  if (channelid != null && channelid != "")
  {
    isMenu = false;
    $("#menu ul li a[@onclick]").each(function() {
      if ($(this).attr("onclick").toString().indexOf(channelid) == -1)
      {
        $(this).removeClass("active");
      }
      else
      {
        isMenu = true;
        $(this).addClass("active");
        GetSubMenus(channelid, p, '');
      }
    });
    
    if (!isMenu)
    {
      $.ajax({url:"/AJAX/menu.aspx", 
	      type:"POST",
	      dataType:"text",
        data:{request: "getchannelparent", channelid: channelid},
	      success:function(result){	    
          $("#menu ul li a[@onclick]").each(function() {
            if ($(this).attr("onclick").toString().indexOf(result) == -1)
            {
              $(this).removeClass("active");
            }
            else
            {
              $(this).addClass("active");
              GetSubMenus(result, p, '');            
            }
          });	      
          $("#subMenu ul li a").each(function() {
            if ($(this).attr("onclick").toString().indexOf(channelid) == -1)
              $(this).removeClass("active");
            else
              $(this).addClass("active");  
          }); 	        	   	    
//          auxSubMenu = qs.get("exploresubmenu");
//          if (auxSubMenu != null && auxSubMenu == "1")
//          {
//            ExploreSubMenu(channelid, p);
//          }                  
	      },
	      error:function(req,error,ex){			  	      			    
	      }
      });
    }
  }
}

//mudar o logo para o da homepage ou para o interior
function SwitchLogo(channelid)
{
  if (channelid == "home")
  {
    $("#logoInt").hide();   
    $("#logoHome").show();
  }
  else
  {
    $("#logoInt").show();   
    $("#logoHome").hide();  
  }
}

//mudar a tag zahir para o da homepage ou para o interior
function SwitchPub(channelid)
{
//  if (channelid == "home")
//  {
//    $("#zahirInt").hide();   
//    $("#zahirHP").show();
//  }
//  else
//  {
//    $("#zahirInt").show();   
//    $("#zahirHP").hide();  
//  }
}

//mostra a divShow e esconde todas as divList que não a divShow
function SwitchDiv(divList,divShow)
{
//  if (divShow == "divNoticias_Ultimas")
//  {
//    $("#divDestaquesNoticiasHome").css("height","650px");
//  }
//  else
//  {
//    $("#divDestaquesNoticiasHome").css("height","520px");
//  }  
//  
//  if (divShow == "divBlogs_Ultimas")
//  {
//    $("#divDestaquesBlogsHome").css("height","520px");
//  }
//  else
//  {
//    $("#divDestaquesBlogsHome").css("height","");
//  }    
  
  arrDivList = divList.split(',');
  for(i=0;i<=arrDivList.length-1;i++)
  {
    $("#"+arrDivList[i]).hide();
  }
  $("#"+divShow).show();
  
}

//mostrar a próxima div de uma lista de id de divs separado por virgulas
function SwitchNextDiv(divList)
{
  arrDivList = divList.split(',');
  showIndex = 0;
  for(i=0;i<=arrDivList.length-1;i++)
  {
    if ($("#"+arrDivList[i]).css("display") == "block")
    {
      showIndex = i;
      $("#"+arrDivList[i]).hide();
    }
  }
  if ($("#"+arrDivList[showIndex+1]).length > 0)
  {
    $("#"+arrDivList[showIndex+1]).show();
  }
  else
  {
    $("#"+arrDivList[0]).show();
  }
}

/*
Ao clicar num canal de notícias executa esta função
para refrescar os painéis AJAX: destaques centrais, destaques notícias, outras notícias
e mostrar o UC de top + lidos

O ideal era quando se explora um canal esconder o que está na homepage, pois para quando se quiser
ver a homepage não ser preciso refrescar a página, ser só mostrar as coisas da homepage e esconder a não necessárias
*/
function ExploreSubMenu(channelid, aspx, channelIdBeachLiveTV, contentidArtigo, nomeSubCanal)
{
//  path = window.location.pathname.toString();
//  if (path != "/" && path.toLowerCase() != "/default.aspx")
//  {
//    window.location.href = "Default.aspx?channelid="+channelid+"&exploresubmenu=1";
//  }
//  else
//  {  
				  
//    SwitchLogo(channelid);
//    SwitchPub(channelid);
    
    $("#subMenu ul li a").each(function() {
      if ($(this).attr("onclick").toString().indexOf(channelid) == -1)
        $(this).removeClass("active");
      else
      {
        $(this).addClass("active");  
//    		WRP_SECTION = $("#menu ul li a[@class='active']")[0].innerHTML;
//				WRP_SUBSECTION = $(this)[0].innerHTML;            
//		    w_counter;
//		    if(wreport_ok==1){w_counter = new wreport_counter(WRP_SECTION, WRP_SUBSECTION, WRP_ID, WRP_ACC, WRP_CHANNEL, WRP_SECTION_GRP, WRP_SUBSECTION_GRP);
//		    w_counter.add_content(WRP_CONTENT);
//		    w_counter.count();}            
      }
    }); 
    
    //POR ISTO NO CODE BEHIND A MOSTRAR
    //$("#topLidosMain").show();  
    if(channelid == channelIdBeachLiveTV || nomeSubCanal.indexOf("Beach Live TV")>=0)
        window.location.href = "artigodetalhe.aspx?channelid="+channelid+"&contentid="+contentidArtigo;
    else
        window.location.href = aspx+"?channelid="+channelid+"&exploresubmenu=1";
//    $("#divDestaquesCentraisHome").hide();  
//    $("#divDestaquesNoticiasHome").hide();    
    //RenderPartial("channelproperties",channelid,"","TemplateIdHomepageDestaquesCentrais","DestaquesCentrais",$("#divDestaquesCentrais").empty()[0].id,"divDestaquesCentraisWait");
    //RenderPartial("channelproperties",channelid,"","TemplateIdHomepageDestaquesNoticias","DestaqueNoticias,UltimasNoticias",$("#divDestaquesNoticias").empty()[0].id,"");
    //RenderPartial("channelproperties",channelid,"","TemplateIdMasterpageOutrasNoticias","UltimasNoticias",$("#divOutrasNoticias").empty()[0].id,"");
//    $("#divDestaquesCentrais").show();    
//    $("#divDestaquesNoticias").show();  
//    $("#divOutrasNoticias").show(); 
    
    //falta mostrar o bloco top + lidos  
  //}
}

function ExploreMenu(channelid,aspx,channelIdBeachLiveTV)
{
  if (aspx != null && aspx.length>0)
  {
    //abrir uma página
    window.location.href = aspx+"?channelid="+channelid;
  }
  else
  {
//    path = window.location.pathname.toString();
//    if (path != "/" && path.toLowerCase() != "/default.aspx")
//    {
//      window.location.href = "Default.aspx?menu="+channelid;
//    }
//    else
//    {
      //é homepage
        
      if (channelid == "home")
      {
        window.location.href = "Default.aspx";
//        $("#menu ul li a[@onclick]").each(function() {
//          if ($(this).attr("onclick").toString().indexOf(channelid) == -1)
//            $(this).removeClass("active");
//          else
//            $(this).addClass("active");
//        }); 	
//            
//        SwitchLogo(channelid);
//        SwitchPub(channelid);
//        
//        //IE7 FIX
//        $("#divOutrasNoticias").empty()
//        
//        $("#divDestaquesCentraisHome").show();  
//        $("#divDestaquesNoticiasHome").show();
//        $("#topLidosMain").hide();
//        
//        $("#divDestaquesCentrais").hide();
//        $("#divDestaquesNoticias").hide(); 
//        $("#divOutrasNoticias").hide();
//           
//        $("#subMenu").hide();
//        $($("#subMenu")[0].parentNode).addClass("inHome");
//        $("div.menuBottomBg").show();         
      }
      else
      {  
        //é outro canal
        $("#menu ul li a[@onclick]").each(function() {
          if ($(this).attr("onclick").toString().indexOf(channelid) == -1)
            $(this).removeClass("active");
          else
          {
            $(this).addClass("active");
//		    		WRP_SECTION = $(this)[0].innerHTML;
//    				WRP_SUBSECTION = "";            
//				    w_counter;
//				    if(wreport_ok==1){w_counter = new wreport_counter(WRP_SECTION, WRP_SUBSECTION, WRP_ID, WRP_ACC, WRP_CHANNEL, WRP_SECTION_GRP, WRP_SUBSECTION_GRP);
//				    w_counter.add_content(WRP_CONTENT);
//				    w_counter.count();}            				
          }
        });  
          
        if (aspx == "blogs.aspx") aspx ="blogsposts.aspx";
        
       GetSubMenus(channelid, aspx, channelIdBeachLiveTV);             
      }
     //}
   }
}

function GetSubMenus(channelid, aspx, channelIdBeachLiveTV)
{
  $.ajax({url:"/AJAX/menu.aspx", 
    type:"POST",
    dataType:"text",
    async: false,
    data:{request: "getsubmenu", channelid: channelid},
    success:function(result){	    	   	        
      if (result == "")
      {
        $("#subMenu").innerHTML = "";
        $("#subMenu").hide();
        $($("#subMenu")[0].parentNode).addClass("inHome");
        $("div.menuBottomBg").show();
      }
      else
      { 
        result = eval( "(" + result + ")" );	        
        toAppend = "<ul>";
        for (i=0;i<=result.canais.length-1;i++)
        {	
          toAppend += "<li><a href=\"javascript:void(0)\" onclick=\"ExploreSubMenu('"+result.canais[i].idcanal+"','"+ result.canais[i].aspx +"','"+ channelIdBeachLiveTV +"','"+ result.canais[i].contentidArtigo+"','"+ result.canais[i].nome+"'); return false;\">"+result.canais[i].nome+"</a></li>";  
        }  	          
        toAppend += "</ul>";
        $("#subMenu")[0].innerHTML = toAppend;
        $($("#subMenu")[0].parentNode).removeClass("inHome");
        $("div.menuBottomBg").hide();
        $("#subMenu").show();	      
      }	
    },
    error:function(req,error,ex){			  	      			    
    }
  });
}

var stylesorangeTitle = [ "13px" , "15px" , "17px", "19px"];
var stylesglobalText = [ "10px" , "12px" , "15px", "18px"];

var style = 1;
function changestyle(l_direction) {
	    if ( ( style > 1 ) && ( l_direction == -1 ) ) { style--; }
	    if ( ( style < 4 ) && ( l_direction == 1 ) ) { style++; }
    	
	    try{
		    document.getElementById("orangeTitle").style.fontSize = stylesorangeTitle [style-1];
	        document.getElementById("globalText").style.fontSize = stylesglobalText [style-1];
	        document.getElementById("globalText2").style.fontSize = stylesglobalText [style-1];
    				
	    }catch(e){}

}
function gotoUrl(url)
{
    window.location.href = url;
}

function PesquisaClassificados()
{
  qs = new Querystring();
  channelid = qs.get("channelid");
  refreshcache = "";
  if (qs.get("refreshcache") != null)
    refreshcache = qs.get("refreshcache");  

  window.location.href = "classificados.aspx?channelid="+channelid+"&search="+document.getElementById('txtPesquisaClassificados').value+(refreshcache!=""?"&refreshcache="+refreshcache:"");
}

//buscar o bloco de comunidade escondido on demand
function getComunidadeBlogs()
{
  if ($("#comunidade_blogs")[0].innerHTML.length == 0)
    RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdComunidadeBlogs","UltimosPostsBlogs,BlogPostsMaisComentados,BlogPostsMaisVistos",$("#comunidade_blogs").empty()[0].id,"comunidade_blogs_Wait","BlogPostsMaisComentados_subchannels=1#BlogPostsMaisComentados_first=0#BlogPostsMaisComentados_max=4#BlogPostsMaisComentados_channelid=WC(ChannelIdBlogs)#BlogPostsMaisComentados_order=$$.totalcomentarios desc#UltimosPostsBlogs_channelid=WC(ChannelIdBlogs)#UltimosPostsBlogs_subchannels=1#UltimosPostsBlogs_first=0#UltimosPostsBlogs_max=4");
}                          
//buscar o bloco de tops escondido on demand

function getTopEventos()
{
  if ($("#topseventos")[0].innerHTML.length == 0)
    RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdTopEventos","TopEventosComentados,TopEventos",$("#topseventos").empty()[0].id,"topsnoticias_Wait","TopEventosComentados_first=0#TopEventosComentados_max=4#TopEventosComentados_channelid=WC(ChannelIdEventos)#TopEventosComentados_order=$$.totalcomentarios desc#TopEventos_channelid=WC(ChannelIdEventos)#TopEventos_first=0#TopEventos_max=5");
}                            



function getpagecomultimasblogs(first,max)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageComUltimasBlogs","UltimosPostsBlogs",$("#divComBlogs_Ultimas").empty()[0].id,"divComBlogs_Ultimas_Wait","UltimosPostsBlogs_first="+first+"#UltimosPostsBlogs_max="+max+"#UltimosPostsBlogs_subchannels=1#UltimosPostsBlogs_order=$$.TotalComentarios DESC");
}
function getpageComForumUltimos(first,max)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageComUltimosTopicos","ForumUltimosTopicos",$("#divComForum_Ultimos").empty()[0].id,"divComForum_Ultimos_Wait","ForumUltimosTopicos_first="+first+"#ForumUltimosTopicos_max="+max);
}

//este
function getpageComBlogsMaisVistos(first,max)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageComMaisVistos","BlogPostsMaisVistos",$("#divComBlogs_MaisVistos").empty()[0].id,"divComBlogs_MaisVistos_Wait","RankResults_first="+first+"#RankResults_max="+max);
}
function getpageComTopicosMaisVistos(first,max)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageComMaisVistos","TopicosMaisVistos",$("#divComForum_MaisVistos").empty()[0].id,"divComForum_MaisVistos_Wait","RankResults_first="+first+"#RankResults_max="+max);
}


function getpageComForumMaisComentados(first)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageComMaisComentados","ForumTopicosMaisComentados",$("#divComForum_MaisComentados").empty()[0].id,"divComForum_MaisComentados_Wait","ForumTopicosMaisComentados_subchannels=1#ForumTopicosMaisComentados_first="+first+"#ForumTopicosMaisComentados_order=$$.TotalComentarios DESC");
}
function getpageComBlogsMaisComentados(first)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageComUltimasBlogs","BlogPostsMaisComentados",$("#divComBlogs_MaisComentados").empty()[0].id,"divComBlogs_MaisComentados_Wait","BlogPostsMaisComentados_first="+first+"#BlogPostsMaisComentados_subchannels=1#BlogPostsMaisComentados_order=$$.TotalComentarios DESC");
}


function getpageultimasblogs(first,max)
{
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","","TemplateIdHomepageUltimasBlogs","UltimosPostsBlogs",$("#divBlogs_Ultimas").empty()[0].id,"divBlogs_Ultimas_Wait","UltimosPostsBlogs_first="+first+"#UltimosPostsBlogs_max="+max+"#UltimosPostsBlogs_subchannels=1");
}
function getpageultimasnoticias(first,max,chid)
{
  template = "TemplateIdHomepageUltimasNoticias";
  qs = new Querystring();
  if (qs.get("channelid") != null)
  {
    chid = qs.get("channelid");
    template = "TemplateIdCanalUltimasNoticias";
  }
  RenderPartialWithParams("channelproperties","ChannelIdHomepage","",template,"UltimasNoticias",$("#divNoticias_Ultimas").empty()[0].id,"divNoticias_Ultimas_Wait","UltimasNoticias_first="+first+"#UltimasNoticias_channelid="+chid+"#UltimasNoticias_max="+max+"#UltimasNoticias_subchannels=1");
}

//function Showcalendar()
//{
//  if ($"#divCalendar").css("display") == "block")
//  {
//    $"#divCalendar").css("display") == "none"
//  }
//  else
//  {
//    $"#divCalendar").css("display") == "block"
//  }
//  
//  if($#arrDivList[i]).css("display") == "block")
//  {
//  
//  }
//}
function Showcalendar(id)
{
if ($("#"+id).css("display") == "block" || $("#"+id).css("display") == "")
  $("#"+id).animate({height: "hide",opacity: "hide"},"slow");
else
  $("#"+id).animate({height: "show",opacity: "show"},"slow");

}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
