var HDAClient = {
  init: function() {
    this.initChrome();

    HDAPlayer.events.loadURL.subscribe(this.handleUrl, this);

    HDAFacePlayer.events.error.subscribe(this.handleError, this);

    HDAPlayer.events.faceHelp.subscribe(function() {
      getElementByIdHDA('hda-textArea').innerHTML = "<p>&nbsp;</p>";
    });
  },
  
  initXMLHttpRequest: 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;
  },
  
  handleError: function(error){
	  if (error == 'connection-failed'){
	    // Call an URL to advice this case
		// WARNING: Since we use AJAX, you cannot call
		// an URL outside the domain from witch this script works
		var URL_TO_NOTIFY = 'http://localhost:8080/brain/player-connection-error.jsp';
		var request = this.initXMLHttpRequest();
		request.open("GET", URL_TO_NOTIFY, true);
		request.send(null);
	  }
  },
  
  handleUrl: function(urlData) {
		if (urlData.method == 'POST') {
			this.handlePostMethod(urlData);
		} else {
			this.handleGetMethod(urlData);
		}
	},
  

  runCustomAction: function(action) {
    // TODO
  },
  
	handleGetMethod: function(urlData) {
		if (urlData.target == '_popup') {
			var popup = window.open(urlData.url, 'name', 'height='
					+ urlData.popup.height + ',width='
					+ urlData.popup.width);
			if (popup && window.focus) {
				popup.focus()
			}
		} else if (urlData.target == '_self') {
			location.href = urlData.url;
		} else if (urlData.target == '_parent') {
			top.opener.location.href = urlData.url;
		} else if (urlData.target == '_blank') {
			popup = window.open(urlData.url);
			if (popup && window.focus) {
				popup.focus()
			}
		} else {
			var doc = top.frames[urlData.target];
			if (doc) {
				doc.location.href = urlData.url;
			} else {
				popup = window.open(urlData.url);
				if (popup && window.focus) {
					popup.focus()
				}
			}
		}		
	},
	
	handlePostMethod: function(urlData) {
		var queryString = urlData.url.split('?');
		var url;
		if(queryString.length > 1) {
			url = queryString[0];
			queryString = queryString[1];
		}else{
			url = queryString[0];
			queryString = null;
		}
		var parameters;
		var keys = [], values = [];

		if (queryString != null){
			parameters = queryString.split('&');
			for(i = 0; i < parameters.length; i++) {
				pair = parameters[i];
				var tmp = pair.split('=');
				keys.push(tmp.shift());
				values.push(tmp.shift());
			};
		}
		
		if (urlData.target == '_popup') {
			var popup = this.openWindowWithPost(url, 'name', keys, values, urlData.popup.height, urlData.popup.width);
			if (popup && window.focus) {
				popup.focus()
			}
		} else if (urlData.target == '_self') {
			this.openUrlWithPost(document, url, keys, values);
		} else if (urlData.target == '_parent') {
			this.openUrlWithPost(top.opener.document, url, keys, values);
		} else if (urlData.target == '_blank') {
			var popup = this.openWindowWithPost(url, 'name', keys, values);
			if (popup && window.focus) {
				popup.focus()
			}
		} else {
			var doc = top.frames[urlData.target];
			if (doc) {
				this.openUrlWithPost(doc, url, keys, values);
			} else {
				var popup = this.openWindowWithPost(url, 'name', keys, values);
				if (popup && window.focus) {
					popup.focus()
				}
			}
		}		
	},

  initChrome: function() {
  // If we are using a table for the buttonset, add a void tr just to add the footer
    var bs=getElementByIdHDA('hda-menu-body')
    if (bs && bs.tagName=='TBODY') {
      var tf=document.createElement('tr')
      tf.id='hda-menu-bottom'
      tf.appendChild(document.createElement('td'))
      bs.appendChild(tf)
    }

    // Create a new scroller widget for the text area
    var scroller = new hda_scroller({
      windowWidth: 170,
      windowHeight: 120,
      container: 'hda-textArea'
    })

    // Bind scroll action to widget
    getElementByIdHDA('hda-textWidgetScrollUp').onmouseover   = function() {scroller.scrollUp()}
    getElementByIdHDA('hda-textWidgetScrollDown').onmouseover = function() {scroller.scrollDown()}
    getElementByIdHDA('hda-textWidgetScrollDown').onmouseout  = function() {scroller.stopScroll()}
    getElementByIdHDA('hda-textWidgetScrollUp').onmouseout    = function() {scroller.stopScroll()}
    getElementByIdHDA('hda-textArea').style.visibility='visible'

    HDAPlayer.events.videoBegin.subscribe(function() {
      scroller.scrollToTop();
    }, this);
  },
  
	openWindowWithPost : function(url, name, keys, values, width, height) {
		var vars = null;
		if(width && height)
			vars = 'height=' + height + ',width=' + width
		var newWindow = window.open(url, name, vars);
		if (!newWindow)
			return false;
		this.openUrlWithPost(newWindow.document, url, keys, values);
		return newWindow;
	},
	
	openUrlWithPost: function(targetDocument, url, keys, values) {
		var html = "";
		html += "<html><head></head><body><form id='formid' method='post' action='"
				+ url + "'>";
		if (keys && values && (keys.length == values.length))
			for (var i = 0; i < keys.length; i++)
				html += "<input type='hidden' name='" + keys[i] + "' value='"
						+ values[i] + "'/>";
		html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</script></body></html>";
		targetDocument.write(html);
	}
  
}

function hda_scroller(options) {
  this.windowWidth=options.windowWidth
  this.windowHeight=options.windowHeight

  this.container=document.getElementById(options.container)

  this.offsetTop=this.container.offsetTop
  this.amount=options.amount || 10
  this.time=options.time || 100
  this.container.style.clip = 'rect(0,'+this.windowWidth+'px, '+this.windowHeight+'px,0)';
  this._top=0
  this._bottom=this.windowHeight
}

hda_scroller.prototype.scrollDown = function() {
  if (this._bottom > this.container.offsetHeight) return;
  this._top    += this.amount;
  this._bottom += this.amount;
  this.offsetTop -= this.amount;
  this.scroll()
  obj=this
  this.to = setTimeout(function() {
    obj.scrollDown()
  }, this.time);
}

hda_scroller.prototype.scrollUp = function() {
  if (this._top <= 0) return
  this._top    -= this.amount;
  this._bottom -= this.amount;
  this.offsetTop += this.amount;
  this.scroll()
  obj=this
  this.to = setTimeout(function() {
    obj.scrollUp()
  }, this.time);
}

hda_scroller.prototype.scroll = function() {
  this.container.style.clip = 'rect('+this._top+'px,'+this.windowWidth+'px,'+this._bottom+'px,0)';
  this.container.style.top = this.offsetTop + 'px';
}

hda_scroller.prototype.stopScroll = function() {
  if (this.to) clearTimeout(this.to);
}

hda_scroller.prototype.scrollToTop = function() {
  this._top = 0;
  this.offsetTop = 0;
  this.scroll();
}
