/*
 * livespotting.tv player embedding
 * version 1.0.2 (2011/11/03)
 * Steffen Beyer <s.beyer@windit.de>
 *
 * requires jQuery library to be loaded
 *
 * invocation:
 *
 * <div id="player" style="width: 400px; height: 300px;"></div>
 * <script type="text/javascript">
 *   $('#player').livespottingPanning({
 *     playerID: 42,
 *     videoScale: 0.8,
 *     tooltipClose: 'Close'
 *   });
 * </script>
 *
 * The only mandatory option is 'playerID.' Other options:
 *
 * videoWidthPx, videoHeightPx    explicitly set video dimensions in pixel
 *  - or -
 * videoScale                     set video scaling factor (0 < x <= 1)
 *
 * tooltipClose                   tooltip for the lightbox close button
 *
 * lightboxZoomSpeed              speed of lightbox zoom effect ("slow", "default", "fast" or duration in ms)
 *
 * backgroundCoverFadingSpeed     speed of background fading effect ("slow", "default", "fast" or duration in ms)
 *
 * backgroundCoverOpacity         set the level of background darkening (0 <= x <= 1)
 *                                0 = no darkening, 1 = black background
 *
 * imagePath                      image directory
 *
 */

(function($) {
  $.fn.livespottingPanning = function(options) {

    var LS_PLAYER_BORDER_WIDTH  = 6;
    var LS_PLAYER_BORDER_HEIGHT = 51;

    var settings = $.extend({
      // defaults
      lightboxZoomSpeed:          500,  // [ms]
      backgroundCoverFadingSpeed: 500,  // [ms]
      backgroundCoverOpacity:     0.6,
      imagePath:                  'images'
    }, options);

    if (! settings.playerID) {
      alert('livespottingPan: no playerID specified!');
      return;
    }

    var playerActive = false;   // player currently active?

    var
      sourceVideoWidthPx,   // original video dimensions (also used for image)
      sourceVideoHeightPx,
      wantedVideoWidthPx,   // overridable video dimensions for lightbox/player (border gets added)
      wantedVideoHeightPx,
      windowWidthPx,        // preview window dimensions
      windowHeightPx;

    return this.each(function() {
      var target = $(this);
      target.css('overflow', 'hidden');

      $.ajax({
        url: 'http://www.livewind.de/config/' + settings.playerID + '.xml',
        dataType: 'xml',

        success: function(xml) {
          sourceVideoWidthPx  = parseInt( $('videowidth', xml).text() )  || 640;
          sourceVideoHeightPx = parseInt( $('videoheight', xml).text() ) || 480;

          if ( settings.videoWidthPx && settings.videoHeightPx ) {
            wantedVideoWidthPx  = settings.videoWidthPx;
            wantedVideoHeightPx = settings.videoHeightPx;
          } else if ( settings.videoScale ) {
            wantedVideoWidthPx  = sourceVideoWidthPx * settings.videoScale;
            wantedVideoHeightPx = sourceVideoHeightPx * settings.videoScale;
          } else {
            wantedVideoWidthPx  = sourceVideoWidthPx;
            wantedVideoHeightPx = sourceVideoHeightPx;
          }

          windowWidthPx  = target.width();
          windowHeightPx = target.height();

          var img = $(document.createElement('img')).appendTo(target);
          img.attr( 'src', 'http://api.livespotting.tv/v1/video/snapshot/vv' + $('videoid', xml).text() + '.jpg' );
          img.attr( 'width', sourceVideoWidthPx );
          img.attr( 'height', sourceVideoHeightPx );
          img.css({
            position: 'relative',
            cursor:   "url('" + settings.imagePath + "/magnifier.png'), pointer"
          });

          setImageOffset( windowWidthPx / 2, windowHeightPx / 2, img );

          target.mousemove(function(e) {
            if (! playerActive) {
              var relX = e.pageX - target.offset().left;
              var relY = e.pageY - target.offset().top;
              setImageOffset( relX, relY, img );
            }
          });

          img.livespottingZoom({
            contentCallback: function( container ) {
              container.livespottingFlash({
                swf:               'http://livespotting.tv/stream/TEMPLATE/stealthplayer.swf',
                width:             wantedVideoWidthPx + LS_PLAYER_BORDER_WIDTH,
                height:            wantedVideoHeightPx + LS_PLAYER_BORDER_HEIGHT,
                quality:           'high',
                bgcolor:           '#ffffff',
                allowscriptaccess: 'always',
                allowfullscreen:   'true',
                flashvars: {
                  playerID: settings.playerID
                }
              });
            },
            openCallback: function() {
              playerActive = true;
            },
            closeCallback: function() {
              playerActive = false;
            },
            width:                      wantedVideoWidthPx + LS_PLAYER_BORDER_WIDTH,
            height:                     wantedVideoHeightPx + LS_PLAYER_BORDER_HEIGHT,
            zoomSpeed:                  settings.lightboxZoomSpeed,
            backgroundCoverFadingSpeed: settings.backgroundCoverFadingSpeed,
            backgroundCoverOpacity:     settings.backgroundCoverOpacity,
            tooltipClose:               settings.tooltipClose,
            directory:                  settings.imagePath
          });
        },

        error: function(request, state, error) {
          alert( 'livespottingPan: XML request failed (' + state + (error ? ', ' + error : '') + ')' );
        }
      });
    });

    function setImageOffset( pointerX, pointerY, img ) {
      img.css({
        left: -( pointerX / windowWidthPx ) * ( sourceVideoWidthPx - windowWidthPx ),
        top: -( pointerY / windowHeightPx ) * ( sourceVideoHeightPx - windowHeightPx )
      });
    };
  };
}(jQuery));

