/*
  parseUri 1.2.1
  (c) 2007 Steven Levithan <stevenlevithan.com>
  MIT License
*/

function parseUri (str) {
  var o   = parseUri.options,
    m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;

  while (i--) uri[o.key[i]] = m[i] || "";

  uri[o.q.name] = {};
  uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
    if ($1) uri[o.q.name][$1] = $2;
  });

  return uri;
};

parseUri.options = {
  strictMode: false,
  key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  q:   {
    name:   "queryKey",
    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
    loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};

function addEvent(obj, type, fn) {
  if (obj.addEventListener) {
     obj.addEventListener(type, fn, false);
  } else if (obj.attachEvent) {
     obj["e"+type+fn] = fn;
     obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
     obj.attachEvent( "on"+type, obj[type+fn] );
  }
};

function sendEvent(swf, typ, prm, norelocation) { 
  var movie = thisMovie(swf);
  if (movie && movie.sendEvent) {
    movie.sendEvent(typ, prm);
    return true;
  } else if (!norelocation) {
    document.location.href='/video/hafen-warnemuende.php';
    return false;
  } else {
    return false;
  }
};

function getUpdate(typ, pr1, pr2, swf) {
  if ('mp1' == swf) {
    mp1VideoController.update(typ, pr1, pr2);
  }
};

function thisMovie(swf) {
//  if (navigator.appName.indexOf("Microsoft") != -1) {
//    return window[swf];
//  } else {
//   	return document[swf];
//  }
return swfobject.getObjectById(swf);
};

/**
 * A cookie handler which can write, retrieve and delete both session
 * and persistent cookies. Adapted from 
 * http://www.braemoor.co.uk/software/cookies.shtml
 *
 * Routines written by John Gardner - 2003 - 2005; See 
 * www.braemoor.co.uk/software for information about more freeware available.
 *
 * @constructor
 */
function CookieHandler() {
}

/**
 * Test if a session cookie can be written
 * 
 * @return A boolean indicating if a session cookie can be written
 */
CookieHandler.prototype.testSessionCookie = function() {
  document.cookie="testSessionCookie=Enabled";
  if (this.getCookieValue("testSessionCookie") == "Enabled")
    return true 
  else
    return false;
}

/**
 * Write a session cookie
 *
 * @param (String) cookieName
 * @param (String) cookieValue
 */
CookieHandler.prototype.writeSessionCookie = function(cookieName, cookieValue) {
  document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
}

/**
 * Get a cookie value
 *
 * @param (String) cookieName
 * @return Either a String containing the cookie's contents or a boolean false
 */
CookieHandler.prototype.getCookieValue = function(cookieName) {
  var exp = new RegExp(escape(cookieName) + "=([^;]+)");
  if (exp.test(document.cookie + ";")) {
    exp.exec(document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/**
 * Test if a persistent cookie can be written
 *
 * @return A boolean indicating if a persistent cookie can be written
 */
CookieHandler.prototype.testPersistentCookie = function() {
  this.writePersistentCookie("testPersistentCookie", "Enabled", "minutes", 1);
  if (this.getCookieValue("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/**
 * Write a persistent cookie
 *
 * @param (String) cookieName
 * @param (String) cookieValue
 * @param (String) periodType - one of 'years', 'months', 'days', 'hours', 'minutes'
 * @param (Integer) offset
 */
CookieHandler.prototype.writePersistentCookie = function(CookieName, CookieValue, periodType, offset) {
  var expireDate = new Date();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years": 
     var year = expireDate.getYear();     
     // Note some browsers give only the years since 1900, and some since 0.
     if (year < 1000) year = year + 1900;     
     expireDate.setYear(year + offset);
     break;
    case "months":
      expireDate.setMonth(expireDate.getMonth() + offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate() + offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours() + offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes() + offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
};

/**
 * Delete a cookie
 * Actually the cookie's lifetime will be set to value in history
 *
 * @param (String) cookieName
 * @return A boolean indicating if the cookie was deleted successfully
 */
CookieHandler.prototype.deleteCookie = function(cookieName) {
  if (this.getCookieValue(cookieName)) {
    this.writePersistentCookie(cookieName, "Pending delete", "years", -1);
    return true;
  } else {
    return false;
  }     
};


/**
 * A video controller to write a session cookie if the video was run successfully
 *
 * @constructor
 */
function HoheDueneClusterVideoController() {
  this.cookieName = 'HoheDueneVideoGespielt';
  this.cookieHandler = cookieHandler; // Use globally accessible cookieHandler
  this.autorunOnArray = new Array();
};

HoheDueneClusterVideoController.prototype.setAutorunOnArray = function(arr) {
  this.autorunOnArray = arr;
};

HoheDueneClusterVideoController.prototype.checkAutorun = function(itemIdx, videoId) {
  if ('undefined' == mp1VideoController) return false;
  
  var path = parseUri(document.location.href).path;
  var existingCookie = this.cookieHandler.getCookieValue(this.cookieName);
  if (existingCookie) {
    var existingValues = existingCookie.split('|');
    for (var i = 0; i < existingValues.length; i++) {
      if (videoId == existingValues[i]) return false;
    }
  }
  
  for (var i = 0; i < this.autorunOnArray.length; i++) {
    if (path == this.autorunOnArray[i]) {
      window.setTimeout(function() { mp1VideoController.play(); }, 1000);
      return true;
    }
  }
  
  return false;
};

HoheDueneClusterVideoController.prototype.videoPlayed = function(videoId) {
  var existingCookie = this.cookieHandler.getCookieValue(this.cookieName);
  var existingValues = new Array();
  if (existingCookie) {
    existingValues = existingCookie.split('|');
  }
  
  // Check if videoId is already in the cookie
  for (i = 0; i < existingValues.length; i++) {
    if (existingValues[i] == videoId) return true;
  }
  
  // Add videoId
  existingValues[existingValues.length] = videoId;
  
  // Write session cookie
  this.cookieHandler.writeSessionCookie(this.cookieName, existingValues.join('|'));
};

function VideoController(swfId, volumeSliderWidth, volumeScrubberWidth, timelineWidth, timelineScrubberWidth) {
  this.volumeSliderWidth = volumeSliderWidth;
  this.volumeScrubberWidth = volumeScrubberWidth;
  this.timelineWidth = timelineWidth;
  this.timelineScrubberWidth = timelineScrubberWidth;
  
  this.volumeScrubber = document.getElementById(swfId + '_volume_scrubber');
  this.soundControl = document.getElementById(swfId + '_sound');
  this.volumeSlider = document.getElementById(swfId + '_volume');
  this.playPauseButton = document.getElementById(swfId + '_playpause');
  this.timelineScrubber = document.getElementById(swfId + '_timeline_scrubber');
  this.time = document.getElementById(swfId + '_time');

  this.swfId = swfId;
  this.volume = null;
  this.load = 0;
  this.state = null;
  this.duration = null;
  this.durationString = null;
  this.itemIdx = null;
  this.file = null;
  
  this.onUpdateItemFunctions = new Array();
  
  // Attach events to buttons
  var me = this;
  
  if (this.playPauseButton) {
    var tmpTogglePlayPause = function() { me.togglePlayPause(); }
    addEvent(this.playPauseButton, 'click', tmpTogglePlayPause);
  }

  if (this.soundControl) {
    var tmpToggleSound = function() { me.toggleSound(); }
    addEvent(this.soundControl, 'click', tmpToggleSound);
  }
};

VideoController.prototype.updateTime = function(elapsed, remaining) {
  if (!this.duration) {
    this.setDuration(elapsed + remaining);
  }
  
  if (this.timelineScrubber) {
    var w = Math.round((this.duration > 0 ? (elapsed / this.duration) : 0) * 100);
    w = w > 100 ? 100 : w;
    this.timelineScrubber.style.width = w + '%';
  }
  
  // Gespielte Zeit und Gesamtdauer anpassen
  if (!this.time) return false;
  
  // Sekunden in Minuten umrechnen
  var elapsedMinutes = Math.floor(elapsed / 60);
  var elapsedSeconds = elapsed % 60;

  var data =
    elapsedMinutes + 
    ':' + 
    (elapsedSeconds < 10 ? '0' : '') + 
    elapsedSeconds + 
    '/' + 
    this.durationString;
  
  this.time.firstChild.data = data;
  return true;
};

VideoController.prototype.stop = function() {
  var swf = thisMovie && thisMovie(this.swfId);
  if (swf && (this.load < 100 || this.state > 0)) {
    sendEvent(this.swfId, 'stop', null, true);
    this.load = 100;
  }
};

VideoController.prototype.updateVolume = function(vol) {
  this.volume = vol;
  
  if (this.soundControl) {
    if (0 == this.volume) {
      this.soundControl.style.backgroundPosition = '-62px 0';
      this.soundControl.title = 'Ton ausgeschaltet';
    } else {
      this.soundControl.style.backgroundPosition = '-80px 0';
      this.soundControl.title = 'Ton eingeschaltet';
    }
  }

  if (this.volumeScrubber) {
    var scrubberPosition = ((this.volumeSliderWidth - this.volumeScrubberWidth) * this.volume) / 100;
    this.volumeScrubber.style.left = Math.round(scrubberPosition) + 'px';
  }
  
  return true;
};

VideoController.prototype.updateLoad = function(load) {
  this.load = load;
};

VideoController.prototype.updateState = function(state) {
  if (!this.playPauseButton) return false;
  this.state = state;
  
  switch (this.state) {
    case 0: // Film gestoppt
      this.playPauseButton.style.backgroundPosition = '-31px 0';
      this.playPauseButton.title = 'Abspielen';
      return true;
    case 1: // Film wird geladen
    case 2: // Film läuft
      this.playPauseButton.style.backgroundPosition = '0 0';
      this.playPauseButton.title = 'Stopp';
      if (this.movieRuns) this.movieRuns();
      return true;
    default:
      return false;
  }
  
  return true;
};

VideoController.prototype.updateItem = function(itemIdx) {
  this.itemIdx = itemIdx;
  this.retrieveData();
  this.setDuration(0);
  
  for (var i = 0; i < this.onUpdateItemFunctions.length; i++) {
    this.onUpdateItemFunctions[i](itemIdx, this.file);
  }
  
  return true;
};

VideoController.prototype.addOnUpdateItemFunction = function(f) {
  this.onUpdateItemFunctions[this.onUpdateItemFunctions.length] = f;
};

VideoController.prototype.setDuration = function(duration) {
  this.duration = duration;
  var secs = this.duration % 60;
  var mins = Math.floor(this.duration / 60);
  this.durationString = mins + ':' + (secs < 10 ? '0' : '') + secs;
};

VideoController.prototype.retrieveData = function() {
  var data = thisMovie(this.swfId).itemData(this.itemIdx);
  for (var i in data) {
    switch (i) {
      case 'duration': this.duration = data[i]; break;
      case 'file': this.file = data[i]; break;
      default: break;
    }
  }
};

VideoController.prototype.update = function(typ, pr1, pr2) {
  switch (typ) {
    case 'state': this.updateState(pr1); break;
    case 'volume': this.updateVolume(pr1); break;
    case 'item': this.updateItem(pr1); break;
    case 'time': this.updateTime(pr1, pr2); break;
    case 'load': this.updateLoad(pr1); break;
    default: break;
  }
};

VideoController.prototype.toggleSound = function() {
  if (0 == this.volume) {
    sendEvent(this.swfId, 'volume', 80, true);
  } else {
    sendEvent(this.swfId, 'volume', 0, true);
  }
};

VideoController.prototype.togglePlayPause = function() {
  sendEvent(this.swfId, 'playpause');
};

VideoController.prototype.play = function() {
  if (2 != this.state) { sendEvent(this.swfId, 'playpause', null, true); };
};

var cookieHandler = new CookieHandler();
var hoheDueneClusterVideoController = new HoheDueneClusterVideoController();
hoheDueneClusterVideoController.setAutorunOnArray(new Array(
  '/',
  '/index.html',
  '/hotels-ostsee-hd.html',
  '/wellnesshotel-ostsee-index.html',
  '/ostseeurlaub-index.html',
  '/ostsee-kurzurlaub-yachthafen.html',
  '/tagungshotels-index.html',
  '/kurzurlaub-hd.html',
  '/hotel-arrangement-index.html'
));

mp1VideoController = new VideoController('mp1', 0, 0, 197, 0);
mp1VideoController.movieRuns = function() {
  hoheDueneClusterVideoController.videoPlayed(this.file);
};

mp1VideoController.addOnUpdateItemFunction(function(itemIdx, videoId) {
  hoheDueneClusterVideoController.checkAutorun(itemIdx, videoId);
});