
/*
 * tweenBox
 *
 * Created by Will Jessup (http://www.willjessup.com)
 * Under an Attribution, Share Alike License
 * 
 */

  

(function(){

  //previous and next images for gallery
  var prev;
  var nex;
  //currently viewing first image
  var curViewing = 0;
  //params of the URL sent to thickbox
  var params;                                                     
  var pos = function(){ $.tweenbox.position($("#tweenContent")[0]); };

  //tweenbox namespace
  $.tweenbox = {

    init: function(o, params, url) {

        var urlString = /\.jpg|\.jpeg|\.png|\.gif|\.html|\.htm|\.php|\.cfm|\.asp|\.aspx|\.jsp|\.jst|\.rb|\.txt/g;
        this.urlType = url.toLowerCase().match(urlString);
        this.url = url;
        this.setup = this.setup ? true : false;

        o.doAfter ? this.doAfter = o.doAfter : '';
        //use params, if not use default set in $()tweenbox options, else use default
        params.type ? this.type = params.type : ( o.type ? this.type = o.type : this.type = 'tween');
        params.speed ? this.speed = params.speed : ( o.speed ? this.speed = o.speed : this.speed = '200');
        params.easing ? this.easing = params.easing : ( o.easing ? this.easing = o.easing : this.easing = 'elasout');


      if(this.setup) {

          try {
            this.type ? $.tweenbox.tweens.init(this.type, this.url) : $.tweenbox.tweens.init('tween', this.url);
          } catch(e) {
            alert("method '" + this.type + "' not working properly. Error = " + e.message);
          }
      } else {



        //window is the main container, which always is visible & gets handled for changing location & size
        //container holds the content which can be shown and hidden independantly
        $("body").append('<div id="tweenLoad">' +
                               '<img src="/images/circle_animation.gif" />' +
                          '</div>' +
                          '<div id="tweenOverlay"></div>' +
                          '<div id="tweenWindow">' +
                               '<div id="tweenClose"></div>' +
                               '<div id="tweenContent"></div>' +
                          '</div>');

        //if doBefore is set, call the decorate function
        o.doBefore ?  o.doBefore() : '';

        $("#tweenOverlay, #tweenClose").bind("click",function(){ $.tweenbox.tearDown() });

        $(window).bind("scroll", pos);

        $('select').hide();
        overlaySize();
        load_position();

       //everyone clap if you love IE.
        ($.browser.msie) ? $("#tweenOverlay").css("opacity", .6) :  $("#tweenOverlay").fadeTo(parseFloat(this.speed), .6);
        $("#tweenWindow").fadeTo(parseFloat(this.speed), 1);

        //should abstract this to factory method
        if(".jpg.jpeg.png.gif".match(this.urlType) ){
           $("#tweenContent").append(
                 '<div id="tweenGalleryLeft"><a href=""></a></div>' +
                 '<div id="tweenGalleryRight"><a href=""></a></div>' +
                 '<div id="tweenImageBox"></div>'
           );
           this.setup = true;
           this.doTweenGallery();
           return;
        }

        if (".htm.html.php.asp.aspx.jsp.jst.rb.rhtml.txt.cfm".match(this.urlType)){
          this.setup = true;
          $.tweenbox.doTweenBox();
          return;
        }
      };
    },

    doTweenGallery: function() {
        var self = this;
        var pagesize = getPageSize();
        var arrayPageScroll = getPageScrollTop();
        this.position();

        $.post(url, {}, function(json) {


              $("#tweenLoad").fadeOut();
              $("#tweenWindow").show();
              eval("var args = " + json);

              //new array to hold images from JSON.
              imageArray = new Array();
              var i = 0;
              for (j in args) {
                imageArray[i++] = args[j];
              }

              //show the image and tween to the right size.
              self.tweenImage(imageArray, curViewing);

             //if doAfter is set, call the decorate function
              if (params.doAfter) $.tweenbox.doAfter[ params.doAfter ]();

        });

    },
    doTweenBox: function() {
        var self = this;
        $("#tweenContent").load(url, function(){
            self.position(this);
            $("#tweenContent a").tweenbox();
            $("#tweenLoad").remove();
            $("#tweenWindow").show();

            self.doAfter ? self.doAfter() : '';
        });
    },
    tweenImage: function(imageArray, curViewing) {

               var curImage = new Image();
              var totalImages = imageArray.length;

              if(curViewing == 0)
                prev = (totalImages - 1);
              else
                prev = curViewing - 1;

              if(curViewing == (totalImages - 1))
                nex = 0;
              else
                nex = curViewing + 1;


      var self = this;
      //set which image we're currently on
      curImage.src = imageArray[curViewing];

      var pagesize = getPageSize();
      var arrayPageScroll = getPageScrollTop();

      // this Sets up the first image and creates the left / right DIV's. These need to be included in any future animation, so be careful.
      $("#tweenContent").fadeOut(parseInt(params.speed/2), function() {


              $("#tweenLoad").css({display: "block", font: "2em arial", color: "#888"});
              var k = 0
              new function imageCompleteCheck() {
                        if(!curImage.complete) {
                               $("#tweenLoad").html('loading' +k );
                               return setTimeout(imageCompleteCheck, k++ , 10);
                        } else {
                                  $("#tweenLoad").hide();
                                  var x = pagesize[0] - 100;
                                  var y = pagesize[1] - 100;
                                  imageWidth = curImage.width;
                                  imageHeight = curImage.height;
                                  if (imageWidth > x) {
                                        imageHeight = imageHeight * (x / imageWidth);
                                        imageWidth = x;
                                              if (imageHeight > y) {
                                                      imageWidth = imageWidth * (y / imageHeight);
                                                      imageHeight = y;
                                              }
                                  } else if (imageHeight > y) {
                                          imageWidth = imageWidth * (y / imageHeight);
                                          imageHeight = y;
                                                if (imageWidth > x) {
                                                        imageHeight = imageHeight * (x / imageWidth);
                                                        imageWidth = x;
                                                }
                                  }


                                $("#tweenImageBox").html('<img src="' + curImage.src + '" height="' + imageHeight + 'px" width="' + imageWidth + 'px" />');
                                if(gallerySetup === false){
                                  $("#tweenGalleryLeft a").bind("click", function(){ self.tweenImage(imageArray, prev); return false; });
                                  $("#tweenGalleryRight a").bind("click", function(){ self.tweenImage(imageArray, nex); return false; });
                                  gallerySetup = true;
                                }

                                //$("#tweenWindow").animate({left: parseInt((pagesize[0] - curImage.width)/2), width: parseInt(curImage.width + 30)}, parseInt(params.speed), function(){
                                $("#tweenWindow").animate({left: parseInt((pagesize[0] - imageWidth)/2), width: parseInt(imageWidth + 0)}, parseInt(params.speed), function(){
                                    $("#tweenWindow").animate({height: parseInt(imageHeight + 0), top: parseInt(arrayPageScroll[1] + ((pagesize[1] - imageHeight)/2) - 30)}, parseInt(params.speed), function(){
                                          $("#tweenContent").fadeIn(parseInt(params.speed/2))
                                          $("#tweenGalleryLeft a, #tweenGalleryRight a").css({top: (imageHeight/2 - 20) + "px"});
                                          $("#tweenWindow").css("overflow", "visible");

                                    });
                                });
                           }
                    }
            });
    },
    position: function(o) {
        var pagesize = getPageSize();
        var arrayPageScroll = getPageScrollTop();
        var width = getWidth(o);  //grab and cache width
        var height = getHeight(o); //grab and cache height
        $("#tweenWindow").css({width: width+"px",height: height+"px", left: ((pagesize[0] - width)/2)+"px", top: (arrayPageScroll[1] + ((pagesize[1]-height)/2))+"px" });
        overlaySize();
    },
    tearDown: function() {
      var self = this;
      $("#tweenWindow").fadeTo(parseFloat(this.speed), 0);
      $("#tweenOverlay").fadeTo(parseFloat(this.speed), 0, function() {
        $('#tweenWindow,#tweenOverlay,#tweenLoad').remove();
        self.setup = false;
      });
      $(window).unbind("scroll", pos);
      $('select').show();
    }

  }




  $.tweens = {
    init: function(type, url) {

      this.self = this;
      this.url = url;
      this.tweenContent = $("#tweenContent");
      this.tweenWindow = $("#tweenWindow");
      this.pagesize = getPageSize();
      this.arrayPageScroll = getPageScrollTop();
      this.tweenContent.notAuto = true;
      this[type]();
    },
    elas: function() {
      var self = this;

      self.tweenContent.fadeOut(parseInt(self.speed), function() {
          self.tweenContent.load(self.url, function(){
              $("#tweenContent a").tweenbox();
              var width = getWidth(this);  //grab and cache width
              var height = getHeight(this); //grab and cache height
              self.tweenWindow.animate({height: parseInt( height ), top: parseInt(self.arrayPageScroll[1] + ((self.pagesize[1] - height )/2)), left: parseInt( (self.pagesize[0] - width )/2), width: parseInt( width ) }, self.speed, self.easing , function(){
                self.tweenContent.fadeIn(parseInt(self.speed));
              });
          });
      });

    },

    tween: function() {


          tweenContent.fadeOut(parseInt(self.speed), function() {
              tweenContent.load(self.url, function(){
                  $("#tweenContent a").tweenbox();
                  var width = getWidth(this);  //grab and cache width
                  var height = getHeight(this); //grab and cache height
                  tweenWindow.animate({left: parseInt( (pagesize[0] - width )/2), width: parseInt( width ) }, parseInt(self.speed), function(){
                      tweenWindow.animate({ height: parseInt( height ), top: parseInt(arrayPageScroll[1] + ((pagesize[1] - height )/2)) }, parseInt(self.speed), function(){
                          tweenContent.fadeIn(parseInt(self.speed));
                      });
                  });
              });
          });
    }

  }
  $.tweenbox.tweens = $.tweens

  function getWidth(o) {
       return (this.params.width) ? this.params.width : parseInt($.css(o, "width"))
  }
  function getHeight(o) {
       return (this.params.height) ? this.params.height : parseInt($.css(o, "height"))
  }
  function imageLoadedCheck() {
     //if image isn't loaded, loop back until it is.
     if (!curImage.complete) {
         return false;

     } else {
          return true;
      }
  }
  function overlaySize(){
        if (window.innerHeight && window.scrollMaxY) {  
                yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
                yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                yScroll = document.body.offsetHeight;
        }
        $("#tweenOverlay").css("height",yScroll +"px");
  }

  function load_position() {
        var pagesize = getPageSize();
        var arrayPageScroll = getPageScrollTop();
        $("#tweenLoad").css({display: "block", left: ((pagesize[0] - 100)/2)+"px", top: (arrayPageScroll[1] + ((pagesize[1]-100)/2))+"px" })
  }



  
  function getPageScrollTop(){
        var yScrolltop;
        if (self.pageYOffset) {
                yScrolltop = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop){      // Explorer 6 Strict
                yScrolltop = document.documentElement.scrollTop;
        } else if (document.body) {// all other Explorers
                yScrolltop = document.body.scrollTop;
        }
        arrayPageScroll = new Array('',yScrolltop)
        return arrayPageScroll;
  }
  
  function getPageSize(){
        var de = document.documentElement;
        var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
        var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;

        arrayPageSize = new Array(w,h)
        return arrayPageSize;
  }


})();


function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

jQuery.fn.tweenbox = function( options  ) {
  this.click(function(){
    url = this.href;
    var queryString = url.replace(/^[^\?]+\??/,'');
    params = parseQuery( queryString );

    $.tweenbox.init(options = {}, params, url);
    return false;
  });
}



