var newsItemsHeadings = {};
var newsItemsContents = {};
var newsItemsIds = {};
var totalItemsCount = 0;
var currentPosition = 1;
var previousPosition = 1;
var moveBackwardAllowed = moveForwardAllowed = false;
var newsTickAllowed = true;
var ticker = null;
var allowEvents = true;
var accessibilityCompatibility = false;

var pe = null;
var menuHasFocus = false;
var currentlyOpenedList = null;

window.onload=setBehaviors;
function setBehaviors(){
 ////////////////////////////////////////////////
  ////////CREAR BUTON PARA DESACTIVAR TODOS LOS EFECTOS Y SCRIPTS (PARA LECTORES DE PANTALLA)///////
  ///////////////////////////////////////////////////
  var scrCompatString = '<button title="Activar compatibilidad con navegación por teclado" class="accessibilityToggleBtn" id="accessibilityToggleBtn" tabindex="0" onclick="toggleAccessibilityCompatibility()">Acceso por teclado</button>';
  $('accessibilityOptions').insert({ 'before': scrCompatString});
 // $('pageSearchForm').insert({ 'before': scrCompatString});



  /////////////////////////////////////////
  //COMPORTAMIENTO MENU PRINCIPAL//////////
  ///////////////////////////////////////
  setMainMenuKeyboardNavigation();

/////////////////////////////////
  ////COMPORTAMIENTO PILARES///////
  /////////////////////////////////
  $$('#nav2 .nav_li_link_level_1').each(function(item) {
      item.onmouseover = function(){item.style.backgroundPosition='bottom left'};
      item.onmouseout = function(){item.style.backgroundPosition='top left'};
  });

  ////////////////////////////////////////////////
  ////////COMPORTAMIENTO NOTICIAS PORTADA///////
  ///////////////////////////////////////////////////
  
  setMainNewsBehaviors();

  //////////////////////////////////////////////
  ///////COMENTAR ARRIBA PARA RESTABLECER NOTICIAS PORTADA CON SCROLL
  /////////////////////////////////////////////////

/////////////////////////////////////////////////////////////
//  ////////////COMPORTAMIENTO NOTICIAS NO DESTACADAS////////////
//    /////////////////////////////////////////////////////////////
      setNewsItemsPositions();

}


function setMainMenuKeyboardNavigation()
{
  var newCount = 300;

  $$('#nav1 .nav_li_level_1').each(function(item) {
      newCount++;
      if(item.firstDescendant().next()!=null)
      {
        item.style.zIndex = newCount;
        
        item.onmouseover = function(){
            item.firstDescendant().next().style.visibility='visible';
            item.firstDescendant().style.backgroundPosition = 'bottom center';
             menuHasFocus = true;
        };
        item.onmouseout = function(){
            item.firstDescendant().next().style.visibility='hidden'
            item.firstDescendant().style.backgroundPosition = 'top center';
            menuHasFocus = false;
        };
      }
  });



  $$('#nav1 .nav_li_link_level_1').each(function(item) {
      newCount++;
          item.style.zIndex = newCount;
        
        item.onmouseover = function(){
           // item.firstDescendant().next().style.visibility='visible';
            item.firstDescendant().next().style.visibility = 'visible';
            item.firstDescendant().style.backgroundPosition = 'bottom center';
             menuHasFocus = true;
             currentlyOpenedList = item.next();
        };

 
       
               item.onfocus = function(){
              //hide currently opened list if it exists 
              if(currentlyOpenedList!=null)
              {
                 currentlyOpenedList.style.visibility = 'hidden';
              }
              menuHasFocus = true;
              item.next().style.visibility = 'visible';
              currentlyOpenedList = item.next();
              item.firstDescendant().next().style.visibility='visible';
        };
        item.onblur = function(){
              pe = new PeriodicalExecuter(checkOpenedMenu, 1); 
              menuHasFocus = false;
              //hide list if focus is not within current list
        };

  });



  $$('#nav1 .nav_li_link_level_2').each(function(item) {
       item.onblur = function(){
         pe = new PeriodicalExecuter(checkOpenedMenu, 1); 
         menuHasFocus = false;
       };
       item.onfocus = function(){
         menuHasFocus = true;
         currentlyOpenedList.style.visibility = 'visible';
       };

       item.onmouseover = function(){
         menuHasFocus = true;
         //currentlyOpenedList.style.visibility = 'visible';
       };
   
 
  });
  
  $$('#nav1 .nav_li_link_level_3').each(function(item) {
       item.onblur = function(){
         pe = new PeriodicalExecuter(checkOpenedMenu, 1); 
         menuHasFocus = false;
       };
       item.onfocus = function(){
         menuHasFocus = true;
         currentlyOpenedList.style.visibility = 'visible';
       };
  });

}

