﻿/* Província Portuguesa da Companhia de Jesus (Jesuítas) */
var TheUrl = "";
var MyLocationBegin = "";
var MyLocationEnd = "";
var MycurrentPageId = "";
var MyImgPath = "";
var MyFolderPath = "";
var sSelectFlag = 0;
 
 
 
// handles the selected thumbnail
var selectedImg = null;
 
 
$(function() {
  //Correct Menus First - Second Level
  if ($("#MainMenu ul ul").length) {
    $("#MainMenu ul ul").appendTo("#SecondLevelMenu");
  }
  else if ($("#HiddenMenu ul").length) {
    $("#HiddenMenu ul").appendTo("#SecondLevelMenu");
  }
  
  if ($.browser.safari)
    resizeTimer = setTimeout(CorrectMainMenu, 100);
  else
    CorrectMainMenu();
  
  //Add by Nuno
  if ($("form[name='subscribe']").length) {
    $("#NewsletterWrapper").css("height","225px");
    $("form[name='subscribe']").parent().wrap('<div id="newsletterDiv"></div>'); 
    $("#ContentWrapper > .ImageRightCols > .ParagraphImage img").wrap('<span id="imagem"></span>');
    $("#ContentWrapper > .ImageRightCols > .ParagraphText a").parent().wrap('<div id="NewsletterList"></div>');
  }
    
  
  // Fixed Boletim dos Jesuítas. Added By Nuno 
  if ($.browser.msie && 7>$.browser.version.substr(0,1)) {
    $("#NewsletterWrapper").parent().css({
      "width":"370px",
      "position":"relative"
    });
    $("#NewsletterText").css({
      "width":"269px"
    });
  }
  if (!$('#newsletterDiv').length) {
   if ($('#NewsletterWrapper').length) {
     $('.ParagraphImage > img').parent().wrap("<div id='BoletimImg'></div>");
     $('.ParagraphImage').css("width","100%");
     $('#BoletimImg').css("padding-left","8px");
     $('#BoletimImg').css("border-left","1px solid #acacad");
     $('#BoletimImg').css("float","right");
     $('#ContentWrapper > div[class="Paragraph ImageRightCols"] > .ParagraphImage').css("text-align","right");
   }
  }
  
  // Correct Menus Column
  $("#SecondLevelMenu ul:last").css("display", "none");
  $("#SecondLevelMenu ul:first").css("display", "block");
  $("#SecondLevelMenu").css("height", ($("#MenusColumn").height()-$("#QuickAccessMenu").height()) + "px");
  
  // #ContentWrapper
  $("#ContentWrapper").height($("#Content").height()-$("#ContentHeader").outerHeight(true));
  $("#ContentWrapper").jScrollPane({showArrows:true});
  $("#PortugalMenu").jScrollPane({showArrows:true});
  
  // Editor templates (code snippets)
  $("div.TableNoBg tr:last, div.TableColorBg tr:last, div.InfoTable table table tr:last").find("td").css({
    'color': '#84bde6',
    'font-weight': 'bold',
    'border-bottom': 'none'
  });
  
  // Video News Paging
  $(".VideosPaging").each(function(e){
    TheUrl = String(window.location);
    MyLocationBegin = TheUrl.slice(0,TheUrl.search(/&currentPage=/) + 13);
    MyLocationEnd = TheUrl.slice(TheUrl.search(/&currentPage=/) + 13, TheUrl.length);
    if(MyLocationEnd.length > 1) {
      MycurrentPageId = MyLocationEnd.slice(0,MyLocationEnd.search(/&/));
      MyLocationEnd = MyLocationEnd.slice(MycurrentPageId.length, MyLocationEnd.length);
    }
    else {
      MycurrentPageId = MyLocationEnd;
      MyLocationEnd = "";
    }
  
    $(".PagingList").append("<a href='" + MyLocationBegin + $(".PagingListDummy a:last").html() + MyLocationEnd + "'>" + $(".PagingListDummy a:last").html() + "</a>");
    $(".CurrentPage").prepend(MycurrentPageId);
  
    MycurrentPageId--;
    $(".PagingBack a").attr( 'href' , MyLocationBegin + MycurrentPageId + MyLocationEnd);
  
    MycurrentPageId = MycurrentPageId + 2;
    $(".PagingForward a").attr( 'href' , MyLocationBegin + MycurrentPageId + MyLocationEnd);
    
    $(".LeftColumn").css({'width':'350px'});
    $(".RightColumn").css({'width':'260px'});
    $("#ContentHeader").css({'border-bottom':'1px solid #acacad'});
  });

  
  checkSocialNetworks();

  if( $( '.topButtons' ).length )
    fixTopLeftButtons();

  /* helpdeskStart - nuno.b - 11/07/2011 (activar hiperligação ao clicar na imagem, problema que ocorria so em IE7) */
    if ($.browser.msie && 9 > $.browser.version.substr(0,1)) {
      $('.ImageRightCols .ParagraphImage').each(function() {
        if ($(this).find('a img').length) {
          $(this).find('a').css({
            'top' : '-12px',
            'right' : '-25px',
            'display' : 'block',
            'position' : 'absolute',
            'border-left' : '1px solid #acacad'
          });
          $(this).find('a span').css('position', 'static');
        }
      });
    }
  /* helpdeskEnd */
});



