/*
 * Flixn JavaScript Recorder API Toolkit
 * Version: 1.0
 * (C) Flixn, Inc.
 */

flixn = {

  inputId: null,
  htmlCode: '[flixn]{ID}[/flixn]',
//  htmlCode: 'http://flixn.com/player/api/{ID}/',
//  htmlCode: '{ID}',

  backdropId: 'flixn_backdrop',
  indicatorId: 'flixn_indicator',
  containerId: 'flixn_container',
  recorderId: 'flixn_recorder',

  indicatorText: 'Loading...',
  indicatorUrl: 'http://flixn.com/js/api/recorder/10/indicator.gif',
  indicatorWidth: 56,
  indicatorHeight: 42,

  containerCloseImg: 'http://flixn.com/js/api/recorder/10/container_close.gif',
  containerWidth: 403,
  containerHeight: 447,

  hideObjects: false,
  hideSelects: false,

  // Target percentages
  backdropOpacity: 70,
  indicatorOpacity: 100,

  // Fade-in step, percentage
  backdropFadeStep: 20,
  indicatorFadeStep: 20,

  // Fade-in step delay, milliseconds
  backdropFadeDelay: 0.1,
  indicatorFadeDelay: 5,

  _recorderWidth: 328,
  _recorderHeight: 320,
  _recorderUrl: 'http://flixn.com/flash/recorder.swf',

  _indicatorWidth: 56,
  _indicatorHeight: 42,

  _indicatorTimer: null,

  _insertTextArea: null, // Method
  _insertTextAreaArgs: null,

  showRecorder: function(inputId) {
    flixn.inputId = inputId;

    var handle = this.getInputHandle();
/*
    var inputType = handle.nodeName.toLowerCase();
    if (inputType == 'textarea') {
      this._storeTextAreaPos(handle);
    }
*/

    if (this.hideObjects) {
      this._setVisibilityStylesByTagName('object', 'hidden');
      this._setVisibilityStylesByTagName('embed', 'hidden');
    }

    if (this.hideSelects) {
      this._setVisibilityStylesByTagName('select', 'hidden');
    }

    this._buildBackdrop();
//    this._buildIndicator();
//    this._placeIndicator();
    this._showBackdrop();
    this._buildRecorder();
    this.recorderLoaded();
  },

  recorderLoaded: function() {
//    this._hideIndicator();
    this._placeRecorder();
    this._showRecorder();
  },

  recordComplete: function(videoId) {
    this._hideRecorder();
    this._hideBackdrop();

    if (this.hideObjects) {
      this._setVisibilityStylesByTagName('object', 'visible');
      this._setVisibilityStylesByTagName('embed', 'visible');
    }

    if (this.hideSelects) {
      this._setVisibilityStylesByTagName('select', 'visible');
    }

    this._insertCode(videoId);
  },

  getInputHandle: function() {
    return document.getElementById(this.inputId);
  },

  closeRecorder: function() {
    flixn._hideRecorder();
    flixn._hideBackdrop();
  },

  _buildBackdrop: function() {
    var backdrop = document.createElement('div');
    backdrop.setAttribute('id', this.backdropId);
//    backdrop.onclick = function () { flixn.closeRecorder(); return false; }
    var windowSize = this._getWindowSize();
    var height = Math.max(document.documentElement.scrollHeight ||
                          document.body.scrollHeight, windowSize[1]);
    backdrop.style.width = windowSize[0] + 'px';
    backdrop.style.height = height + 'px';
    this._setOpacity(backdrop, 0);
    document.body.appendChild(backdrop);
  },

  _hideBackdrop: function() {
    document.body.removeChild(document.getElementById(this.backdropId));
  },

  _showBackdrop: function() {
    this._fadeObjectIn(this.backdropId, this.backdropOpacity,
                       this.backdropFadeStep, this.backdropFadeDelay,
                       "");
  },

  _buildIndicator: function() {
    var indicator = document.createElement('div');
    indicator.setAttribute('id', this.indicatorId);

    var indicator_text = document.createElement('span');
    indicator_text.setAttribute('id', this.indicatorId + '_text');
    var indicator_text_contents = document.createTextNode(this.indicatorText);
    indicator_text.appendChild(indicator_text_contents);
    indicator.appendChild(indicator_text);

    var indicator_img = new Image()
    indicator_img.setAttribute('id', this.indicatorId + '_img');
    indicator.appendChild(indicator_img);

    this._setOpacity(indicator, 0);
    document.body.appendChild(indicator);

    indicator_img.src = this.indicatorUrl;
    indicator_img.onLoad = flixn._showIndicator();
  },

  _hideIndicator: function() {
    clearTimeout(this._indicatorTimer);
    document.body.removeChild(document.getElementById(this.indicatorId));
  },

  _placeIndicator: function() {
    var windowSize = this._getWindowSize();
    this._scrollOffset = this._getScrollOffset();

    x = this._scrollOffset[0] + (windowSize[0] - this._indicatorWidth)/2;
    y = this._scrollOffset[1] + (windowSize[1] - this._indicatorHeight)/2;

    var indicator = document.getElementById(this.indicatorId);
    indicator.style.left = x + 'px';
    indicator.style.top = y + 'px';
  },

  _showIndicator: function() {
    this._fadeObjectIn(this.indicatorId, this.indicatorOpacity,
                       this.indicatorFadeStep, this.indicatorFadeDelay,
                       "");
  },

  _checkRecorder: function() {
    // This is 100% bunk

    this._showRecorder();
    return;

    recorder = document.getElementById(this.recorderId + '_obj');

    if (recorder.PercentLoaded) {
      if (recorder.PercentLoaded() == 100) {
//        flixn._hideIndicator();
        flixn._showRecorder();
      } else {
        setTimeout('flixn._checkRecorder()', 50);
      }
    } else {
//      this._hideIndicator();
      this._showRecorder();
    }
  },

  _buildRecorder: function() {
    var container = document.createElement('div');
    container.setAttribute('id', this.containerId);
//    container.setAttribute('onclick', 'window.open("http://flixn.com/"); return;');
    container.style.display = 'none';

    var flixn_link_d = document.createElement('div');
    var flixn_link = document.createElement('a');
    flixn_link.href = "http://flixn.com/";
    flixn_link_d.style.width = "403px";
    flixn_link_d.style.height = "26px";
    flixn_link_d.setAttribute('onclick', 'window.open("http://flixn.com/");');
    flixn_link.appendChild(flixn_link_d);

    var close_link = document.createElement('a');
    close_link.href = "javascript:flixn.closeRecorder();";
//    close_link.setAttribute('onclick', 'flixn.closeRecorder(); return;');

//    var close_link_img = new Image();
    var close_link_img = document.createElement('img');
    close_link_img.setAttribute('id', this.containerId + '_close');
    close_link.appendChild(close_link_img);
    close_link_img.src = this.containerCloseImg;
    container.appendChild(close_link);

    var recorder = document.createElement('div');
    recorder.setAttribute('id', this.recorderId);
    container.appendChild(recorder);

container.appendChild(flixn_link);

    var noflash = document.createElement('a');
    noflash.href = 'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash';
    noflash.target = '_blank';

    var noflashimg = document.createElement('div');
    noflashimg.setAttribute('id', 'flixn_noflash');
    noflash.appendChild(noflashimg);
    recorder.appendChild(noflash);

    document.body.appendChild(container);

    var so = new SWFObject(this._recorderUrl, this.recorderId + '_obj',
                           this._recorderWidth, this._recorderHeight, '8',
                           '#ffffff');
    so.addParam('menu', 'false');
    so.addParam('allowScriptAccess', 'always');
    so.addParam('swLiveConnect', 'true');
    so.write(this.recorderId);
  },

  _hideRecorder: function() {
    document.body.removeChild(document.getElementById(this.containerId));
  },

  _placeRecorder: function() {
    var windowSize = this._getWindowSize();
    this._scrollOffset = this._getScrollOffset();

    x = this._scrollOffset[0] + (windowSize[0] - this.containerWidth)/2;
    y = this._scrollOffset[1] + (windowSize[1] - this.containerHeight)/2;

    var recorder = document.getElementById(this.containerId);
    recorder.style.left = x + 'px';
    recorder.style.top = y + 'px';
  },

  _showRecorder: function() {
    var recorder = document.getElementById(this.containerId);
    recorder.style.display = 'block';
  },

  _insertCode: function(videoId) {
    var handle = this.getInputHandle();
    var inputType = handle.nodeName.toLowerCase();
    var text = this.htmlCode.replace(/{ID}/g, videoId);

    if (inputType == 'textarea') {
      this._insertTextAreaAppend(handle, text, null);
/*      this._insertTextArea(handle, text, this._insertTextAreaArgs); */
    } else if (inputType == 'input') {
      this._setTextInput(handle, text);
    }
  },

  _setVisibilityStylesByTagName: function(tagname, style) {
    objs = document.getElementsByTagName(tagname);
    for (var i = 0; i < objs.length; i++) {
      objs[i].style.visibility = style;
    }
  },

  _getScrollOffset: function() {
    var x = window.pageXOffset || document.documentElement.scrollLeft ||
            document.body.scrollLeft || 0;

    var y = window.pageYOffset || document.documentElement.scrollTop ||
            document.body.scrollLeft || 0;

    return [x, y];
  },

  _getWindowSize: function() {
    var width, height;

    if (window.innerWidth) {
      width = window.innerWidth;
      height = window.innerHeight;
    }

    if (document.documentElement &&
        document.documentElement.clientWidth) {

      cw = document.documentElement.clientWidth;
      if (!width || cw && cw < width) {
        width = cw;
      }
      if (!height) {
        height = document.documentElement.clientHeight;
      }
    } else if (document.body) {
      width = document.body.clientWidth;
      height = document.body.clientHeight;
    }

    return [width, height];
  },

  _fadeObjectIn: function(objectId, targetOpacity, fadeStep,
                          fadeDelay, callback) {

    handle = document.getElementById(objectId);
    currentOpacity = flixn._getOpacity(handle);

    if (currentOpacity >= targetOpacity) {
      eval(callback);
      return;
    }

    newOpacity = currentOpacity + fadeStep;

    flixn._setOpacity(handle, newOpacity);

    var command = 'flixn._fadeObjectIn("' + objectId + '",' +
                                           targetOpacity + ',' +
                                           fadeStep + ',' +
                                           fadeDelay + ',"' +
                                           callback + '")';
    var t = setTimeout(command, fadeDelay);
    if (objectId == this.indicatorId) {
      flixn._indicatorTimer = t;
    }
  },

  _getOpacity: function(handle) {
    return handle.style.opacity * 100;
  },

  // Takes target opacity as a percentage, ie: 60
  _setOpacity: function(handle, opacity) {
    handle.style.MozOpacity = opacity / 100;
    handle.style.opacity = opacity / 100;
    handle.style.filter = 'alpha(opacity=' + opacity + ')';
  },

  _storeTextAreaPos: function(handle) {
/*
    if (handle.createTextRange && handle.caretPos) {
      flixn._insertTextArea = flixn._insertTextAreaCaret;
      flixn._insertTextAreaArgs = handle.caretPos;
    } else if (handle.selectionStart || handle.selectionStart == '0') {
      flixn._insertTextArea = flixn._insertTextAreaPos;
      flixn._insertTextAreaArgs = [handle.selectionStart, handle.selectionEnd]
    } else {
*/
      flixn._insertTextArea = flixn._insertTextAreaAppend;
/*
    }
*/
  },

  _insertTextAreaCaret: function(handle, text, args) {
    args.text = args.text.charAt(args.text.length - 1) == ' ' ?
                args.text + text + ' ' : args.text + text;
    handle.focus();
  },

  _insertTextAreaPos: function(handle, text, args) {
    handle.value = handle.value.substring(0, args[0])
                   + text
                   + handle.value.substring(args[1], handle.value.length);
    handle.focus();
    handle.selectionStart = args[0] + text.length;
    handle.selectionEnd = args[1] + text.length;
  },

  _insertTextAreaAppend: function(handle, text, args) {
    handle.value += text;
    handle.focus();
  },

  _setTextInput: function(handle, text) {
    handle.value = text;
    handle.focus();
  }
};
