/**
 * jQuery.homeslider.js
 * homeslider jquery plug-in for Anadin
 * 
 * @author: Eri, Adam (VEC)
 * @version: 1.1
 *
 * This plug-in is to set up a carousel on the home page.
 * 
 * The content is coming from DNN (new content module). The script -
 * based on the current local time - determines which slide to
 * display as default. Then creates link for paging between the
 * slides.
 * 
*/

var imgList = new Array('btn_home_BackPain', 'btn_home_Headache', 'btn_home_JointPain', 'btn_home_Inflammation', 'btn_home_Migraine', 'btn_home_FluSymptoms');
var actImg = 0;

$(document).ready(function() {
    $("#homeslider").homeSlider();
});


$.fn.homeSlider = function(){
    $(this).data('obj', $.extend({}, $.slider))
    $(this).data('obj').init($(this));
}

$.slider = {
    // variables
    opts: {
        slider: null,
        slideWidth: null,
        numberOfSlides: null,
        curTime: null
    },
    timesOfTheDay: new Array,

    init: function(s){
        this.opts.slider = s;
        this.opts.numberOfSlides = s.find("ul li").length;
        this.opts.slideWidth = s.find("ul li").css("width");
        
        this.getTimesOfTheDay();
        
        // set current time
        var d = new Date;
        this.opts.curTime = d.getHours()*60+d.getMinutes();
        
        // set ul width to avoid line brakes
        this.opts.slider.find("ul").css("width", (Math.abs(parseInt(this.opts.slideWidth)) * Math.abs(parseInt(this.opts.numberOfSlides)))+"px");
        
        // show the slide closest to current time
        this.showSlide( this.getClosestTime() );
        
        // generate left-right navigation
        this.generateNavigation();
    },
    
    generateNavigation: function() {
        $self = this;
        
        // left button
        $("<a/>", {
            href: '#',
            'class': 'btnLeft',
            click: function(){ $self.slideEffect('left'); return false; },
            text: ''
        }).appendTo(this.opts.slider);

        // right button
        $("<a/>", {
            href: '#',
            'class': 'btnRight',
            click: function(){ $self.slideEffect('right'); return false; },
            text: ''
        }).appendTo(this.opts.slider);

    },
    
    // iterates thru slides and loads times into timesOfTheDay array in minutes [HH*60+MM]
    getTimesOfTheDay: function() {
        $self = this;
        $.each(this.opts.slider.find("ul li"), function(key){
                // new array for given time
                $self.timesOfTheDay[$self.timesOfTheDay.length] = key;
                // split time by colon
                var t = $(this).find(".slide-time").html().split(":");
                // save time to array
                $self.timesOfTheDay[key] = parseInt(t[0])*60+parseInt(t[1]);
            });
    },
    
    // determines which is the right time-frame based on current local time
    getClosestTime: function() {
        //var closest = Math.abs(this.opts.curTime - this.timesOfTheDay[0]);
        var closestID = 0;
        for (i=0; i<this.timesOfTheDay.length; i++){
            // that genius piece of code would calculate the closest time to the current local time.
                //if (Math.abs(this.opts.curTime - this.timesOfTheDay[i]) < closest){
                //    closest = Math.abs(this.opts.curTime - this.timesOfTheDay[i])
                //    closestID = i;
                //}
                //else { continue; }
            
            // but instead, this not-that-smart code just calculates the timeframe, the current local time is in between
			//console.log(i);
			//console.log(this.opts.curTime);
			//console.log(this.timesOfTheDay[i]);
			//console.log(this.timesOfTheDay[i+1]);
			
			//console.log((this.opts.curTime > this.timesOfTheDay[i]) && ( (this.opts.curTime < this.timesOfTheDay[i+1]) || !this.timesOfTheDay[i+1] ) );
			
			//console.log(" ");
			
            if ( (this.opts.curTime > this.timesOfTheDay[i]) && ( (this.opts.curTime < this.timesOfTheDay[i+1]) || !this.timesOfTheDay[i+1] ) )
                closestID = i
				//console.log(closestID);

        }
        return closestID;
    },
    
    /**
     * Animated scroll to next or previous slide
     *  @param [String] [left|right]
     *  
    */
    slideEffect: function(direction){
        var left = Math.abs(parseInt(this.opts.slider.find("ul").css("left")));
        var width = parseInt(this.opts.slideWidth);
        var ulWidth = parseInt(this.opts.slider.find("ul").css("width"));
        
        // if !first or !last aniamte ul position by this.opts.slideWidth +-
        if ( (direction == "left" && left) || ((direction == "right") && (left + width < ulWidth )) ) {
            /**
             * To avoid the braindead clicking 200/sec on the navigation buttons
             * w/o waiting for the anilation to be finished:
             * After click, the click action will be disabled, then enabled again after the animation
             * 
            */
            $(".btnRight").unbind();
            $(".btnLeft").unbind(); 
            
            // slide animation
            this.opts.slider.find("ul")
                .animate({ 'left': ((direction == "left") ? '+=' : '-=') + width },
                         400,
                        function(){
                            $(".btnRight").bind("click", function(){ $self.slideEffect('right'); return false; });
                            $(".btnLeft").bind("click", function(){ $self.slideEffect('left'); return false; });
                            });
        }
		// change product image coresponding to slider image
		if((direction == 'left') && (actImg > 0)) {
			actImg -= 1;
		} else if ((direction == 'right') && (actImg < 5)) {
			actImg += 1;
		}
		$('#homeProdImg').attr('src', '/Portals/_default/Skins/Anadin/img/' + imgList[actImg] + '.png');
    },
    
    
    /**
     * Show slide w/o animation
     *  Sets the ul postiton: left = -slider size*slideToShow
     *  @param showSlide [Integer]
     *   The number of the slide that has to be shown. Starting with 0;
     * 
    */
    showSlide: function( slideToShow ){
        // modify ul position accordingly
        this.opts.slider.find("ul").css('left', 0-parseInt(this.opts.slideWidth)*slideToShow+"px");
				//set correct product image when opening page
				actImg = slideToShow;
				$('#homeProdImg').attr('src', '/Portals/_default/Skins/Anadin/img/' + imgList[actImg] + '.png');
    }
}
