/////////////////////////////////////////////////////////////////////////////
// FUNCTIONS
/////////////////////////////////////////////////////////////////////////////

// Get parameter fetching
function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if ( results === null )  return "";
  return results[1];
}

/////////////////////////////////////////////////////////////////////////////
// CLASSES
/////////////////////////////////////////////////////////////////////////////

/**
 * XML/Text RPC
 * 
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @class
 */
var RPC = (function() {

  var createXMLObject = function() {
    var ua = navigator.userAgent.toLowerCase();
    var request = null;
    if (!window.ActiveXObject)
      request = new XMLHttpRequest();
    else if (ua.indexOf('msie 5') == -1)
      request = new ActiveXObject("Msxml2.XMLHTTP");
    else
      request = new ActiveXObject("Microsoft.XMLHTTP");

    return request;
  };

  return function(obj, url) {

    var self = this;
    var oXML = null;
    var sURL = url;

    var __construct = function() {
      oXML = createXMLObject();
    };

    var handler = function() {
      if ( oXML.status == 200 ) {
        if ( oXML.readyState == 4 ) {
          obj.onSuccess(("" + oXML.responseText + ""), self);
        }
      }
    };

    var createURI = function(vars) {
      var args = [];
      for ( var i in vars ) {
        args.push(i + "=" + vars[i]);
      }
      return args.join("&");
    };

    this.createPOST = function(vars) {
      var params = createURI(vars);
      oXML.open("POST", sURL, true);
      oXML.onreadystatechange = handler;
      oXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      oXML.setRequestHeader("Content-length", params.length);
      oXML.setRequestHeader("Connection", "close");
      oXML.send(params);
    };

    this.createGET = function(vars) {
      oXML.open("GET", sURL + "?" + createURI(vars));
      oXML.onreadystatechange = handler;
      oXML.send("");
    };

    __construct();
  };

})();

/**
 * Simple Image Gallery
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @class
 */
