/**
 * MedPortica Home Page Hero
 */

(function(){
  var container;
  var indicatorsContainer;
  var tiles = [];
  var currentIndex = 0;
  var length = 1;
  var TIMEOUT_SPEED = 5000;
  var currentTileElement;
  var timeout;
  var currentlyChanging = false;
  var minimumISITime = 60000;

  var init = function(){
    container = $('hero').observe('mouseover', pause).observe('mouseout', resume);
    var link = currentTileElement = container.down('a');
    var image = link.down('img');
    indicatorsContainer = new Element('div',{id:'hero-tile-indicators'});
    container.insert({after:indicatorsContainer});

    var tile = {
      img: {
        src: image.readAttribute('src'),
        width: image.readAttribute('width'),
        height: image.readAttribute('height'),
        loaded: false
      },
      url: link.readAttribute('href'),
      onclick:link.readAttribute('onclick')
    };

    image.remove();
    firstImageLoadedInterval = setInterval(function(){
      if(tile.img.loaded){
        link.insert(
          new Element('div').addClassName('hero-img').setStyle({
            'width': tile.img.width+'px',
            'height': tile.img.height+'px',
            'background': 'url("'+tile.img.src+'") no-repeat'
          })
        );
        clearInterval(firstImageLoadedInterval);
      }
    }, 100);


     var isi = container.down('.hero-isi');
     if(isi==undefined){
       tile.isi = false;
     }
     else{
       var isiElement = isi.down('.content');
			var pi = isi.down('.pi-links-container').childElements('h6');

			var pi_links = [];
			pi =pi.reverse();
			for (var i=0; i<pi.length; i++) {
				var pi_obj = {
					title: pi[i].down('a').innerHTML,
					url: pi[i].down('a').readAttribute('href')
				};

				pi_links.unshift(pi_obj);
			}

			tile.prescribingInformation = pi_links;


       tile.isi = {
         element: isi,
         content: isiElement.innerHTML,
         scrollingISI: false
       };
     }

    tiles.unshift(tile);

    var url = '/portal/com/novartis/pharma/novartisquo/portlets/herotiles/generateJSONObject.do';
    var t=$('hero_slot_1');
    if(t){ url+='?brand_1_slot='+ t.value; }
    new Ajax.Request(url, {
      method: 'get',
  	  onSuccess: function(transport){
  	    var additionalTiles = eval('('+transport.responseText+')');
  	    tiles = tiles.concat(additionalTiles);
  	    length = tiles.length;

        for(var c=0; c<length; c++){
          prepareTile(tiles[c]);
        }

        indicatorsContainer.setStyle({
          paddingLeft: Math.floor((indicatorsContainer.getWidth() - (tiles.length * 21))/2) + 'px'
        });

        setupTimeout();
	    }
  	});
  };

  var prepareTile = function(tile){
    var img = new Image();
    img.onload = function(){
      tile.img.loaded = true;
    };
    img.src = tile.img.src;

    if((tile.isi!=false) &&((typeof tile.isi)!="object")){
      tile.isi = {
        content: tile.isi,
        element: false,
        scrollingISI: false
      };
    }

    tile.indicator = new Element('div').addClassName('hero-tile-indicator').observe('click',function(){
      next(tile);
    });
    if(tile==tiles[currentIndex]) tile.indicator.addClassName('hero-tile-indicator-active');
    indicatorsContainer.insert(tile.indicator);
  };

  var setupTimeout = function(){
    clearTimeout(timeout);
    var currentTile = tiles[currentIndex];
    if(!currentTile.isi){
      timeout = setTimeout(function(){next();}, TIMEOUT_SPEED);
    }
    else if(!currentTile.isi.scrollingISI){
      var startTime = new Date();
      currentTile.isi.scrollingISI = new ScrollingISI(currentTile.isi.element,{showHoverState:false, onComplete:function(){
        var currentTime = new Date();
        var time = (currentTime.getTime() - startTime.getTime());
        var remainingTime = minimumISITime-time;

        if(remainingTime>0) {
          timeout = setTimeout(function(){next();}, remainingTime);
        }
        else{
          next();
        }

      }});
    }
  };

  var next = function(tile){
    if(currentlyChanging) return;
    currentlyChanging = true;

    clearTimeout(timeout);

    var nextIndex;
    var nextTile;
    if(tile==undefined){
      nextIndex = (currentIndex>=(length-1)) ? 0 : currentIndex+1;
      nextTile = tiles[nextIndex];
    }
    else{
      nextTile = tile;
      nextIndex = tiles.indexOf(tile);
    }

    if(!nextTile.img.loaded){
      timeout = setTimeout(next, 500);
      return;
    }

    tiles[currentIndex].indicator.removeClassName('hero-tile-indicator-active');
    var currentISI=tiles[currentIndex].isi;
	if(currentISI && currentISI.scrollingISI && currentISI.scrollingISI.effect){
		currentISI.scrollingISI.effect.cancel();
	}

    var nextTileElement = tileElement(nextTile);
    transition(nextTileElement, function(){
      currentlyChanging = false;

      currentTileElement.remove();
      currentTileElement = nextTileElement;
      currentIndex = nextIndex;
      if(currentIndex>=length) currentIndex = 0;
      nextTile.indicator.addClassName('hero-tile-indicator-active');
      setupTimeout();
    });

  };

  var tileElement = function(tile){
    var e = new Element('div').addClassName('hero-tile').insert(
      new Element('a',{href: tile.url,onclick:tile.onclick}).insert(
        new Element('div').setStyle({
          'width': tile.img.width+'px',
          'height': tile.img.height+'px',
          'background': 'url("'+tile.img.src+'") no-repeat'
        }).addClassName('hero-img')
      )
    );
    if(tile.isi!=false){
      tile.isi.scrollingISI = false;
			tile.pi = new Element('div').addClassName('pi-links-container');
			if (typeof tile.prescribingInformation == 'string') {
				tile.pi.insert(new Element('h6').insert(new Element('a',{href:tile.prescribingInformation, target:'_blank'}).update('Full Prescribing Information')));
			} else {
				for (var i=0; i<tile.prescribingInformation.length; i++) {
					var pi = tile.prescribingInformation[i];
					tile.pi.insert(new Element('h6').insert(new Element('a',{href:pi.url, target:'_blank'}).update(pi.title)));
				}
			}
      tile.isi.element = new Element('div').addClassName('hero-isi')
        .insert(new Element('h5').update('Indication & Important Safety Information'))
				.insert(tile.pi)
        .insert(new Element('div').addClassName('content').update(tile.isi.content));
      e.insert(tile.isi.element);
    }
    return e;
  };

  var transition = function(next, callback){
    next.setStyle({opacity:0}).fade({
      duration:1,
      from: 0,
      to: 1,
      afterFinish: callback
    });
    container.insert(next);
  };

  var pause = function(){
    clearTimeout(timeout);
  };

  var resume = setupTimeout;

  Event.observe(document, "dom:loaded", init);

})();

