
tj$.carousel = { 
           //=========================================================
           //Settable parameters: Web Admin: set them here:
           //---------------------------------------------------------
           interfeed_interval : 300000,  //msec
           picture_load_yield : 500,     //msec
           maximum_slots : 6, 
           initial_snap : 4,             //since that to start roll
           slot_vertical_padding : 4,
           image_left_position : 6,
           image_texts_gap : 4,
           title_height : 10,          //,px, slot title, text
           message_left : 14,          //,px
           submove_height : 2,         //,px
           submove_duration : 20,      //,msec
           pause_duration : 4000,      //,msec
           data_feed_url : 'workouts/pulljs.php',
           uploads : 'uploads',           //file feed folder
           //More fine tune CSS done in style attribute in code below:
           //=========================================================
           

           //Non-settable parameters, calculated later:
           feeds_count : 0,
           move_duration:0,          //calculated from other parameters
           slot_height:0,            //calculated from CSS
           nextPicture:-1,           //picture index to download to
                                     //depository.
                                     //Is a flag: when < 0, means
                                     //   feeding completed and -nextPicture is
                                     //   a number of uploads fed if any.

           weels:[],
           images:[],                //depository of pictures kept in
                                     //"background" and to be source for weels
                                     //after weel turns.
           images_slot:[],           //slot to which image is attached.
           //Movement parameter:
           //flg_moving : false,
           head:null,
           frontWeel:0,
           filled_slots:0
   }; //tj$.carousel = { 


   //===================================================================
   //Setup placeholders for carousel:
   //-------------------------------------------------------------------
   //Runs in file-namespace: plays role of constructor for tj$.carousel:
   (function (){
       var c = tj$.carousel;
       //tj$.digs( "started building carousel controls" );
       if( c.initial_snap > c.maximum_slots ) c.initial_snap = c.maximum_slots;
       for( var j=0; j<2; j++ ){
           //Weel wrap:
           var ww = document.getElementById('weel_'+j);
           var weel = { wrap:ww, img:[], msg:[], texts:[], ttl:[], dte:[], slots:[] }; 
           c.weels[j]=weel;
           var h = Math.ceil(parseInt(ww.style.height) / c.maximum_slots);
           c.slot_height = h;

           var slot_contents_height = h - c.slot_vertical_padding * 2;
           c.slot_contents_height = slot_contents_height;
           c.image_height = Math.ceil( c.slot_contents_height * 0.95);
           if( c.image_height < 10 ) c.image_height = 10;
           c.image_width = c.image_height;

           c.move_duration = c.submove_duration * h / c.submove_hight;
           var w = parseInt(ww.style.width);
           ww.style.zIndex = '' + (parseInt(ww.parentNode.style.zIndex) + 3-j);
           //Populate weels with slots with images and message-divs:
           for( var i=0; i<c.maximum_slots; i++ ){

                //Create div-slot: contains image and texts:
                var slot = document.createElement('div');
                weel.slots[i]=slot;
                var s = slot.style;
                s.position = "absolute";
                s.height = slot_contents_height + 'px'; 
                s.width = w + 'px';  
                s.top = (h * i + c.slot_vertical_padding) + 'px';
                s.fontSize = '10px';


                //IE possibly breaks here:
                //slot.addClassName('customize_horizontal_reverse');
                //slot.addClassName = 'customize_carousel_slot';

                //slot.setAttribute( 'class', 'tweet-status' ); //'customize_horizontal_reverse customize_carousel_slot status' );

                    var texts = document.createElement('div');
                      //texts.setAttribute( 'class', 'tweet-commet' ); //workout_texts' ); //customize_horizontal_reverse customize_carousel_message_slot' );
                      s = texts.style;
                      s.position = "absolute";
                      var verticalShift = 0;
                      left = c.image_width + c.image_left_position + c.image_texts_gap;
                      s.left = left + 'px';
                      s.top = '4px';
                      var texts_height = slot_contents_height;
                      s.height = texts_height + 'px';
                      var texts_width = (w - left);

                      s.width = texts_width + 'px';
                      s.visibility = 'hidden';
                      c.weels[j].texts[i] = texts;
                      slot.appendChild(texts);

                         
                         //texts - Add image to serve as a background image for div texts.
                         img = document.createElement('img');
                         img.src = 'img/tweet_full_back.png'; //'img/twitter-t.png';
                         s = img.style;
                         s.position = "absolute";
                         s.top = '-4px';
                         s.left = '0px';
                         //s.height = texts_height + 'px';
                         //s.width = texts_width + 'px';
                         texts.appendChild(img);
                           

                         var texts_content_width = texts_width - c.message_left;

                         //texts - Add a placeholder for text-message:
                         var msg = document.createElement('div');
                           msg.setAttribute( 'class', 'tweet-c-roll' );
                           s = msg.style;
                           s.position = "absolute";
                           s.left = c.message_left + 'px';
                           verticalShift = 2;
                           //s.backgroundColor = '#AACCCC';
                           //s.color = '#FFFFFF';
                           //s.fontSize = '10px';
                           var top = 13;
                           s.top = top +'px';
                           s.height = (texts_height - top) + 'px';
                           //s.width =  texts_content_width + 'px';
                           s.width =  (texts_content_width - 20) + 'px'; //patch
                           s.textAlign = 'left';
                           s.fontWeight = 'normal';
                           c.weels[j].msg[i] = msg;
                           texts.appendChild(msg);

                         //title - Add a placeholder for text-message:
                         var ttl = document.createElement('div');
                           ttl.setAttribute( 'class', 'tweet-t-roll' ); 
                           s = ttl.style;
                           s.position = "absolute";
                           s.left = c.message_left + 'px';
                           verticalShift = 0;
                           top = 0;
                           s.top = top +'px';
                           s.height = (c.title_height - top) + 'px';
                           var title_width = Math.ceil( texts_content_width * .65);
                           s.width =  title_width + 'px';
                           s.textAlign = 'left';
                           s.fontWeight = 'bold';
                           c.weels[j].ttl[i] = ttl;
                           texts.appendChild(ttl);

                         //date - Add a placeholder for text-message:
                         var dte = document.createElement('div');
                           //dte.setAttribute( 'class', 'roll-date ie' );
                           s = dte.style;
                           s.position = "absolute";
                           verticalShift = 0;
                           s.left = (c.message_left + title_width) + 'px';
                           top = 0;
                           s.top = top +'px';
                           s.height = (c.title_height - top) + 'px';
                           s.width =  Math.ceil( texts_content_width * .25 )+ 'px';
                           s.textAlign = 'right';
                           s.fontWeight = 'lighter';
                           s.color = "#AAAAAA";
                           c.weels[j].dte[i] = dte;
                           texts.appendChild(dte);

                ww.appendChild(slot);
           } //i
       } //j
   }());
   //-------------------------------------------------------------------
   //Setup placeholders for carousel:
   //===================================================================
   //tj$.digs( "finished building car controls" );
  


   //Main purpose: activate src property for carousel.images storage array:
   //from carousel.response list:
   tj$.carousel.collectPictures = function () {
        var c = tj$.carousel; //TODO this.
        var r = c.response;
        //tj$.digs('entered collectPictures');
        if( !r || r.count < 1 ) {
            if( c.feeds_count == 0 ){
                //tj$.digs('This is a landing time ... Keep trying until first response is arrieved:');
                setTimeout('tj$.carousel.collectPictures()', 500 ); 
            }
            return; //Faulty feed. Skip.
        }
        var n = c.nextPicture < 0 ?  0  :  c.nextPicture;
        var ixF = c.frontWeel;
        if( !c.images[n] ) {    //Create image place holder in div-slot:
                    c.images[n] = document.createElement('img');
                    c.images_slot[n] = null;
                    s = c.images[n].style;
                    s.position = "absolute";
                    s.visibility = 'hidden';
                    s.top = '1px';
                    s.left = c.image_left_position + 'px';
                    s.height = c.image_height + 'px';
                    s.width = c.image_width + 'px';
        } 
        var img = c.images[n];
        img.src = ( r[n].file_name.substring(0,4) == 'http' ?  r[n].file_name  : tj$.carousel.uploads + '/'+ r[n].file_name );
        //main debug: tj$.digs( "set image source to" + img.src );
        //The rest of the code: builds first weel and initiates move.
        c.initial_snap = Math.min( c.initial_snap, r.count );

        //Show initial_snap-slots before carousel started moving:
        if( c.initial_snap > n ) {
            //img.style.visibility = 'visible';
            //var slot = c.weels[ ixF ].slots[n];

            if( c.feeds_count == 0 ) {
                //c.weels[ ixF ].msg[n].innerHTML = r[n].user_message;
                c.weels[ ixF ].msg[n].innerHTML = '<a href=\"http://www.yogatailor.com?pmode=week&usr='+r[n].user_id+'\" title=\"Click to see ' + r[n].name + '\'s weekly log\">' + r[n].user_message + '</a>';
                //c.weels[ ixF ].ttl[n].innerHTML = r[n].name;
                c.weels[ ixF ].ttl[n].innerHTML = r[n].name;
                c.weels[ ixF ].dte[n].innerHTML = r[n].posted_date;
                //Don't make images in back-wheel visible during upload:
                c.weels[ ixF ].texts[n].style.visibility = 'visible';
                tj$.carousel.reattach_image(n, ixF, n);

                //c.weels[0].msg[0].style.visibility = 'visible';
                //c.head = (n+1) % r.count;
                c.filled_slots = n+1;
                if( n == c.initial_snap - 1 ) {
                   //Initial snap is filled. Ignight moving sequence.
                   c.head = (n+1) % r.count;
                   //tj$.digs( "sequence of movements ingnited" );
                   setTimeout('tj$.carousel.startMove()',tj$.carousel.pause_duration);
                } 
            }
        } 

        n++;
        if( n < r.count ) {
           c.nextPicture = n;
           //Favor first snap and give normal time for the rest of the images:
           //Interpicture interval:
           var download_wait = n < c.initial_snap && c.feeds_count ? 10 : c.picture_load_yield;  
           setTimeout('tj$.carousel.collectPictures()', download_wait ); 
        }else{
           c.nextPicture = -n;
           c.feeds_count++;
           //tj$.digs( "stopped collecting pictures" );
           //console.log( "feed " + c.feeds_count + " completed");
        }
   };

   tj$.carousel.reattach_image = function(img_ix, wheel_to_ix, slot_to_ix){
        var i=img_ix;
        var w=wheel_to_ix;
        var s=slot_to_ix;

        var car   = tj$.carousel;
        var wheel = car.weels[w];
        var slot_to = wheel.slots[s];
        var img = car.images[i];
        //tj$.digs(wheel.slots);
        if( car.images_slot[i] ) {
            car.images_slot[i].removeChild(img);
            car.images_slot[i].style.visbility = 'hidden';
        }  
        slot_to.appendChild(img);
        slot_to.style.visibility = 'visible';
        wheel.img[s]=i;
        car.images_slot[i] = slot_to;
        img.style.visibility = 'visible';
   };


   tj$.carousel.startMove = function (){ 
        var c = tj$.carousel;
        var h = c.head;
        if( !c.images[h] || ( c.feeds_count > 0 && c.nextPicture >= 0 )) {
            //Don't move while feeding:
            setTimeout('tj$.carousel.startMove()',tj$.carousel.pause_duration);
            return;
        }

        //Remember filled slots for front weel for future projection
        //to backweel:
        //c.weels[c.frontWeel].filled_slots = c.filled_slots;
      
        //Prepare hidden top image:
        var backWeel = c.frontWeel == 0 ? 1 : 0;
        var b = c.weels[backWeel];

        //b.msg[0].innerHTML = c.response[h].user_message;
        b.msg[0].innerHTML = '<a href=\"http://www.yogatailor.com?pmode=week&usr='+c.response[h].user_id+'\" title=\"Click to see ' + c.response[h].name + '\'s weekly log\">' + c.response[h].user_message + '</a>';
        b.msg[0].style.visibility = 'visible';
        b.ttl[0].innerHTML = '<a href=\"http://www.yogatailor.com?pmode=week&usr='+c.response[h].user_id+'\" title=\"Click to see ' + c.response[h].name + '\'s weekly log\">' + c.response[h].name + '</a>';
        b.ttl[0].style.visibility = 'visible';
        b.dte[0].innerHTML = c.response[h].posted_date;
        b.dte[0].style.visibility = 'visible';
        b.texts[0].style.visibility = 'visible';
        tj$.carousel.reattach_image(h, backWeel, 0);

        c.head =  Math.floor( (h + 1 ) % c.response.count ) ;

        //Initiate move:
        setTimeout('tj$.carousel.move()',tj$.carousel.move_duration); 
   }; 

   tj$.carousel.move = function () {
        var c = tj$.carousel;
        var s = c.weels[c.frontWeel].wrap.style;
        var t = parseInt(s.top);
        t += c.submove_height;
        if( t > c.slot_height ){
            c.swapWraps();
            setTimeout('tj$.carousel.startMove()',c.pause_duration);
            return;
        }
        s.top = t + 'px';
        setTimeout('tj$.carousel.move()',c.submove_duration );
   };

   tj$.carousel.swapWraps = function () {
        var c=tj$.carousel;
        var backWeel = c.frontWeel == 0 ? 1 : 0;
        var b = c.weels[backWeel];
        var f = c.weels[c.frontWeel];

        //Project front slots to back slots:
        filled_slots1 = Math.min(c.maximum_slots, c.filled_slots+1);

        var w=filled_slots1-1;
        var last_front_image = -2;
        if( f.img[w] || f.img[w] == 0 ) {
            //We need last_front_image index:
            //filled_slots exceedes real filled index by 2. 
            //Hence, w may be not point to filled slot at start up:
            last_front_image = f.img[w];
        } 

        for( var i=1; i<filled_slots1; i++ ){
            //b.img[i].src = f.img[i-1].src;

            b.msg[i].innerHTML = f.msg[i-1].innerHTML;
            b.ttl[i].innerHTML = f.ttl[i-1].innerHTML;
            b.dte[i].innerHTML = f.dte[i-1].innerHTML;
 
            //Unhide background:
            //b.img[i].style.visibility = 'visible';
            b.msg[i].style.visibility = 'visible';
            b.dte[i].style.visibility = 'visible';
            b.ttl[i].style.visibility = 'visible';
            b.texts[i].style.visibility = 'visible';

            //Hide front:
            //f.img[i-1].style.visibility = 'hidden';
            f.msg[i-1].style.visibility = 'hidden';
            f.ttl[i-1].style.visibility = 'hidden';
            f.dte[i-1].style.visibility = 'hidden';
            f.texts[i-1].style.visibility = 'hidden';

            tj$.carousel.reattach_image(f.img[i-1], backWeel, i);
            if( last_front_image == f.img[i-1] ) last_front_image = -2;

        }

        //Hide last front image if exists and not be shown in back wheel:
        if( last_front_image > -1 ) c.images[last_front_image].style.visibility = 'hidden';
        
        f.msg[w].style.visibility = 'hidden';
        f.ttl[w].style.visibility = 'hidden';
        f.dte[w].style.visibility = 'hidden';
        f.texts[w].style.visibility = 'hidden';


        //Swap z-indices for back and front wraps:
        b = b.wrap.style;
        f = f.wrap.style;
        var zindex = parseInt(f.zIndex);
        b.zIndex = '' + (zindex+1);
        f.zIndex = '' + (zindex-1);
        b.zIndex = '' + zindex;

        //Lift former front up:
        f.top = b.top;

        //Record front index:
        c.frontWeel = backWeel; 

   };


   tj$.carousel.feeder = function(){
       var c = tj$.carousel;
       if( c.nextPicture < 0 ){
           //Start collect puctures independently on update flow:
           //Give update flow little, 1000, bonus:
           //tj$.digs('Picture Collection is inactive. Ignighting it from feeder. 1000.');
           setTimeout( c.collectPictures, 1000);
       }
       //Don't wait window.onload event: try async, do callback to feeder to keep updates alive:
       //tj$.digs('set car to be fed after ' + c.interfeed_interval);
       tj$.inject( c.data_feed_url, c.interfeed_interval, 'true', tj$.carousel.feeder);
    };

    //Init feeders:
    //Start inside window.onload event, try async, do callback to feeder to keep updates alive:
    //Sometimes, landing does not produce roll. Perhaps something overrides window.onload event.
    //tj$.inject(tj$.carousel.data_feed_url, -1, true, tj$.carousel.feeder);
    //Don't use this event for now. Just ignight feeder now:
    //Apparently: was a bug: true instead of 'true':
    tj$.inject( tj$.carousel.data_feed_url, 0, 'true', tj$.carousel.feeder);
    /*
    (function() {
         var x = document.createElement('script');
         x.setAttribute('async', 'true');
         x.setAttribute('type', 'text/javascript');
         x.src = tj$.carousel.data_feed_url;
         document.documentElement.firstChild.appendChild(x);
         tj$.carousel.feeder();
    )();
    */


//Knowledge base: 
//To cash images: Response.Cache.SetExpires(System.DateTime.Now.AddDays(30));

