// home_anim.js

// creates slideshow of images for front page, and adds titles that fly about - all very "whizzy"

jQuery.fn.extend({
  whizzy: function(opt) {
    return this.each(function() {
      jQuery.whizzy.make(this,opt);
    });
  },

  whizzyPage: function(opt) {
    return this.each(function() {
      jQuery.whizzy.addPage(this,opt);
    });
  },

  doWhizzy: function() {
    // start animation (after all images loaded), and apply css
    return this.each(function() {
      jQuery.whizzy.start(this);
    });
  }
});


jQuery.extend({
  whizzy: {

    make: function(element,opts) {
      // element must be a div. this div will contain all created pages.
      // if the div contains some content, it will be removed (later)
      jQuery(element).addClass('whizzyContainer');

      var defaults = {'animate': true,
                      'dropshadow': true,
                      'width': jQuery(element).width(),
                      'height': jQuery(element).height(),
                      'controls': true,
                      'class':''
                     }
      opts = jQuery.extend(defaults,opts);

      // setup vars...
      jQuery(element).data('whizzyOptions',opts)
                     .data('whizzyCurrentPage',0)
                     .data('whizzyAnimate',opts['animate'])
                     .data('whizzyTitleShadow',opts['dropshadow'])
                     .data('whizzyClass',opts['class'])
                     .data('whizzyWidth',opts['width'])
                     .data('whizzyHeight',opts['height']);


    },
    
    addPage: function(el,opts) {
      // el is div.whizzyContainer
      //origimg = jQuery(element).parent().children().first().children('img').first();
      //pageimg = element;

      var defaults = {'img': '',
                      'title': '',
                      'alt': '',
                      'url': '',
                      'durationIn': 'fast',
                      'durationOut': 'fast',
                      'duration': 5000,
                      'titlepos': 'tr',
                      'transition': 'fade'
                     };
      opts = jQuery.extend(defaults,opts);
      
      el = jQuery(el);
      
      wopts = el.data('whizzyOptions');
      
      //iw = jQuery(el).data('whizzyWidth');
      //ih = jQuery(el).data('whizzyHeight');
      
      var html = '<div class="whizzyPage '+wopts['class']+'" style="background-image:url('+"'"+opts['img']+"'"+');background-repeat:no-repeat;width:'+wopts['width']+';height:'+wopts['height']+';">';
      //html += '<img src="'+opts['img']+'" width="'+wopts['width']+'" height="'+wopts['height']+'" border="0" alt="'+opts['alt']+'" />';
      html += '<div class="whizzyTitle"></div></div>';

      el.append(html);

      // hide all pages except the first one...
      thisPage = el.children('div.whizzyPage').last();
      numPages = el.children('div.whizzyPage').size();
      if(numPages > 1) {jQuery(thisPage).hide();}
      
      jQuery.whizzy.setTitle(thisPage,opts['title']);

      // store anim parameters in div...
      jQuery(thisPage).data('whizzyAnimDuration',opts['duration'])
                      .data('whizzyAnimDurationIn',opts['durationIn'])
                      .data('whizzyAnimDurationOut',opts['durationOut'])
                      .data('whizzyTitlePosition',opts['titlepos']);

    },
    /*
    addPage: function(element,opt) {
      // element is the whizzyOuter container div
      if(typeof opt == 'string') {
        opt = {'img': opt};
      }

      if(opt['img']) {
        jQuery(element).append('<img src="'+opt['img']+'" />');
        element = jQuery(element).children().last().hide();
        // element is now the img we have just added
        jQuery.whizzy.makePage(element,opt);
      }

    },
    */
    start: function(element) {
      // element = whizzyOuter container div
      if(jQuery(element).hasClass('whizzyContainer')) {
        jQuery(element).children(':not(div.whizzyPage)').remove();
        jQuery(element).css({'position': 'relative'
                            })
                       .children().css({'position': 'absolute',
                                        'left': '0px',
                                        'top': '0px',
                                        'overflow':'hidden'
                                       });
                       //.children('div.whizzyTitle').css({'position':'absolute','left':'-20px','top':'0px'});

        // wait for all images to load (uses external javscript class)
        //jQuery(element).imagesLoaded(function() { jQuery.whizzy.showNextPage(element); });
        if(jQuery().waitForImages) {
          jQuery(element).waitForImages(function(){jQuery.whizzy.animTitleIn(element);},null,true);
        } else {
          jQuery.whizzy.animTitleIn(element);
        }
      }
    },
    
    gotoPage: function(el,id) {
      // this goes directly to the specified page with no animation/transition effects

    },

    showPage: function(el,id) {
      // el = whizzyOuter container div?
      if(jQuery(el).hasClass('whizzyOuter')) {
        currPage = jQuery(el).data('whizzyCurrentPage');
        numPages = jQuery(el).children().size();
        nextPage = currPage+1;
        if(nextPage >= numPages) {nextPage = 0;}

        // get rid of existing title

      }


      if(p!=-1) {
        oldpage = jQuery(element).children().eq(p);
      } else {oldpage = null;}
      numpages = jQuery(element).children().size();
      //alert('current page: '+p+'; num pages: '+numpages);
      p = p+1;
      if(p>=numpages) {p = 0;}
      newpage = jQuery(element).children().eq(p);

      //keepgoing = confirm('show page: '+p+'?');
      
      anim = jQuery(element).data('whizzyAnimate');
      if(anim) {
        // slide in title (further bits are done within timeouts on anim completion)...
        //jQuery.whizzy.animTitleIn(element,p,);
      }
      
      

      /*

      if(oldpage) { 
        // animate out old title...

        // hide old page...
        jQuery(oldpage).hide(); 

        // show new page...

        jQuery(newpage).show();
      }
      jQuery(element).data('whizzyCurrentPage',p)
      // animate in new title...
      jQuery.whizzy.animTitleIn(newpage);
      // leave page displayed for x seconds...



      if(keepgoing)
        jQuery.whizzy.showNextPage(element);  */
    },

    animTitleIn: function(el) {
      // el = whizzy container div
      p = jQuery(el).data('whizzyCurrentPage');
      newpage = jQuery(el).children(':eq('+p+')');
      t = jQuery(newpage).children('div.whizzyTitle').first();
      props = jQuery(newpage).data('whizzyTitleProperties');
      // is this the first time this title has been shown? if so, we need to calculate height/width etc...
      if(props == undefined || props['width']==0) {
        props = jQuery.whizzy.drawTitle(newpage);
      }
      jQuery('div#debug').html('<table><tr><td>Item</td><td>Left</td><td>Top</td></tr>'
                               +'<tr><td>Dimensions</td><td>'+props['width']+'</td><td>'+props['height']+'</td></tr>'
                               +'<tr><td>Start Position</td><td>'+props['startLeft']+'</td><td>'+props['startTop']+'</td></tr>'
                               +'<tr><td>Mid Position</td><td>'+props['midLeft']+'</td><td>'+props['midTop']+'</td></tr>'
                               +'<tr><td>End Position</td><td>'+props['endLeft']+'</td><td>'+props['endTop']+'</td></tr>'
                               +'<tr><td>Clip Dimensions</td><td>'+props['clipWidth']+'</td><td>'+props['clipHeight']+'</td></tr>'
                               +'</table>'
                              );
      // set title to start position...
      jQuery(t).css({'top':props['startTop']+'px','left':props['startLeft']+'px'});
      jQuery(t).animate({'top':props['midTop']+'px', 'left':props['midLeft']+'px'},1000,'linear',setTimeout(function(){jQuery.whizzy.animTitleOut(el);},5000));
    },

    animTitleOut: function(el) {
      // el = whizzy container div
      p = jQuery(el).data('whizzyCurrentPage');
      newpage = jQuery(el).children().eq(p);
      t = jQuery(newpage).children('div.whizzyTitle').first();
      props = jQuery(newpage).data('whizzyTitleProperties');
      jQuery(t).animate({'top':props['endTop']+'px', 'left':props['endLeft']+'px'},1000,'linear',function() {jQuery(t).css({'top':props['startTop']+'px', 'left':props['startLeft']+'px'});});
      jQuery.whizzy.animNextPage(el);
    },

    animNextPage: function(el) {
      // el = whizzy container div
      // get index of next page...
      currPageNum = jQuery(el).data('whizzyCurrentPage');
      numPages = jQuery(el).children().size();
      nextPageNum = currPageNum+1;
      if(nextPageNum >= numPages) {nextPageNum = 0;}
      jQuery(el).data('whizzyCurrentPage',nextPageNum);
      currPage = jQuery(el).children().eq(currPageNum);
      nextPage = jQuery(el).children().eq(nextPageNum);

      if(nextPageNum > currPageNum) {
        jQuery(nextPage).fadeIn('slow',function() {
          jQuery(currPage).hide();
          jQuery.whizzy.animTitleIn(el);
        });
      } else if(nextPageNum < currPageNum) {
        // new page has higher z-order, so need to fade it out rather than fade new one in...
        jQuery(nextPage).show();
        jQuery(currPage).fadeOut('slow',function() {
          jQuery(currPage).hide();
          jQuery.whizzy.animTitleIn(el);
        });
      }


      

    },

    animPageChange: function(page) {
      t = jQuery(page).children('div.whizzyTitle').first();
      props = jQuery(page).data('whizzyTitleProperties');
      // reset title position...
      jQuery(t).css({'top':props['startTop'], 'left':props['startLeft']});


    },
    
    resetPage: function(page) {
      // sets title back to start position, and sets opacity to 1

    },
/*
    titleCalcPos: function(page) {
      props = jQuery(page).data('whizzyTitleProperties');
      if(props==undefined) { 
        props = {'clipWidth':0, 'clipHeight':0,
                 'width':0,     'height':0,
                 'startLeft':0, 'startTop':0,
                 'midLeft':0,   'midTop':0,
                 'endLeft':0,   'endTop':0
                };
      };
      props['width'] = jQuery(t).width() + 3;
      props['height'] = jQuery(t).height() + 3;
      jQuery(t).width(props['width']);
      jQuery(t).height(props['height']);
      props['clipWidth'] = jQuery(page).parent().data('whizzyWidth');
      props['clipHeight'] = jQuery(page).parent().data('whizzyHeight');
      pos = jQuery(page).data('whizzyTitlePosition');
      if(pos && typeof pos == 'string' && pos.length==2) {
        pos = pos.toLowerCase();
        if(pos[0]!='t' || pos[0]!='b' || pos[0]!='m' || pos[0]!='c') { pos[0] = 't'; }
        if(pos[0]=='m') { pos[0] = 'c'; }
        if(pos[1]!='l' || pos[1]!='r' || pos[1]!='m' || pos[1]!='c') { pos[1] = 'r'; }
        if(pos[1]=='m') { pos[1] = 'c'; }
      } else {
        pos = 'tr'; // default
      }
      jQuery(page).data('whizzyTitlePosition',pos);
      // calculate tops...
      switch(pos[0]) {
        case 't': props['midTop'] = Math.round(props['clipHeight']*0.05); break;
        case 'c': props['midTop'] = Math.round((props['clipHeight']-props['height'])/2); break;
        case 'b': props['midTop'] = Math.round((props['clipHeight']*0.95)-props['height']); break;
      }
      props['startTop'] = props['midTop'];
      props['endTop'] = props['clipHeight'] + props['midTop'];
      // calculate lefts...
      switch(pos[1]) {
        case 'l': props['midLeft'] = Math.round(props['clipWidth']*0.05); break;
        case 'c': props['midLeft'] = Math.round((props['clipWidth']-props['width'])/2); break;
        case 'r': props['midLeft'] = Math.round((props['clipWidth']*0.95)-props['width']); break;
      }
      props['startLeft'] = -props['width'];
      props['endLeft'] = props['midLeft'];
      //alert(props['width'])

      // apply css to dropshadows...
      h = jQuery(page).children('div.whizzyTitle').children('div.whizzyTitle_top').height();
      if(h!=undefined && h>0) {
        //jQuery(page).children('div.whizzyTitle').children('div.whizzyTitle_mid').css('top','-'+(h-2)+'px');
        //jQuery(page).children('div.whizzyTitle').children('div.whizzyTitle_top').css('top','-'+(h*2)+'px');
      }

      // store values...
      jQuery(page).data('whizzyTitleProperties',props);
      return props;
    },
*/
    calcTitlePos: function(pos,textwidth,textheight,divwidth,divheight) {
      props = {'width':textwidth, 'height':textheight,
               'startLeft':0,     'startTop':0,
               'midLeft':0,       'midTop':0,
               'endLeft':0,       'endTop':0,
               'align':'left'
              };
      if(pos==undefined) {pos = 'tr';}
      if(typeof pos == 'string' && pos.length==2) {
        pos = pos.toLowerCase();
        if(pos[0]!='t' || pos[0]!='b' || pos[0]!='m' || pos[0]!='c') {pos[0] = 't';}
        if(pos[0]=='m') {pos[0] = 'c';}
        if(pos[1]!='l' || pos[1]!='r' || pos[1]!='m' || pos[1]!='c') {pos[1] = 'r';}
        if(pos[1]=='m') {pos[1] = 'c';}
      } else {
        pos = 'tr'; // default
      }
      // calculate tops...
      switch(pos[0]) {
        case 't':props['midTop'] = Math.round(divheight*0.05);break;
        case 'c':props['midTop'] = Math.round((divheight-textheight)/2);break;
        case 'b':props['midTop'] = Math.round((divheight*0.95)-textheight);break;
      }
      props['startTop'] = props['midTop'];
      props['endTop'] = divheight + props['midTop'];
      // calculate lefts...
      switch(pos[1]) {
        case 'l':props['midLeft'] = Math.round(divwidth*0.05);break;
        case 'c':props['midLeft'] = Math.round((divwidth-textwidth)/2);props['align'] = 'center';break;
        case 'r':props['midLeft'] = Math.round((divwidth*0.95)-textwidth);props['align'] = 'right';break;
      }
      props['startLeft'] = props['midLeft']-divwidth;
      props['endLeft'] = props['midLeft'];

      return props;
    },


    drawTitle: function(p) {
      // p = a page that is being shown for the first time.
      t = jQuery(p).children('div.whizzyTitle:first');
      maxwidth = parseInt(jQuery(p).parent().width());
      maxheight = parseInt(jQuery(p).parent().height());
      jQuery('div#debug').html('maxwidth = '+maxwidth+'px; maxheight = '+maxheight+'px');
      // move title div out of visible area...
      t.css({'position':'absolute','top':maxheight+'px','left':'0px','width':(maxwidth*0.9)+'px'});
      // set title...
      //thetitle = t.text();
      //thetitle = 'example title that is just here for testing';
      //t.html('<span class="whizzyTitle_top">'+thetitle+'</span>');
      // what is the width of the span?
      textwidth = parseInt(t.children('span:first').width());
      textheight = parseInt(t.children('span:first').height());
      // add dropshadow if wanted...
      ds = p.data('whizzyTitleShadow');
      if(ds==undefined) {ds = p.parent().data('whizzyTitleShadow');}
      if(ds==undefined || ds) {
        //t.prepend('<span class="whizzyTitle_mid">'+thetitle+'</span>').prepend('<span class="whizzyTitle_low">'+thetitle+'</span>');
      }
      // add dropshadow css...
      //t.children('span.whizzyTitle_mid').css({'position':'absolute','left':'2px','top':'2px','color':'#707070','opacity':'0.7'});
      //t.children('span.whizzyTitle_low').css({'position':'absolute','left':'3px','top':'3px','color':'#202020','opacity':'0.9'});
      //t.children('span.whizzyTitle_top').css({'color':'#F0F0F0'});
      // now figure out where the text should go & save...
      pos = jQuery(p).data('whizzyTitlePosition');
      props = jQuery.whizzy.calcTitlePos(pos,textwidth,textheight,maxwidth,maxheight);
      jQuery(p).data('whizzyTitleProperties',props);
      // apply start position + size to title...
      t.css({'width':(textwidth+3)+'px','top':props['startTop']+'px','left':props['startLeft']+'px','text-align':props['align']});
      return props;
    },

    
    setTitle: function(thepage,title) {
      // page is div.whizzyPage to ammend
      if(jQuery(thepage).hasClass('whizzyPage')) {
        if(title && typeof title == 'string') {
          jQuery(thepage).data('whizzyTitle',title);
        }
        if(jQuery(thepage).children('div.whizzyTitle').size() == 0) {
          jQuery(thepage).append('<div class="whizzyTitle"></div>');
        }
        t = jQuery(thepage).children('div.whizzyTitle').css({'position':'absolute','top':'-999999px','left':'-999999px'});
        title = jQuery(thepage).data('whizzyTitle');
        ds1 = jQuery(thepage).parent().data('whizzyTitleShadow');
        ds = jQuery(thepage).data('whizzyTitleShadow');
        if(ds==undefined) {ds = ds1;}
        if(ds) {
          if(!jQuery.browser.msie) {
            jQuery(t).css({'text-shadow':'2px 2px 2px black'})
                     .html('<span class="whizzyTitle_top">'+title+'</span>');
          } else {
            // fake drop shadow with a couple of extra text divs...
            //jQuery(t).html('<span class="whizzyTitle_low">'+title+'</span><span class="whizzyTitle_mid">'+title+'</span><span class="whizzyTitle_top">'+title+'</span>');
            jQuery(t).html('<span class="whizzyTitle_low">'+title+'</span><span class="whizzyTitle_top">'+title+'</span>');
            jQuery(t).children('span.whizzyTitle_low').css({'color':'black','position':'absolute','top':'2px','left':'2px','opacity':'0.8'});
            jQuery(t).children('span.whizzyTitle_top').css({'position':'absolute','top':'0px','left':'0px'});
          }
        } else {
          jQuery(t).html('<span class="whizzyTitle_top">'+title+'</span>');
        }
        maxwidth = jQuery(thepage).parent().data('whizzyWidth');
        maxwidth = Math.round(maxwidth*0.9);
        //jQuery(t).children().css({'max-width':maxwidth+'px'});

        // apply css to dropshadow...
        var fontHeight = parseInt(jQuery(t).children('div.whizzyTitle_top').css('font-size'));
        if(fontHeight > 0) {
          //jQuery(t).children().css({'position':'relative'});
          //jQuery(t).children('div.whizzyTitle_low').css({'color':'#202020','left':'3px','top':'3px','opacity':'0.9'});
          //jQuery(t).children('div.whizzyTitle_mid').css({'color':'#707070','left':'2px','top':'-'+(fontHeight-2)+'px','opacity':'0.7'});
          //jQuery(t).children('div.whizzyTitle_top').css({'top':'-'+(fontHeight*2)+'px'});
        }
      }
    }

  } // end of whizzy object

});




/*
use jquery timers to repeat anims.
use dropshadow on titles (or make my own)
chain anim pages together somehow...


e.g. 

$('img').whizzyPage().whizzyPage().whizzyPage().whizzyPage().whizzy();


*/










