/* KoldCast Scroller Class
 * Copyright 2009 KoldCast TV
 * @author Sean Hsieh envsn.com
 */
 
 
var PreviewScroller = Class.create({
    initialize: function(name, elementsPer, thumbnailSize) {
        this.name = name;
        this.elementsPer = elementsPer;
        this.tiplimit = elementsPer;
        this.thumbnailSize = thumbnailSize;
        this.pageSize = 0;
        this.currentPage = 1;
        this.maxPages = 0;
        this.container = null;
        this.left = null;
        this.right = null;
        this.object = $(name); // establising the parent object, let's pull the UL of thumbnails and setup the width properly
        
        if (this.object != null) {
            //console.log(this.name + ":" + this.object.childElements().length);
            
			if (this.object.down('div#NewestContainer')) {
                this.container = $('NewestContainer');
                this.container.setStyle({width: '5000px'});
                this.tiplimit = 6;
            }
			else if (this.object.down('div#NewestSeriesContainer')) {
                this.container = $('NewestSeriesContainer');
                this.container.setStyle({width: '2808px'});
                this.tiplimit = 6;
            }
			else if (this.object.down('div#OtherPopularSeriesContainer')) {
                this.container = $('OtherPopularSeriesContainer');
                this.container.setStyle({width: '2808px'});
                this.tiplimit = 6;
            }
			else if (this.object.down('div#YesterdaysMostPopularSeriesContainer')) {
                this.container = $('YesterdaysMostPopularSeriesContainer');
                this.container.setStyle({width: '2808px'});
                this.tiplimit = 6;
            }
            else {
                this.container = this.object.down('ul');
                this.container.setStyle({width: (this.container.childElements().length * this.thumbnailSize) + 'px'});
            }

            this.pageSize = this.elementsPer * this.thumbnailSize;
            this.maxPages = parseInt(this.container.childElements().length / this.elementsPer);
            if ((this.container.childElements().length % this.elementsPer) > 0) this.maxPages += 1;
            
            // establish the actions for the left & right clicks
            if (this.maxPages <= 1) $$('#' + this.name + ' div.paginators')[0].remove();
            else {
            this.left = $$('#' + this.name + ' a.left')[0];
            this.right = $$('#' + this.name + ' a.right')[0];
            this.left.observe('click', this.shiftLeft.bindAsEventListener(this));
            this.right.observe('click', this.shiftRight.bindAsEventListener(this));
            }
            //initialize the tooltips as well
            this.thumbnails = $$('#' + this.name + ' a.tooltip');
            this.descriptions = $$('#' + this.name + ' li p');
            this.titles = $$('#' + this.name + ' li h5');
            for (var i=0;i<this.thumbnails.length;i++) {
            if ((((i+1)%this.tiplimit)==0) || (((i+2)%this.tiplimit)==0)) {
                this.thumbnails[i].tip = new Tip(this.thumbnails[i], this.descriptions[i].innerHTML, {
                    title: this.titles[i].innerHTML,
                    style: 'koldcast',
                    stem: 'rightMiddle',
                    hook: {tip: 'rightMiddle', target: 'leftMiddle'},
                    viewport: 'true',
                    delay: 0.5,
                    offset: {x: 0, y: -10}
                });                
            }
            else {
                this.thumbnails[i].tip = new Tip(this.thumbnails[i], this.descriptions[i].innerHTML, {
                    title: this.titles[i].innerHTML,
                    style: 'koldcast',
                    stem: 'leftMiddle',
                    hook: {tip: 'leftMiddle', target: 'rightMiddle'},
                    viewport: 'true',
                    delay: 0.5,
                    offset: {x:0, y: -10}
                });
            }
                this.thumbnails[i].observe('prototip:shown', function() {
                    this.tip.wrapper.setStyle({'display':'none'});
    				this.tip.wrapper.appear({duration: 0.5});
    				Tips.hideAll();
    			});
    			this.thumbnails[i].observe('prototip:hidden', function() {
                    this.tip.wrapper.setStyle({'display':'block'});
    				this.tip.wrapper.fade({duration: 0.5});
    			});
    			
            }
        }
    },
    shiftLeft: function(e) {
        e.stop();
        var element = Event.element(e);
        if (this.currentPage > 1) {
			this.load_images(this.currentPage-2);
            new Effect.MoveBy(this.container, 0, this.pageSize, {
                duration: 0.5,
                queue: 'end'
            });
            this.currentPage -= 1;
        }
        else {
			this.load_images(this.maxPages-1);
            new Effect.MoveBy(this.container, 0, (-1 * (this.maxPages-1) * this.pageSize), {
                duration: 0.5,
                queue: 'end'
            });
            this.currentPage = this.maxPages;
        }
    },
    shiftRight: function(e) {
        e.stop();
        var element = Event.element(e);
        if (this.currentPage < this.maxPages) {
			this.load_images(this.currentPage);
            new Effect.MoveBy(this.container, 0, (-1 * this.pageSize), {
                duration: 0.5,
                queue: 'end'
            });
            this.currentPage += 1;
        } else {
			this.load_images(0);
            new Effect.MoveBy(this.container, 0, (this.maxPages-1) * this.pageSize, {
                duration: 0.5,
                queue: 'end'
            });
            this.currentPage = 1;
        }
    },
    write: function(message) {
        return this.name + ':' + message;
    },
	load_images: function(ulIndex){
		if (this.container == $('NewestSeriesContainer') || this.container == $('OtherPopularSeriesContainer') || this.container == $('YesterdaysMostPopularSeriesContainer') || this.container == $('NewestContainer'))
		{
			$$('#'+this.container.identify()+' ul')[ulIndex].childElements().each(function(element, i){
				
				image = element.down('a span img');
				
				imagesrc = image.readAttribute('image');
				
				if (imagesrc != '' & imagesrc != null)
				{
					
					image.writeAttribute('src', imagesrc);
					
					image.writeAttribute('image', '');
				}
				
			});
		}
		else
		{
			this.container.childElements().each(function(element, i){
				
				span = element.down('a span');
				
				if (span.readAttribute('image') != '' & span.readAttribute('image') != null)
				{
					span.setStyle({
						backgroundImage: 'url('+span.readAttribute('image')+')'
					});
					
					span.writeAttribute('image', '');
				}
				
			});	
		}
	}
});