function checkOpenedMenu()
{
  if(!menuHasFocus)
  {
    if(currentlyOpenedList!=null)
    {
      currentlyOpenedList.style.visibility = 'hidden';
    }
  }
  pe.stop();
}

function toggleAccessibilityCompatibility()
{
  accessibilityCompatibility = (accessibilityCompatibility)?false:true;
  if(accessibilityCompatibility)
  {
    unsetMainNewsBehaviors();
  $('accessibilityToggleBtn').title = 'Desactivar compatibilidad con navegación por teclado';
  $('accessibilityToggleBtn').style.backgroundPosition = 'bottom left';
    unsetNewsItemsPositions();
  }
  else
  {
  newsTickAllowed = true
  $('newsControls').style.display = 'block';
  setMainNewsBehaviors();
  $('accessibilityToggleBtn').title = 'Activar compatibilidad con navegación por teclado';
  $('accessibilityToggleBtn').style.backgroundPosition = 'top left';
  resetNewsItemsPositions();
  //  setNewsItemsPositions();
  }
}

function setMainNewsBehaviors()
{
  ticker = new PeriodicalExecuter(newsTick, 14);
  //le quitamos la barra de scroll que se muestra por defecto
  $('da1').style.overflow = 'hidden';

  //escondemos las noticias que no son la primera
  var newsItemsCount = 0;
  $$('#da1 div.newsItemBox').each(function(item){
     newsItemsCount++;
     if(newsItemsCount>1)
     {
       item.style.display = 'none';
     }
     else
     {
       item.style.display = 'block';
     }
     item.firstDescendant().style.border = '0';
     item.firstDescendant().style.height = '200px';
     newsItemsHeadings[newsItemsCount] = item.firstDescendant().firstDescendant().firstDescendant().innerHTML;
     newsItemsIds[newsItemsCount] = item.id;
     item.style.clear = 'both';
  });
  totalItemsCount = newsItemsCount;
  if(totalItemsCount>1)
  {
    moveForwardAllowed = true;
  }
  //generamos un div con los controles para cambiar la noticia

  //dar formato a los controles
  $('da1').style.position = 'relative';
  $('da1').style.zIndex = '50';
  $('newsControls').style.height = '20px';
 // $('newsControls').style.lineHeight = '20px';
  $('newsControls').style.width = '590px';
  $('newsControls').style.padding = '2px 0px 0px 5px';
  $('newsControls').style.background = 'url(/css/portal/images/newsControlsFondoGris.jpg) top left no-repeat';
  $('newsControls').style.position = 'absolute';
  $('newsControls').style.left = '25px';
  $('newsControls').style.top = '307px';//era 287px
  $('newsControls').style.zIndex = '140';
  var controlsString = '';
  for(x=1; x<=newsItemsCount; x++)
  {
    var itemClass = (x==1)?'activeNewsItemControl':'newsItemControl';
    var itemTag = (x==1)?'button':'a href="http://www.udelar.com"';
    var onclickOption = (x!=1)?'onclick="showItem('+x+');return false"':'';
    //$('newsControls').innerHTML+= '<'+itemTag+' title="'+newsItemsHeadings[x]+'" class="'+itemClass+'" tabindex="0" '+onclickOption+'>'+x+'</'+itemTag+'> ';
    //$('newsControls').innerHTML+= '<button type="button" title="'+newsItemsHeadings[x].replace('"','&quot;')+'" class="'+itemClass+'" tabindex="0" '+onclickOption+'>'+x+'</button> ';
    controlsString += '<button type="button" title="'+newsItemsHeadings[x].replace('"','&quot;')+'" class="'+itemClass+'" tabindex="0" '+onclickOption+'>'+x+'</button> ';
  }
    //$('newsControls').innerHTML+= '<button type="button" onclick="moveBackward();" id="moveBackwardBtn">Atrás</button> <button onclick="toggleNewsTick();" type="button" id="pauseBtn">Pausar</button> <button onclick="moveForward();" type="button" id="moveForwardBtn">Adelante</button>';
    controlsString += '<button type="button" onclick="moveBackward();" id="moveBackwardBtn">Atrás</button> <button onclick="toggleNewsTick();" type="button" id="pauseBtn">Pausar</button> <button onclick="moveForward();" type="button" id="moveForwardBtn">Adelante</button>';
//  $('newsControls').innerHTML+= newsItemsHeadings[1];
    $('newsControls').insert(controlsString);
}