// lightbox is based on FancyZoom by John Nunemaker and others
// http://github.com/jnunemaker/fancy-zoom

(function($){
$.fn.livespottingZoom = function(options){

  var options      = options || {};
  var directory    = options && options.directory ? options.directory : 'images';
  var tooltipClose = options && options.tooltipClose ? options.tooltipClose : 'Schlie&szlig;en';
  var zooming      = false;

  if ($('#ls_zoom').length == 0) {
    var ext = $.browser.msie ? 'gif' : 'png';
    var html = '<div id="ls_zoom" style="display: none; z-index: 30001"> \
                  <table id="ls_zoom_table" style="border-collapse:collapse; width:100%; height:100%;"> \
                    <tbody> \
                      <tr> \
                        <td class="tl" style="background:url(' + directory + '/tl.' + ext + ') 0 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="tm" style="background:url(' + directory + '/tm.' + ext + ') 0 0 repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="tr" style="background:url(' + directory + '/tr.' + ext + ') 100% 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="ml" style="background:url(' + directory + '/ml.' + ext + ') 0 0 repeat-y; width:20px; overflow:hidden;" /> \
                        <td class="mm" style="background:#fff; vertical-align:top; padding:10px;"> \
                          <div id="ls_zoom_content"> \
                          </div> \
                        </td> \
                        <td class="mr" style="background:url(' + directory + '/mr.' + ext + ') 100% 0 repeat-y;  width:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="bl" style="background:url(' + directory + '/bl.' + ext + ') 0 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="bm" style="background:url(' + directory + '/bm.' + ext + ') 0 100% repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="br" style="background:url(' + directory + '/br.' + ext + ') 100% 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                    </tbody> \
                  </table> \
                  <a href="#" title="' + tooltipClose + '" id="ls_zoom_close" style="position:absolute; top:0; left:0;"> \
                    <img src="' + directory + '/closebox.' + ext + '" alt="' + tooltipClose + '" style="border:none; margin:0; padding:0;" /> \
                  </a> \
                </div>';

    $('body').append(html);

    // conflicts with FlashBlock et al.
    // $('html').click(function(e){if($(e.target).parents('#ls_zoom:visible').length == 0) hide();});

    $(document).keyup(function(event){
        if (event.keyCode == 27 && $('#ls_zoom:visible').length > 0) hide();
    });

    $('#ls_zoom_close').click(hide);

    var cover_layer = $('<div id="ls_cover_layer">&nbsp;</div>');
    $('body').append( cover_layer );
    cover_layer.css({
      position:           'absolute',
      top:                0,
      left:               0,
      width:              '100%',
      height:             '100%',
      'z-index':          30000,
      display:            'none',
      'background-color': '#000000'
    });
  }

  var zoom          = $('#ls_zoom');
  var zoom_table    = $('#ls_zoom_table');
  var zoom_close    = $('#ls_zoom_close');
  var zoom_content  = $('#ls_zoom_content');
  var middle_row    = $('td.ml,td.mm,td.mr');

  this.each(function(i) {
    $($(this).attr('href')).hide();
    $(this).click(show);
  });

  return this;

  function show(e) {
    if (zooming) return false;
    zooming = true;
    options.openCallback();

    $("#ls_cover_layer").fadeTo( options.backgroundCoverFadingSpeed, options.backgroundCoverOpacity );

    var zoom_width  = options.width;
    var zoom_height = options.height;

    var width       = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
    var height      = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
    var x           = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
    var y           = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
    var window_size = {'width':width, 'height':height, 'x':x, 'y':y}

    var width              = (zoom_width || content_div.width()) + 60;
    var height             = (zoom_height || content_div.height()) + 60;
    var d                  = window_size;

    // ensure that newTop is at least 0 so it doesn't hide close button
    var newTop             = Math.max((d.height/2) - (height/2) + y, 0);
    var newLeft            = (d.width/2) - (width/2);
    var curTop             = e.pageY;
    var curLeft            = e.pageX;

    zoom_close.attr('curTop', curTop);
    zoom_close.attr('curLeft', curLeft);

    $('#ls_zoom').hide().css({
      position  : 'absolute',
      top       : curTop + 'px',
      left      : curLeft + 'px',
      width     : '1px',
      height    : '1px'
    });

    fixBackgroundsForIE();
    zoom_close.hide();

    if (options.closeOnClick) {
      $('#ls_zoom').click(hide);
    }

    zoom_content.empty();

    $('#ls_zoom').animate({
      top     : newTop + 'px',
      left    : newLeft + 'px',
      opacity : "show",
      width   : width,
      height  : height
    }, options.zoomSpeed, null, function() {
      options.contentCallback( zoom_content );
      unfixBackgroundsForIE();
      zoom_close.show();
      zooming = false;
    })
    return false;
  }

  function hide() {
    if (zooming) return false;
    zooming         = true;
    $('#ls_zoom').unbind('click');
    fixBackgroundsForIE();
    zoom_content.empty();
    zoom_close.hide();
    $("#ls_cover_layer").fadeOut( options.backgroundCoverFadingSpeed );
    $('#ls_zoom').animate({
      top     : zoom_close.attr('curTop') + 'px',
      left    : zoom_close.attr('curLeft') + 'px',
      opacity : "hide",
      width   : '1px',
      height  : '1px'
    }, options.zoomSpeed, null, function() {
      unfixBackgroundsForIE();
      options.closeCallback();
      zooming = false;
    });
    return false;
  }

  function switchBackgroundImagesTo(to) {
    $('#ls_zoom_table td').each(function(i) {
      var bg = $(this).css('background-image').replace(/\.(png|gif|none)\"\)$/, '.' + to + '")');
      $(this).css('background-image', bg);
    });
    var close_img = zoom_close.children('img');
    var new_img = close_img.attr('src').replace(/\.(png|gif|none)$/, '.' + to);
    close_img.attr('src', new_img);
  }

  function fixBackgroundsForIE() {
    if ($.browser.msie && parseFloat($.browser.version) >= 7) {
      switchBackgroundImagesTo('gif');
    }
  }

  function unfixBackgroundsForIE() {
    if ($.browser.msie && $.browser.version >= 7) {
      switchBackgroundImagesTo('png');
    }
  }
}
})(jQuery);

// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject

(function($, flash, Plugin) {
  var OBJECT = 'object',
    ENCODE = true;

  function _compareArrayIntegers(a, b) {
    var x = (a[0] || 0) - (b[0] || 0);

    return x > 0 || (
      !x &&
      a.length > 0 &&
      _compareArrayIntegers(a.slice(1), b.slice(1))
    );
  }

  function _objectToArguments(obj) {
    if (typeof obj != OBJECT) {
      return obj;
    }

    var arr = [],
      str = '';

    for (var i in obj) {
      if (typeof obj[i] == OBJECT) {
        str = _objectToArguments(obj[i]);
      }
      else {
        str = [i, (ENCODE) ? encodeURI(obj[i]) : obj[i]].join('=');
      }

      arr.push(str);
    }

    return arr.join('&');
  }

  function _objectFromObject(obj) {
    var arr = [];

    for (var i in obj) {
      if (obj[i]) {
        arr.push([i, '="', obj[i], '"'].join(''));
      }
    }

    return arr.join(' ');
  }

  function _paramsFromObject(obj) {
    var arr = [];

    for (var i in obj) {
      arr.push([
        '<param name="', i,
        '" value="', _objectToArguments(obj[i]), '" />'
      ].join(''));
    }

    return arr.join('');
  }

  try {
    var flashVersion = Plugin.description || (function () {
      return (
        new Plugin('ShockwaveFlash.ShockwaveFlash')
      ).GetVariable('$version');
    }())
  }
  catch (e) {
    flashVersion = 'Unavailable';
  }

  var flashVersionMatchVersionNumbers = flashVersion.match(/\d+/g) || [0];

  $[flash] = {
    available: flashVersionMatchVersionNumbers[0] > 0,

    activeX: Plugin && !Plugin.name,

    version: {
      original: flashVersion,
      array: flashVersionMatchVersionNumbers,
      string: flashVersionMatchVersionNumbers.join('.'),
      major: parseInt(flashVersionMatchVersionNumbers[0], 10) || 0,
      minor: parseInt(flashVersionMatchVersionNumbers[1], 10) || 0,
      release: parseInt(flashVersionMatchVersionNumbers[2], 10) || 0
    },

    hasVersion: function (version) {
      var versionArray = (/string|number/.test(typeof version))
        ? version.toString().split('.')
        : (/object/.test(typeof version))
          ? [version.major, version.minor]
          : version || [0, 0];

      return _compareArrayIntegers(
        flashVersionMatchVersionNumbers,
        versionArray
      );
    },

    encodeParams: true,

    expressInstall: 'expressInstall.swf',
    expressInstallIsActive: false,

    create: function (obj) {
      var instance = this;

      if (
        !obj.swf ||
        instance.expressInstallIsActive ||
        (!instance.available && !obj.hasVersionFail)
      ) {
        return false;
      }

      if (!instance.hasVersion(obj.hasVersion || 1)) {
        instance.expressInstallIsActive = true;

        if (typeof obj.hasVersionFail == 'function') {
          if (!obj.hasVersionFail.apply(obj)) {
            return false;
          }
        }

        obj = {
          swf: obj.expressInstall || instance.expressInstall,
          height: 137,
          width: 214,
          flashvars: {
            MMredirectURL: location.href,
            MMplayerType: (instance.activeX)
              ? 'ActiveX' : 'PlugIn',
            MMdoctitle: document.title.slice(0, 47) +
              ' - Flash Player Installation'
          }
        };
      }

      attrs = {
        data: obj.swf,
        type: 'application/x-shockwave-flash',
        id: obj.id || 'flash_' + Math.floor(Math.random() * 999999999),
        width: obj.width || 320,
        height: obj.height || 180,
        style: obj.style || ''
      };

      ENCODE = typeof obj.useEncode !== 'undefined' ? obj.useEncode : instance.encodeParams;

      obj.movie = obj.swf;
      obj.wmode = obj.wmode || 'opaque';

      delete obj.fallback;
      delete obj.hasVersion;
      delete obj.hasVersionFail;
      delete obj.height;
      delete obj.id;
      delete obj.swf;
      delete obj.useEncode;
      delete obj.width;

      var flashContainer = document.createElement('div');

      flashContainer.innerHTML = [
        '<object ', _objectFromObject(attrs), '>',
        _paramsFromObject(obj),
        '</object>'
      ].join('');

      return flashContainer.firstChild;
    }
  };

  $.fn[flash] = function (options) {
    var $this = this.find(OBJECT).andSelf().filter(OBJECT);

    if (/string|object/.test(typeof options)) {
      this.each(
        function () {
          var $this = $(this),
            flashObject;

          options = (typeof options == OBJECT) ? options : {
            swf: options
          };

          options.fallback = this;

          flashObject = $[flash].create(options);

          if (flashObject) {
            $this.children().remove();

            $this.html(flashObject);
          }
        }
      );
    }

    if (typeof options == 'function') {
      $this.each(
        function () {
          var instance = this,
          jsInteractionTimeoutMs = 'jsInteractionTimeoutMs';

          instance[jsInteractionTimeoutMs] =
            instance[jsInteractionTimeoutMs] || 0;

          if (instance[jsInteractionTimeoutMs] < 660) {
            if (instance.clientWidth || instance.clientHeight) {
              options.call(instance);
            }
            else {
              setTimeout(
                function () {
                  $(instance)[flash](options);
                },
                instance[jsInteractionTimeoutMs] + 66
              );
            }
          }
        }
      );
    }

    return $this;
  };
}(
  jQuery,
  'livespottingFlash',
  navigator.plugins['Shockwave Flash'] || window.ActiveXObject
));