var SubscribeGrid = Class.create({
   initialize: function(name) {
       this.name = name;
       this.link = null;
       this.toggled = false;
       this.object = $$('#'+this.name+' .subscribeContainer')[0];
       if (this.object != null) {
           this.link = $$('#'+this.name+' .subscribeContainer .btnSubscribe')[0];
           this.link.observe('click', this.toggle.bindAsEventListener(this));
           
           this.links = $$('#'+this.name+' .subscribeContainer .links')[0];
       }
   },
   
   toggle: function(e) {
       e.stop();
       if (this.toggled) {
           this.toggled = false;
           this.links.setStyle({'display':'none'});
           this.link.removeClassName('active');
       }
       else {
           this.links.setStyle({'display':'block'});
           this.link.addClassName('active');
           this.toggled = true;
       } 
   }
   
});

//Charlie's AJAX Scrollers

function Daily(element, scrollertype) {
    var myAjax = new Ajax.Request('/landingpage/'+scrollertype, {
      method: 'get',
      // onException: function (requester, exception) {
      //     alert(requester + exception)
      // },
      onComplete: function(oReq) {
        var data = oReq.responseText.evalJSON();
        var todaysHTML = '<ul>';
        for (var i = 0; i < data.length; i++) {
            todaysHTML += '<li'
            var radius='';
            if (i==0) {
                if (data.length == 1) {
                 todaysHTML += ' style="border-top:medium none"><a href="' + data[i].url +'"><div class="header top">';
                 radius = ' class="radius8"';
                }
                else {
                 todaysHTML += ' class="first"><a href="' + data[i].url +'"><div class="header top">';
                 radius = ' class="topradius8"';
                }
            }
            else if (i == (data.length - 1)) {
                todaysHTML += ' class="last"><a href="' + data[i].url +'"><div class="header bottom">';
                radius = ' class="bottomradius8"';
            }
            else
                todaysHTML += '><a href="' + data[i].url +'"><div class="header bottom">';
            todaysHTML += data[i].name + '</div><span style="height: ' + 342/data.length + 'px; background-image:url('+ data[i].img_url + ');"'+radius+'></span></a></li>';
          }
         todaysHTML += '</ul>';
         $(element).addClassName('daily');
         $(element).innerHTML=todaysHTML;
        }
    });
}