// Removes the icon if no url if defined
function checkSocialNetworks() {
  $( '.socialNetwork' ).each( function() {
    if( $( this ).attr( 'href' ).replace(/^\s*|\s*$/g,'').length == 0 )
      $( this ).remove();
  });
}



// Fix the top left Buttons
function fixTopLeftButtons() {
  var buttonSpan,
      buttonImg;

  $( '.topButtons' ).each( function( i ) {
    buttonSpan = $( this ).find('span');
    buttonImg = $( this ).find('img');

    // is the image's src attribute is defined, remove the text that may be defined, otherwise remove the image
    if( $( buttonImg ).attr( 'src' ).replace(/^\s*|\s*$/g,'').length == 0 ) {
      $( buttonImg ).remove();

      // remove the all div the no image and text are defined
      if( $( buttonSpan ).text().replace(/^\s*|\s*$/g,'').length == 0 ) {
        $( this ).remove();

        // if the first div is removed, place the second button on the first button's position
        if( i == 0 )
          $( '.topButtons' ).css( 'left', '121px' );
      }
      else {
        $( this ).css({ 'padding':'5px', 'height':'14px' });

        // show only teh first 30 characters if the user inserts more than 30 characters
        if( $( buttonSpan ).text().length > 30 )
          $( buttonSpan ).text( $( buttonSpan ).text().substr( 0, 30 ) );
      }
    }
    else
      $( buttonSpan ).remove();
  });
}

 
 
// binds the controls of the horizontal slider and sets the click event on any thumb
function mycarousel_initCallback(carousel) {
  jQuery('.forwardArrow').bind('click', function() {
      carousel.next();
      return false;
  });
 
  jQuery('.reverseArrow').bind('click', function() {
      carousel.prev();
      return false;
  });
  selectedImg = $('#ListGalleryThumbs .ImgSelected');
  setImgsLegend();
  
  if( $('.LeftColumn').height() > $('#ContentWrapper').height() ) {
    $('.NewsItem_Video').height(250);
    $('.NewsItem_Video').jScrollPane({showArrows:true});
  }
  
  $("#ListGalleryThumbs a").click(function() {
    MyImgPath = $(this).children('img').attr('src');
    MyImgPath = MyImgPath.slice((MyImgPath.search(/Files/)-1),MyImgPath.length);
    MyImgPath = MyImgPath.slice(0,MyImgPath.search(/&/));
    MyImgPath = "/admin/public/getimage.aspx?&Image=" + MyImgPath + "&Width=350&Height=235&crop=0";
    $(".NewsItem_Image img").attr('src',MyImgPath);
    
    var liImg = $(this).parent();
    if( selectedImg != null ) {
      $(selectedImg).removeClass('ImgSelected');
    }
    $(liImg).addClass('ImgSelected');
    selectedImg = liImg;
 
    setImgsLegend();
  });
}
 
// updates the thumbnail legend 
function setImgsLegend() {
  $('#actualImg').text($(selectedImg).attr("jcarouselindex"));
  $('#totalImgs').text($("#ListGalleryThumbs li").length);
}
 
function CorrectMainMenu() {
  var actualWidth = 655;
  var totalLIWidth = 0;
  
  // Calculate total width of list items
  $("#MainMenu ul li").css("float","left").find("a").css('margin-top','5px');
  var lis = $('#MainMenu ul li:not(:first)');
  
  lis.each(function(){
    totalLIWidth += $(this).width();
  });
  
  // Work out how much padding we need
  var requiredPadding = Math.round(((actualWidth-totalLIWidth)/lis.length)/2);
  
  // To account for rounding errors, the error is going to be forced into the first tab.
  var roundingErrorFix = (requiredPadding*lis.length*2)+totalLIWidth-actualWidth;
  
  // Apply padding to list items
  var isFirst = true;
  lis.each(function() {
    if(isFirst) {
      $(this).find("a").css('padding-left',requiredPadding-(roundingErrorFix/2)+'px').css('padding-right',requiredPadding-(roundingErrorFix/2)+'px');
      isFirst = false;
    }
    else
      $(this).find("a").css('padding-left',requiredPadding+'px').css('padding-right',requiredPadding+'px');
  });
  
  //Safari and Chrome correction
  if($.browser.safari || $.browser.chrome) {
    $("#MainMenu ul").css("display", "block");
    $("#MainMenu li").css("display", "list-item");
  }
  if ($.browser.msie && 7>$.browser.version.substr(0,1)) {
    $("#MainMenu ul").css("display", "block");
  }
}
 
 
 
function RandomTopGraphic(path) {
  if (path==null) path="";
  path = path.substring(0,path.lastIndexOf("/"));
  $.ajax({
      url: "/Files/GetFolderContents.aspx?Path=" + path,
      success: function(data){
        var xml;
        if ($.browser.msie && typeof data == "string") {
          xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = false;
          xml.loadXML(data);                
        } else {
           xml = data;
        }
        
        var randomnumber=Math.floor(Math.random()*$(xml).find("File").length)
        RandomImage = $(xml).find("File:eq("+randomnumber+")").attr("href");
        $("#HeaderGraphicLogo").css({
          'width': "985px",
          'background-image': "url('" + RandomImage + "')"
        });
      }
  });
}
 
 
 