function setNewsItemsPositions(){
  var itemsCount = 0;
  $$('#da3 .newsCategoryTitle').each(function(item){
  itemsCount++;
  if(itemsCount>1)
  {
    item.next().style.display = 'none';
    item.style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulCentro.jpg) top left no-repeat';
    item.firstDescendant().style.backgroundPosition = '0px -3px';
  }
  else
  {
    item.style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulArriba.jpg) top left no-repeat';
    item.firstDescendant().style.backgroundPosition = '0px -23px';
  }
  item.onclick = function(){ toggleNewsItemsVisibility(item.id)};
  });
}


function unsetNewsItemsPositions(){
  $$('#da3 .newsCategoryTitle').each(function(item){
    item.next().style.display = 'block';
    item.style.background = 'none';
    item.firstDescendant().style.background = 'none';
    item.firstDescendant().style.padding = '0';
    item.style.color = '#333333';
  item.onclick = function(){ return false};
  });

//cambiamos formato a area de noticias no destacadas

  $('da2_3Box').style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulArriba.jpg) top center no-repeat';
  $('da2_3Box').style.paddingTop = '25px';
  $('da2_3Box').style.height = '295px';

  $('da2_3Box').style.width = '320px';
  $('da3').style.overflow = 'auto';
  $('da3').style.height = '155px';
  $('da3').style.width = '320px';
  $('da3').style.padding = '0';
  //$('da3').style.paddingRight = '20px';
  
  $('da3').style.background = 'url(/css/portal/images/portadaFondoRect320.jpg) top center repeat-y';
//  $('da3').style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulAbajo.jpg) bottom center no-repeat';
 // $('da3').style.paddingBottom = '25px';
 // $('da3').style.height = '130px';

 $$('#da3 .newsItemsBox').each(function(item){
    item.style.margin = '0px';
    item.style.padding = '0px';
})


 
 $$('#da3 .box').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = 'inherit';
    item.style.width = '290px';
})

  $$('#da3 ul.newsItemsList').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = 'inherit';
    
});

  $$('#da3 .newsCategoryFirstItemsBox').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = 'auto';
})

  $$('#da3 .newsCategorySingleItemsBox').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = 'inherit';
})

  $$('#da3 .newsCategoryMiddleItemsBox').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = 'inherit';
})

  $$('#da3 .newsCategoryLastItemsBox').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = 'inherit';
})
}