var ImageGallery = (function() {

  var SHOW_TIMEOUT = 10;
  var HIDE_TIMEOUT = 300;
  var SLIDE_TIMEOUT = 5000;

  /**
   * Create a new ImageGallery
   *
   * @param     DOMElement      root    Gallery element (Defaults to #ImageGallery)
   * @param     Array           uargs   Gallery RPC options (Defaults to URL values)
   * @param     Integer         gtype   Gallery type (0=Slide, 1=Thumbs)
   * @param     Array           gopts   Gallery options (Defaults to none)
   */
  return function(root, uargs, gtype, gopts) {
    var self = this;

    var eRoot = $(root) || $("ImageGallery");
    var eImage = null;///$("ImageGalleryImage");
    var eThumbs = null;//$("ImageGalleryThumbs");
    var eThumbsBack = null;//$("ImageGalleryThumbsBackground");
    var iBackStart = 0;
    var oRPC = null;
    var aImages = [];
    var aTitles = [];
    var eCurrent = null;
    var oSlideUp = null;
    var oSlideDown = null; // To prevent slippery sliding
    var bSlideLock = false;
    var bSlideVisible = false;
    var iIndex = 0;
    var iMax = 0;
    var iType = 0;
    var aOptions = {
      'random'    : false,
      'links'     : true
    };
    var aOptionsRPC = {
      'fla'       : 1,
      'mac'       : 'con',
      'sac'       : 'all',
      'site'      : 'swfit2site',
      'cid'       : gup('cid') || 0,
      'fid'       : gup('fid') || 0,
      'aid'       : gup('aid') || 0
    };

    /**
     * @constructor
     */
    var __construct = function() {
      if ( eRoot ) {
        eImage = eRoot.select(".ImageGalleryImage")[0];
        eThumbs = eRoot.select(".ImageGalleryThumbs")[0];
        eThumbsBack = eRoot.select(".ImageGalleryThumbsBackground")[0];
      }

      if ( !eRoot || !eImage || !eThumbs ) return;

      iBackStart = eThumbsBack.offsetTop;

      var i;

      // Apply user settings
      for ( i in uargs ) {
        if ( uargs.hasOwnProperty(i) ) {
          aOptionsRPC[i] = uargs[i];
        }
      }

      for ( i in gopts ) {
        if ( gopts.hasOwnProperty(i) ) {
          aOptions[i] = gopts[i];
        }
      }

      // Get all images from server
      oRPC = new RPC(self, "/swfit2/servlet/swfit2web");
      oRPC.createGET(aOptionsRPC);
    };

    ///////////////////////////////////////////////////////////////////////////
    // GALLERY WITH THUMBNAILS
    ///////////////////////////////////////////////////////////////////////////

    var showThumbs = function() {
      if ( bSlideLock ) 
        return;

      clearTimeout(oSlideUp);
      clearTimeout(oSlideDown);

      oSlideUp = setTimeout(function() {
        var opts = {mode:'absolute',x:0,y:(iBackStart),afterFinish:function(){bSlideVisible = true;}};
        new Effect.Move(eThumbsBack, opts);
        new Effect.Move(eThumbs, opts);
      }, SHOW_TIMEOUT);

    };

    var hideThumbs = function(force) {
      if ( force && bSlideLock ) return;

      var func = force ? function(){bSlideLock = false;bSlideVisible=false;} : function(){bSlideVisible = false;};
      clearTimeout(oSlideUp);
      clearTimeout(oSlideDown);
      oSlideDown = setTimeout(function() {
        var opts = {mode:'absolute',x:0,y:(iBackStart + 40),afterFinish:func};
        new Effect.Move(eThumbsBack, opts);
        new Effect.Move(eThumbs, opts);
      }, force ? 0 : HIDE_TIMEOUT);

      if ( force ) {
        bSlideLock = true;
      }
    };

    var initThumbs = function() {
      if ( aImages.length < 2 ) {
        eThumbs.style.display = 'none';
        eThumbsBack.style.display = 'none';
        eRoot.className = "small";
      }

      for ( var i = 0; i < aImages.length; i++ ) {
        // Create thumbnail container
        var div = document.createElement('DIV');
        div.onclick = (function(d,i) {
          return function() {
            var spl_src = eImage.src.split("/");
            var spl_cur = i.split("/");

            if ( spl_src[spl_src.length-1] !== spl_cur[spl_cur.length-1] ) {
              if ( eCurrent ) {
                eCurrent.className = "";
              }
              eCurrent = d;
              d.className = "current";

              eImage.setOpacity(0.0);

              eImage.onload = function() {
                Effect.Fade(eImage, { duration: 1.0, from: 0, to: 1, afterFinish : function() {
                  eImage.setOpacity(1.0);
                }});
              };

              eImage.onmouseover = function() {
                clearTimeout(oSlideDown);
              };
              eImage.src = i;

              if ( aOptions.links ) {
                eImage.style.cursor = 'pointer';
                eImage.onclick = function() {
                  var img = this.src.replace("_mid", "_big");
                  window.open(img);
                };
              }

            }
          };
        })(div, aImages[i] + '_mid.jpg');

        // Create thumbnail
        var el = document.createElement('IMG');
        el.src = aImages[i] + '_thb.jpg';
        el.title = aTitles[i];
        el.alt = aTitles[i];
        div.appendChild(el);
        eThumbs.appendChild(div);

        // Select first image
        if ( i === 0 ) {
          div.onclick();
        }

        // Show/Hide thumbnails event
        eThumbs.onmouseover = function() {
          showThumbs();
        };
        eThumbs.onmouseout = function() {
          hideThumbs();
        };
        eRoot.onmouseout = function() {
          hideThumbs();
        };
        eImage.onmouseover = function() {
          hideThumbs();
        };
        eImage.onmousemove = function() {
          if ( bSlideVisible ) {
            hideThumbs(true);
          }
        };

        hideThumbs();
      }
    };

    ///////////////////////////////////////////////////////////////////////////
    // GALLERY WITH SLIDING
    ///////////////////////////////////////////////////////////////////////////

    var __showImage = function(src, initial) {
      if ( initial === false ) {
        Effect.Fade(eImage, { duration: 1.0, from: 1, to: 0, afterFinish : function() {
          eImage.setOpacity(0.0);
          eImage.show();

          eImage.onload = function() {
            Effect.Fade(eImage, { duration: 1.0, from: 0, to: 1, afterFinish : function() {
            }});
          };
          eImage.src = src;
        }});
      } else {
        eImage.setOpacity(1.0);
        eImage.src = src;
        eImage.style.width = "100%";
      }
    };

    var showImage = function(index, initial) {
      var src = aImages[index] + "_mid.jpg";
      __showImage(src, initial);
      iIndex = index;
    };

    this.nextImage = function() {
      iIndex++;
      if ( iIndex >= iMax ) {
        iIndex = 0;
      }
      showImage(iIndex, false);
    };

    this.prevImage = function() {
      iIndex--;
      if ( iIndex < 0 ) {
        iIndex = iMax;
      }
      showImage(iIndex, false);
    };

    var initSlide = function() {
      showImage(0, true);

      setInterval(function() {
        self.nextImage();
      }, SLIDE_TIMEOUT);

      // Global click
      if ( aOptions.links ) {
        eImage.style.cursor = 'pointer';
        eImage.onclick = function() {
          var img = this.src.replace("_mid", "_big");
          window.open(img);
        };
      }

      eThumbs.style.display = 'none';
      eThumbsBack.style.display = 'none';
    };

    ///////////////////////////////////////////////////////////////////////////
    // GALLERY METHODS
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Initialize the gallery and show image(s)
     */
    var start = function() {
      if ( aImages.length ) {
        iMax = aImages.length;
        eRoot.style.display = 'block';

        if ( aOptions.random ) {
          aImages = aImages.sort(function() {return 0.5 - Math.random();});
        }

        if ( iMax ) {
          if ( iType === 0 ) {
            initSlide();
          } else {
            initThumbs();
          }
        }
      } else {
        eRoot.style.display = 'none';
      }
    };

    /**
     * Parse data from swfit request
     */
    this.onSuccess = function(res) {
      var splits = res.split("&");
      var options = {};
      var titles = [];
      var i = 0;

      // Parse URI to object
      for ( i = 0; i < splits.length; i++ ) {
        var splits2 = splits[i].split("=");
        if ( splits2[0] && typeof splits2[1] !== undefined ) {
          options[decodeURIComponent(splits2[0])] = unescape(splits2[1].replace("+"," "));
        }
      }

      // Extract image and text
      for ( var x in options ) {
        if ( options.hasOwnProperty(x) ) {
          if ( x.match(/img_url_/) ) {
            aImages.push(options[x]);
          }
          if ( x.match(/img_text_/) ) {
            var text = options[x].replace("+", " ");
            titles.push(text);
          }
        }
      }

      // Parse text
      var tmpEl = document.createElement("DIV");
      tmpEl.style.visibility = 'hidden';
      document.body.appendChild(tmpEl);

      for ( i = 0; i < titles.length; i++ ) {
        tmpEl.innerHTML = titles[i];
        if ( tmpEl.childNodes[0] ) {
          aTitles.push(tmpEl.childNodes[0].innerHTML);
        } else {
          aTitles.push("");
        }
        break;
      }

      tmpEl.parentNode.removeChild(tmpEl);

      // Cleanup and startup
      delete options;
      delete splits;

      setTimeout(function() {
        start();
      }, 0);
    };

    this.onFailure = function(res) {
    };

    __construct();
  };

})();

