/////////////////////////////////////////////////////////////////////////////
// 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];
}

/*
function findParam(param) {
  var query_params = new QueryParams (window.location.search);
  var default_data = ("?(none)").replace(new RegExp("&amp;","g"),"&");
  var default_params = new QueryParams (default_data);

  return query_params.findQueryParam (param) || default_params.findQueryParam (param) || "";
}
*/

/////////////////////////////////////////////////////////////////////////////
// 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 + "").evalJSON(true), self);
          obj.onSuccess(("" + oXML.responseText + ""), self);
        //} else {
          //obj.onFailure(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;

  return function() {
    var self = this;

    var eRoot = $("ImageGallery");
    var eImage = $("ImageGalleryImage");
    var eThumbs = $("ImageGalleryThumbs");
    var eThumbsBack = $("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 __construct = function() {
      if ( !eRoot || !eImage || !eThumbs ) return;

      iBackStart = eThumbsBack.offsetTop;
      oRPC = new RPC(self, "/swfit2/servlet/swfit2web");

      // Get all images from server
      var args = {
        'fla'   : 1,
        'mac'   : 'con',
        'sac'   : 'all',
        'site'  : 'dramatikkenshus',
        'cid'   : gup('cid'),
        'fid'   : 745,
        'aid'   : gup('aid')
      };
      oRPC.createGET(args);
    };

    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 start = function() {
      if ( aImages.length ) {
        eRoot.style.display = 'block';

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

        // Create thumbnails
        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;
                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();
          */
        }
      } else {
        eRoot.style.display = 'none';
      }
    };

    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("=");
        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();
  };

})();
