﻿$(document).ready(function(){
 
  var DOMAIN = '';   
 
  $(".news-container").scrollable({ circular: true }).autoscroll({ interval: 5000 });
 
  //if element exists
  if($('#cinema-combo').length > 0) {
    var combobox = $('<select />').attr({
        'id'   : 'exibition-combo',
        'name' : 'exibition'
        });
    var html = '';
    if($('.sub-menu ul.M2 li').length > 1) {
    $('.sub-menu ul.M2 li').each(function () {
      if($(this).find('span').html() === null) {
        html = $(this).find('a').html();
      } else {
        html = $(this).find('span').html();
      }
 
 
      if(window.location.toString() == 'http://www.alegro.pt/' + $(this).children('a').attr('href')) {
        combobox.append($('<option />').val($(this).children('a').attr('href')).html(html).attr('selected','selected'));      
      } else {
        combobox.append($('<option />').val($(this).children('a').attr('href')).html(html));
      }
 
 
    });
    
    $('#cinema-combo').append(combobox);
    }
}
 
  $('.top-menu ul li a, #DwFooter .float-right ul li a').bind('click',function (e) {
    e.preventDefault();
    window.open($(this).attr('href'));
  });
 
  if($('#map').length > 0 ) load();
 
 
  /*
   * Main Menu Javascript
   */ 
 
  var topMenu = $('.main-menu ul li');
  var effect  = function () {
 
    var li = $(this);
    var ul = $(this).children('ul');
 
    topMenu.not('.main-menu ul li ul li').bind('mouseenter', effect);
 
    topMenu.children('ul').fadeOut(0);
    li.unbind('mouseenter');
 
    if(ul.css('display') == 'none') {
      
      if(ul.width() < li.width()) {
        ul.width(li.width());
      }
      
      ul.fadeIn(400);
      
      ul.bind('mouseleave', function (e) {
        var offset = {
          top : ul.offset().top-30,
          right : (ul.offset().left + ul.width()),
          bottom : (ul.offset().top + ul.height()),
          left : ul.offset().left
        };
        if(e.pageX < offset.left || e.pageX > offset.right || e.pageY < offset.top || e.pageY > offset.bottom) {
          li.bind('mouseenter',effect);
          ul.fadeOut(0);
        }
      });
    } else {
      topMenu.not('.main-menu ul li ul li').bind('mouseenter', effect);
    }    
  }
  
  topMenu.not('.main-menu ul li ul li').bind('mouseenter', effect);
  
  $('.main-menu-switch').bind('mouseenter', function () {
    topMenu.children('ul').fadeOut(0);
    topMenu.not('.main-menu ul li ul li').bind('mouseenter', effect);
  });
 
  /*
   * Menu Style JS
  */ 
 
 
  /*
   * Arrows JS
  */ 
 
  function addArrowsN (elem) {
 
    //exceptions
    if(elem.children('#map').length > 0 || elem.hasClass('no-scroll')) return false;
 
    var wrapper = $('<div />').addClass('wrapper');
 
    if( elem.children('.wrapper').length == 0 && !elem.hasClass('newsCol1') && !elem.hasClass('newsCol2')) {
        var html = elem.children();
        elem.children().remove();
        elem.append(wrapper);
        elem.children(wrapper).append(html);
    }
 
    $('.wrapper', elem).height(elem.height());
    
    $('.wrapper', elem).jScrollPane({
      showArrows:true,
      maintainPosition:false,
      scrollbarWidth: 7,
      dragMinHeight: 42,
      dragMaxHeight : 42,
      arrowSize: 10
    });
    
  }
 
  function addArrows (elem) {
 
      //no scroll mode
      if(elem.hasClass('no-scroll')) return false;
 
      /* adds arrows */
      var wrapper   = $('<div />').addClass('wrapper'),
          arrowUp   = $('<div />').addClass('arrow-up'),
          arrowDown = $('<div />').addClass('arrow-down'),
          speed     = 200,
          scrollVal = 60;
      
       
       elem.scrollTop(0);
 
      //exception for google maps
      if(elem.children('#map').length > 0) return false;
 
      if(elem.children('.wrapper').length==0) {
        var html = elem.children();
        elem.children().remove();
        elem.append(wrapper);
        elem.children(wrapper).append(html);
      }     
      
      if(elem.height() < elem.children('.wrapper').height()) {
        if(elem.children('div.arrow-up').length == 0 && elem.children('div.arrow-down').length == 0) {
          elem.append(arrowUp).append(arrowDown);
        }
        elem.scrollTop(0);
        elem.children('div.arrow-up').css({'top':'10px'});
        elem.children('div.arrow-down').css({'bottom':'10px'});
 
      } else {
        elem.children('div.arrow-up').remove();
        elem.children('div.arrow-down').remove();
      }
 
      arrowUp.bind('click',function () {
        var scroll        = $(this).parent().scrollTop(),
            bottom        = parseInt(arrowDown.css('bottom')),
            top           = parseInt($(this).css('top')),
            wrapperHeight = $(this).parent().children('div.wrapper').height(),
            height        = $(this).parent().height(),
            newScroll     = 0;
 
        if( scroll > 0 ) {
          ((scroll-scrollVal) < 0) ? newScroll = scroll : newScroll = scrollVal;
          $(this).parent().animate({scrollTop:(scroll-newScroll)}, speed);
          arrowUp.animate({'top':(top-newScroll)+'px'},speed);
          arrowDown.animate({'bottom':(bottom+newScroll)+'px'},speed);
        }
      });
 
      arrowDown.bind('click',function () {
        var scroll        = $(this).parent().scrollTop(),
            bottom        = parseInt($(this).css('bottom')),
            top           = parseInt(arrowUp.css('top')),
            wrapperHeight = $(this).parent().children('div.wrapper').height(),
            height        = $(this).parent().height(),
            newScroll     = 0;
 
        if(scroll < (wrapperHeight-height)) {
          ((scroll+scrollVal) < (wrapperHeight-height)) ? newScroll = scrollVal : newScroll = (wrapperHeight-height) - scroll;
          $(this).parent().animate({scrollTop:(scroll+newScroll)},speed);
          arrowUp.animate({'top':(top+newScroll)+'px'},speed);
          arrowDown.animate({'bottom':(bottom-newScroll)+'px'},speed);
        }        
      });
      
      /*
      $('#DwContent .newsCol2').bind('mousewheel', function (event, delta) {
        if(delta == 1) {
          arrowUp.trigger('click');
        } else {
          arrowDown.trigger('click');
        }
      });
      */ 
  }
 
  $('.right-border-column').each(function () {
    addArrowsN($(this));
  })
  
   
  /*
  * Lista de lojas
  */  
  var nodata = false;
  try {
    var newsItemCat   = window.$newsItems.newsItemCat,
        newsItemId    = window.$newsItems.newsItemId,
        newsItemTitle = window.$newsItems.newsItemTitle,
        activateCat   = -1,
        activateStore = ($(document).getUrlParam("OpenStore") != '') ? $(document).getUrlParam("OpenStore") : 0;
  } catch (e) {
    nodata = true;
  } finally {
    if(!nodata) {
      var ItemCatList = new Array(),
          exists = false,
          counter = 0,
          y = 0,
          newsItem = new Array();
 
      for(i=0;i<newsItemCat.length;i++) {
        exists = false;
        for(y=0;y<ItemCatList.length;y++) {
          //checks for existant value in array
          if(ItemCatList[y] == newsItemCat[i]) {
            exists = true;
            break;
          }
        }
        //if non existant adds it
        if(!exists) {
          ItemCatList[counter] = newsItemCat[i];
          counter++;
          exists = false;
        }
 
        if (activateStore == newsItemId[i]) {
          activateCat = y;
        }
 
        newsItem[i] = {
          id: newsItemId[i],
          cat: y,
          title: newsItemTitle[i]
        }
 
      }
      
      /*sort categories*/
      var ItemCatListTemp  = ItemCatList.slice(0),
          newsItemCatAssoc = new Array();
      
      ItemCatListTemp.sort();
 
      for(i=0;i<ItemCatListTemp.length;i++) {
        for(y=0;y<ItemCatList.length;y++) {
          if(ItemCatList[y] == ItemCatListTemp[i]) newsItemCatAssoc[y] = i;
        }
      }     
      
      ItemCatList = ItemCatListTemp;
 
      for(i=0;i<newsItem.length;i++) {
        //sets the new sorted index for category array
        newsItem[i].cat = newsItemCatAssoc[newsItem[i].cat];
      }
 
      //sets new activateCat id
      activateCat = newsItemCatAssoc[activateCat];
 
      //console.log(newsItem);
 
      //adds three column to the content
      $('#DwContent')
      .append($('<div />').addClass('newsCol1').append($('<div />').addClass('wrapper').append('<ul />')))
      .append($('<div />').addClass('newsCol2').append($('<div />').addClass('wrapper').append('<ul />')))
      .append($('<div />').addClass('newsCol3'))
      .append($('<div />').addClass('clear'));
 
      /*
       * uncommented code
      */  
      var col1 = $('#DwContent .newsCol1 ul'),
          col2 = $('#DwContent .newsCol2 ul'),
          col3 = $('#DwContent .newsCol3'),
          url  = DOMAIN + 'Default.aspx?ID=18&PID=7&Action=1&NewsId=',
          showItem = function (e) {
            $(this).addClass('selected2').siblings('li').removeClass('selected2');
            
            $.ajax({
              type: 'GET',
              url: url+e.data.newsItem.id,
              beforeSend: function () {
                col3.html('');
              },
              success: function (result) {
                if (result != '') {
                  addArrowsN(col3.append($('<div />').html(result)));
                }
              }              
            });                       
          },
          showCatItems = function (e) {
            $(this).addClass('selected1').siblings('li').removeClass('selected1');
            var col2Div   = $('div.newsCol2'),
                storeItem;
 
            col2.children().remove();
 
            for(i=0;i<newsItem.length;i++) {
              if(newsItem[i].cat == e.data.cat) {
                storeItem = $('<li></li>').bind('click',{newsItem:newsItem[i]},showItem).html(newsItem[i].title);
                if(newsItem[i].id == activateStore) {
                  storeItem.addClass('activate');
                }
                col2.append(storeItem);
              }
            }            
            (col2.children('li.activate').length > 0 ) ? col2.children('li.activate').trigger('click').removeClass('activate') : col2.children('li:first').trigger('click');
            activateStore = 0;            
            addArrowsN(col2Div);            
          };
 
      var catItem;
      for(i=0;i<ItemCatList.length;i++) {
        catItem = $('<li></li>').bind('click',{cat:i},showCatItems).html(ItemCatList[i]);
        if(activateCat == i) catItem.addClass('activate');
        col1.append(catItem);
      }
      if (col1.children('li.activate').length > 0 ) {
        col1.find('li.activate').trigger('click').removeClass('activate');
      } else {
        col1.find('li:first').trigger('click');
      }
    }
  }
 
  /*
   *  cinema form code to redirect
  */  
  $('#exibition-combo').change(function (){
    var exibition = $("option:selected", this).val();
    
    window.location.replace(exibition );
 
  });
 
 
  var LoadWindow = function (e) {
    
    e.preventDefault();
    var modal,
        href = $(this).attr('href');
 
    if($('.generic-modal').length > 0) {
      modal = $('div.generic-modal');
    } else {
      modal = $('<div />').addClass('generic-modal')
              .append($('<div />').addClass('generic-modal-close').bind('click',function () {$('.generic-modal').overlay().close()}))
              .append($('<div />').addClass('generic-modal-content'));
      $('#DwContent').prepend(modal);
    }
 
    modal.overlay({
          // some expose tweaks suitable for modal dialogs
          expose: {
                  color: '#000',
                  loadSpeed: 200,
                  opacity: 0.5
          }
    });
 
    modal.overlay().load();
 
    $.ajax({
      type: 'GET',
      url: DOMAIN + href,
      beforeSend: function () {},
      success: function (result) {
        modal.children('div.generic-modal-content').html(result);
      },
      complete: function () {
        addArrowsN($('.generic-modal .m-right-col'));
        addArrowsN($('.generic-modal .m-left-col'));
      }
    });
    
    //ajax request for pageID
    
  }  
 
  var pageID = 10;
  $('.openWindow').bind('click',{page:pageID},LoadWindow);
 
  var eCheckbox   = ($('#Email_67')[0]) ? $('#Email_67') : $('#Email_223'),
      AccessUserEmail  = ($('#AccessUserEmail_67')[0]) ? $('#AccessUserEmail_67') : $('#AccessUserEmail_223'),
      emailHidden = $('#email-hidden');
 
  if( emailHidden.val() != '' && emailHidden.val() != 'on') AccessUserEmail.val(emailHidden.val());
  eCheckbox.attr('checked','checked');
  eCheckbox.bind('click',function (e) {e.preventDefault()})
 
  /*
   * Newsletter JS Code
   */  
  $('#newsletter-submit').live('click', function () {
    $(this).parent('form').submit();
  });
  $('#newsletter-email').live('focus', function () {
    if($(this).val() == 'endere?o de email') $(this).val('');
  });
  $('#newsletter-email').live('blur', function () {
    if($(this).val() == '') $(this).val('endere?o de email');
  }); 
 
  $('#newsletter-aprove').html( $('#newsletter-customfields-table tr:last td:last').html() + $('#newsletter-customfields-table tr:last td:first').html());
  $('#newsletter-customfields-table tr:last').remove();
  /*
   * gets font-family and font-size from sibling
   */
  /* $('.main-menu ul li a').not().css('font-size') */
 
 
  //if($('.sub-menu ul').length
 
/*
 * Adds Arrows to paragraph contents
 */
 
/*
 * sets home page columns straight
 */
 var height = 0;
 $('.ps-content').each(function () {
   if($(this).height() > height) height = $(this).height();
 })
 $('.ps-content').height(height);
 
 height = 0;
 var mediaHeight = 0;
 $('.news-container .ps-content').each(function () {
   if($(this).outerHeight(true) > height) height = $(this).outerHeight(true);
 })
 $('.news-container .ps-media').each(function () {
   if($(this).outerHeight(true) > mediaHeight) mediaHeight = $(this).outerHeight(true);
 }) 
 itemHeight = height+mediaHeight;
 if(itemHeight>241)
   $('.news-container, .news-container .item').height(itemHeight);
 
 var logo_anchor = $('.logo a');
 
 if( logo_anchor.attr('title') == "1") {
   logo_anchor.attr('href',logo_anchor.attr('href') + '&id=2');
 }
 
});
 