function resetNewsItemsPositions(){
  var itemsCount = 0;
  $$('#da3 .newsCategoryTitle').each(function(item){
  itemsCount++;
  if(itemsCount>1)
  {
    item.next().style.display = 'none';
    item.style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulCentro.jpg) top left no-repeat';
  }
  else
  {
    item.style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulArriba.jpg) top left no-repeat';
    item.firstDescendant().style.backgroundPosition = '0px -23px';
  }
  item.firstDescendant().style.background = 'url(/css/portal/images/iconoExpandirColapsarAzulSprite.jpg) 5px 5px no-repeat';
  item.firstDescendant().style.padding = '0px 0px 0px 21px';
  item.firstDescendant().style.backgroundPosition = '0px -3px';

  item.onclick = function(){ toggleNewsItemsVisibility(item.id)};
  item.style.color = '#ffffff';
  });

//cambiamos formato a area de noticias no destacadas
  $('da2_3Box').style.background = 'url(/css/portal/images/portadaFondoRect320.jpg) top center repeat-y';
  $('da2_3Box').style.paddingTop = '0px';
  $('da2_3Box').style.height = '320px';



  $('da3').style.overflow = 'visible';
  $('da3').style.height = '180px';
  $('da3').style.background = 'url(/css/portal/images/portadaRect320FondoEncabezadoAzulAbajo.jpg) bottom center no-repeat';
 
 $$('#da3 .box').each(function(item){
    item.style.overflow = 'auto';
    item.style.width = '310px';
})

  $$('#da3 ul.newsItemsList').each(function(item){
    item.style.overflow = 'visible';
    item.style.height = '135px';
})

  $$('#da3 .newsCategoryFirstItemsBox').each(function(item){
    item.style.overflow = 'auto';
    item.style.height = '95px';
})

  $$('#da3 .newsCategorySingleItemsBox').each(function(item){
    item.style.overflow = 'auto';
    item.style.height = '115px';
})

  $$('#da3 .newsCategoryMiddleItemsBox').each(function(item){
    item.style.overflow = 'auto';
    item.style.height = '95px';
})

  $$('#da3 .newsCategoryLastItemsBox').each(function(item){
    item.style.overflow = 'auto';
    item.style.height = '95px';
})
}

function moveBackward()
{
//  ticker.stop();
  //ticker = new PeriodicalExecuter(newsTick, 5);

  if(allowEvents)
  {
  var targetPosition = currentPosition-1;
  if(moveBackwardAllowed)
  {
    if(targetPosition>=1)
    {
      showItem(targetPosition); 
      //currentPosition--;
    } 
  }
  }
}

function moveForward()
{
//  ticker.stop();
 // ticker = new PeriodicalExecuter(newsTick, 5);
  if(allowEvents)
  {
  var targetPosition = currentPosition+1;
  if(moveForwardAllowed)
  {
    if(targetPosition<=totalItemsCount)
    {
      showItem(targetPosition); 
      //currentPosition++;
    } 
  }
  }
//    alert('Move forward: '+moveForwardAllowed +"\n"+ ' Move back: '+moveBackwardAllowed );
}

function newsTick()
{
  var targetItemNumber;
  if(newsTickAllowed)
  {
   if(currentPosition<totalItemsCount)
   {
     targetItemNumber = currentPosition+1;
   } 
   else
   {
     targetItemNumber = 1;
   }
   //previousPosition = currentPosition;
   //currentPosition = targetItemNumber;
   
   showItem(targetItemNumber);

  }
}

function toggleNewsTick()
{
  newsTickAllowed = (newsTickAllowed)?false:true;
  $('pauseBtn').innerHTML = (newsTickAllowed)?'Pausar':'Continuar';
}

function setNavigationBehaviors(targetItemNumber, totalItemsCount)
{
  if(targetItemNumber == 1)//first item
  {
    moveBackwardAllowed = false;
    if(totalItemsCount>1)
    {
      moveForwardAllowed = true;
    }
    else
    {
      moveForwardAllowed = false;
    }
  }
  else
  {
    moveBackwardAllowed = true;
    if(targetItemNumber == totalItemsCount)//last item
    {
      moveForwardAllowed = false;
    }
    else
    {
      moveForwardAllowed = true;
    }
  }
  //alert('move forward: '+moveForwardAllowed+' move back: '+moveBackwardAllowed);
}