function Scroller(element, scrollertype, title1, title2) {
    var firstTitle = title1;
    var secondTitle = title2;
    var myAjax = new Ajax.Request('/landingpage/'+scrollertype, {
      method: 'get',
      // onException: function (requester, exception) {
      //     alert(requester + exception)
      // },
      onComplete: function(oReq) {
          var thedata = oReq.responseText.evalJSON();
          var data = '';
          
          if (thedata.videos) { 
           data = thedata.videos;
           firstTitle = thedata.name;//.split(' ')[0];
           secondTitle = '';
          }
          else if (thedata[0].feed) {
              data = thedata[0].feed;
              firstTitle = thedata[0].name;//.split(' ')[0];
              secondTitle = '';
          }
          else {
            data = thedata;
            firstTitle = '<span>' + firstTitle + ' </span>';
         }

          var length = data.length;


          var scrollerHTML = '<div class="header"><h3 class="title">' + firstTitle + secondTitle + ' </h3> <div class="paginators"';
          var url = '';
          var img_url = '';
          var name = '';
          if (length < 7)
           scrollerHTML += 'style="display:none"';
          scrollerHTML += '><a href="#" class="left">left</a> <a href="#" class="right">right</a> </div>';
          if (scrollertype == 'video/json/kctv-featured')
           scrollerHTML += '<div class="subscribeContainer"><a href="#" class="btnSubscribe">Subscribe</a><div class="links"><a href="http://www.koldcast.tv/index.php/featured_rss" onClick="javascript: pageTracker._trackPageview(\'/rssSubscribed/main/featured_rss\');" class="rss">RSS Feed</a><div class="stub"></div></div></div>';

		  
          scrollerHTML += '</div></div><div class="main"><div class="thumbnailsContainer"><ul>';
          for (var i = 0; i < length; i++) {

                  url = data[i].url;
                  img_url = data[i].img_url;
                  name = data[i].name;
                  if (data[i].show_name && !data[i].subtitle)
                    var show_name = data[i].show_name;
                  else if (data[i].subtitle)
                    var show_name = data[i].subtitle;
                  if (data[i].description)
                    var description = data[i].description;
                    
              if (scrollertype == 'talent/json/featured-talent')
                url = "http://centerstage.koldcast.tv" + data[i].url;
            
                scrollerHTML += '<li class="ContentBox_li"><a ';
                if (description)
                 scrollerHTML += 'class="img tooltip"';
                else
                 scrollerHTML += 'class="img"';
				if (scrollertype != 'talent/json/featured-talent')
				 scrollerHTML += 'onclick="Effect.ScrollTo(\'KCLogo\');"';
                scrollerHTML += ' href="' + url + '"><span class="radius8" style="background-image: url(' + img_url + ');"></span><h5>' + name + '</h5></a>';
                if (show_name)
                 scrollerHTML += '<h6>' + show_name + '</h6>';
                if (description)
                 scrollerHTML += '<p>' + description + '</p>';
          }
          scrollerHTML += '</ul></div></div>';
          $(element).addClassName('ContentBox');
          $(element).innerHTML=scrollerHTML;
           var scrolla = new PreviewScroller(element, 6, 156);
          if (scrollertype == 'video/json/kctv-featured')
            var featuredSub = new SubscribeGrid(element);


      }
    });
}