var LoadDayEvents = function (Page) {
 
  if($('.flash-modal').length > 0) {
    var modal = $('div.flash-modal');
  } else {
    var modal = $('<div />').addClass('flash-modal');
    $('#DwContent').prepend(modal);
  }
  
  modal.overlay({
	// some expose tweaks suitable for modal dialogs
	expose: {
		color: '#000',
		loadSpeed: 200,
		opacity: 0.5
	}
  });
  
  var PageID = ($(document).getUrlParam("ID") == '126') ? 108 : 30; 
  
  modal.overlay().load();
  modal.flashembed("Files/System/alegro/flash/agenda_detalhe.swf",{
    Page: Page,
    PageID: PageID
  });
}
 
var closeWindow = function () {
  $('.flash-modal').overlay().close();
}
function OverLayerHomePage(fundo, opacidade, posicaoTopo, posicaoEsq, MediaPath, altura, largura) {
  if($('#flash-overlay').length > 0) {
    var flash = $('div#flash-overlay');
  } else {
    var flash = $('<div id="flash-overlay"><div id="backgroundColor"></div></div>');
    $('body').prepend(flash);    
  }

  $('body').prepend('<div id="exposeMask" style="position: fixed; top: 0px; left: 0px; width: 100%; filter:alpha(opacity=' + opacidade + '); height: 100%; display: block; opacity: ' + parseInt(opacidade)/100 + '; z-index: 999998; background-color: ' + fundo + ';" ></div>')
 
  if (MediaPath.substr((parseInt(MediaPath.length)-3),(parseInt(MediaPath.length))) != 'swf') {
    $('div#flash-overlay').html('<img src="' + MediaPath + '" alt="Overlayer Image" />');
  }
  else {
    flashembed('#flash-overlay', { src: MediaPath, 'wmode': 'transparent' });
  }
  $('div#flash-overlay').css({
    'top' : posicaoTopo,
    'left' : posicaoEsq,
    'width' : largura + "px",
    'height' : altura + "px",
    'position' : 'absolute',
    'z-index' : '999999'
  });
  $('#exposeMask').appendTo('div#backgroundColor');
  $("div#flash-overlay object").css({
    "height": altura + "px",
    "width": largura + "px",
    "position": "absolute"
  });
}
function CloseOverlayer() {
  $('#exposeMask').hide();
  $('#flash-overlay').hide();
}