function CreateGallery(path) {
  folderpath = path.substring(0,path.lastIndexOf("/"));
  $.ajax({
      url: "/Files/GetFolderContents.aspx?Path=" + folderpath,
      success: function(data){
        var xml;
        if ($.browser.msie && typeof data == "string") {
          xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = false;
          xml.loadXML(data);
        } else {
           xml = data;
        }
        if ($("#ListGalleryContainer").length == 0) {
          $(".NewsItem_Video").after('<div id="ListGalleryContainer"></div>');
 
          $("#ListGalleryContainer").after('<div class="arrowsContainer"><a class="reverseArrow" href="javascript:void(0)">&nbsp;anterior&nbsp;</a><span id="actualImg" style="color: #77b6e3; font-weight: bold"></span>&nbsp;|&nbsp;<span id="totalImgs" style="color: #095388; font-weight: bold"></span><a class="forwardArrow" href="javascript:void(0)">&nbsp;seguinte&nbsp;</a></div>');
 
          $("#ListGalleryContainer").append('<ul id="ListGalleryThumbs"></ul>');
 
          $(xml).find("File").each(function(e) {
            PathImg=($(this).attr('href'));
            $("#ListGalleryThumbs").append('<li class="ItemGalleryThumbs" id="ItemGalleryThumb' + e + '"><a><img src="/admin/public/getimage.aspx?&Image='+PathImg+'&Width=60&Height=40&Crop=0" alt="" border=""/></a></li>');
            if (path == PathImg) {
              $("#ItemGalleryThumb" + e).addClass('ImgSelected');
              $('#actualImg').text(e+1);
            }
          });
 
          // sets the pictures horizontal slider
          $('#ListGalleryContainer').jcarousel({
            scroll: 5,
            initCallback: mycarousel_initCallback,
            // This tells jCarousel NOT to autobuild prev/next buttons
            buttonNextHTML: null,
            buttonPrevHTML: null
          });
        }
      }
  });
  /*$("#ListGalleryThumbs img").click(function() {
    alert("mostrar foto");
    MyImgPath = $(this).children('img').attr('src');
    MyImgPath = MyImgPath.slice((MyImgPath.search(/Files/)-1),MyImgPath.length);
    MyImgPath = MyImgPath.slice(0,MyImgPath.search(/&/));
    MyImgPath = "/admin/public/getimage.aspx?&Image=" + MyImgPath + "&Width=350&Height=235&crop=0";
    $(".NewsItem_Image img").attr('src',MyImgPath);
  });*/
}
 
function PopulateSelect(filepath, destination) {
  $.ajax({
    url: "/" + filepath,
    success: function(data){
        var xml;
        if ($.browser.msie && typeof data == "string") {
          xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = false;
          xml.loadXML(data);
        } else {
           xml = data;
        }
        $(xml).find("item").each(function(e) {
          $(destination).append('<option value="' + $(this).text() + '">' + $(this).text() + '</option>');
        });
        $(destination).sSelect({ddMaxHeight: '220px'});
    }
  });
}
 
function ShowMonths() {
  $("div.Month:contains('Janeiro'):first").css("visibility", "visible");
  $("div.Month:contains('Fevereiro'):first").css("visibility", "visible");
  $("div.Month:contains('Março'):first").css("visibility", "visible");
  $("div.Month:contains('Abril'):first").css("visibility", "visible");
  $("div.Month:contains('Maio'):first").css("visibility", "visible");
  $("div.Month:contains('Junho'):first").css("visibility", "visible");
  $("div.Month:contains('Julho'):first").css("visibility", "visible");
  $("div.Month:contains('Agosto'):first").css("visibility", "visible");
  $("div.Month:contains('Setembro'):first").css("visibility", "visible");
  $("div.Month:contains('Outubro'):first").css("visibility", "visible");
  $("div.Month:contains('Novembro'):first").css("visibility", "visible");
  $("div.Month:contains('Dezembro'):first").css("visibility", "visible");
}
function ShowMonthsV2() {
  $("div.Month:contains('Janeiro'):first").css("display", "block");
  $("div.Month:contains('Fevereiro'):first").css("display", "block");
  $("div.Month:contains('Março'):first").css("display", "block");
  $("div.Month:contains('Abril'):first").css("display", "block");
  $("div.Month:contains('Maio'):first").css("display", "block");
  $("div.Month:contains('Junho'):first").css("display", "block");
  $("div.Month:contains('Julho'):first").css("display", "block");
  $("div.Month:contains('Agosto'):first").css("display", "block");
  $("div.Month:contains('Setembro'):first").css("display", "block");
  $("div.Month:contains('Outubro'):first").css("display", "block");
  $("div.Month:contains('Novembro'):first").css("display", "block");
  $("div.Month:contains('Dezembro'):first").css("display", "block");
}