function showItem(targetItemNumber)
{
  if(allowEvents)
  {
  currentPosition = targetItemNumber;
  var newsItemsCount = 0;
  var newControlsString = '';
  var itemClass = '';
  var onclickOption = '';
  var itemToShow = null;
  var itemToHide = null;
  $$('#da1 div.newsItemBox').each(function(item){
     newsItemsCount++;
     if(newsItemsCount!=targetItemNumber){
       
       if(newsItemsCount!=previousPosition)
       {
         item.style.display = 'none';
       }
       itemClass = 'newsItemControl';
       onclickOption = 'onclick="showItem('+newsItemsCount+')")';
     }
     else{
       itemToShow = item;
       itemClass = 'activeNewsItemControl';
       onclickOption = '';
     }
     if(newsItemsCount==previousPosition)
     {
       itemToHide = item;
     }
     newControlsString += '<button type="button" title="'+newsItemsHeadings[newsItemsCount]+'" class="'+itemClass+'" tabindex="0" '+onclickOption+'>'+newsItemsCount+'</button> ';

  });
 //disable buttons until animation stops 
  //setNavigationBehaviors(targetItemNumber, totalItemsCount);
  //moveForwardAllowed = moveBackwardAllowed = false;
  allowEvents = false;
          setNavigationBehaviors(targetItemNumber, totalItemsCount);
  itemToHide.fade({
    duration:0.5,
    afterFinish:function(){
      itemToShow.appear({
	duration:0.5,
        afterFinish:function(){
          allowEvents = true;
	}	
      });
    }
  
  });
  //itemToShow.appear();
//  newControlsString += newsItemsHeadings[targetItemNumber];
  var pauseBtnText = (newsTickAllowed)?'Pausar':'Continuar';
  //$('newsControls').innerHTML = newControlsString;
  
  //$('newsControls').innerHTML+= '<button type="button" onclick="moveBackward();" id="moveBackwardBtn">Atrás</button> <button onclick="toggleNewsTick();" type="button" id="pauseBtn">'+pauseBtnText+'</button> <button onclick="moveForward();" type="button" id="moveForwardBtn">Adelante</button> ';
   newControlsString += '<button type="button" onclick="moveBackward();" id="moveBackwardBtn">Atrás</button> <button onclick="toggleNewsTick();" type="button" id="pauseBtn">'+pauseBtnText+'</button> <button onclick="moveForward();" type="button" id="moveForwardBtn">Adelante</button> ';
   $('newsControls').update(newControlsString);
  previousPosition = targetItemNumber;
  }
}

function toggleNewsItemsVisibility(itemId)
{
  var newsItemsCount = 0;

  $$('#da3 .newsCategoryTitle').each(function(item){
     newsItemsCount++;
     if(item.id!=itemId)
     {
       
//       if(newsItemsCount>1){
//         item.next().hide();
//       }else{
//         item.next().slideUp("slow");
//       }
      item.next().style.display = 'none';
     }
     else{
       
      //   item.next().slideDown("slow");
       
       
       item.next().style.display = 'block';
     }

     
  });
}

function unsetMainNewsBehaviors()
{
  newsTickAllowed = false
  ticker.stop();
  //le agregamos la barra de scroll que se muestra por defecto

  $('da1Box').style.height = '340px';


  $$('#da1 div.newsItemsBox').each(function(item){
//modificamos tamanio
     item.style.margin = '5px 0px 5px 0px';
     item.style.width = '630px';
     item.style.height = '300px';
     item.style.padding = '0px';
     item.style.overflow = 'auto';
})

  $$('#da1 div.newsItemTextBox').each(function(item){
//modificamos tamanio
     item.style.width = '215px';
})


//cambiamos la altura
  //escondemos las noticias que no son la primera
  var newsItemsCount = 0;
  $$('#da1 div.newsItemBox').each(function(item){
     item.style.display = 'block';
})
  $('newsControls').style.display = 'none';
  $('newsControls').innerHTML = '';


}

