// Version: $Id: omxnordicexchange.js,v 1.3 2008/06/09 10:38:47 MTST Exp $

// General variables

//dev
//var xsltAjaxUrl = "/infoglueDeliverWorking/utils/xml2json";
//var omxBaseUrl = "/infoglueDeliverWorking/";
//prod
var xsltAjaxUrl = "/utils/xml2json";
var omxBaseUrl = "/";

//-----------------------------------------------------------
// MyList Cookie Function
// Author: igor.stevstedt@omxgroup.com / igor.stevstedt@it-huset.se
// Description: javascript for cookie handling of mylist

var txtAdd = "Add to my list";
var txtRemove = "Remove from my list";
// Properties
var myListCookieName = "myInstrCookie";
var instrlist = getCookie(myListCookieName);
var theDate = new Date();
var dFuture = new Date( theDate.getTime() + 30758400000 );
var dPast = new Date( theDate.getTime() - 30758400000 );
var cookieExpires = dFuture.toGMTString();
var cookieDeleteExpires = dPast.toGMTString();

function setMyListLang(sAdd,sRemove) 
{
	txtAdd = sAdd;
	txtRemove = sRemove;
}

function setCookie(name, value, expires, path, domain, secure) 
{
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	"; domain=omxnordicexchange.com" +
	((secure) ? "; secure" : "");
	document.cookie = curCookie; 
} 

function getCookie(name) 
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) 
	{
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} 
	else
	begin += 2;
	
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
	end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) 
{
	if (getCookie(name)) 
	{
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=" + cookieDeleteExpires;
	}
}

// submitright on enter
function enterSubmit( event ) {
  if ( event.keyCode == 13 ) {
    searchSubmit();
  }
} 

// searchengine
function searchSubmit() {
  var searchText = trimAll(document.getElementById('searchword').value);
  
  if(searchText.length>0)
  {
	  if ( ( searchText.indexOf( '#' ) != -1 ) || ( searchText.indexOf( '%23' ) != -1 )
		|| ( searchText.indexOf( '<' ) != -1 ) || ( searchText.indexOf( '>' ) != -1 ) ) {
		searchText = searchText.replace( /#/g, '' );
		searchText = searchText.replace( /%23/g, '' );
		searchText = searchText.replace( />/g, '' );
		searchText = searchText.replace( /</g, '' );
		document.getElementById('searchword').value = searchText;
	  }
	  document.getElementById('searchFormId').submit();
  }
}


/* Used for retrieving cookies and request params */
function getParam(queryString, param,divider) {
	if (queryString.length>0) {
		var begin = queryString.indexOf(param+"=");
		if (begin !=-1) {
			begin += (param.length+1);
			var end = queryString.indexOf(divider,begin);
			end = (end == -1) ? queryString.length : end; 
		}
		return unescape(queryString.slice(begin,end));
	} 
	return "";
}

function fixDate(date)  {
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0)
    date.setTime(date.getTime() - skew);
}

function addremoveInstrument(instrumentId,callerId) {
	var mode;
	instrlist = getCookie(myListCookieName);

	if (instrlist != null) // cookie exists
	{
		if (instrlist.indexOf(instrumentId) >= 0) //instrument exists, remove
		{
			var regx = new RegExp(instrumentId +"#","g");
			var newinstrlist = instrlist.replace(regx,"");
			setCookie(myListCookieName, newinstrlist,cookieExpires,"/");
			mode = "add";
		}
		else if (instrlist.indexOf(instrumentId) == -1) // instrument does not exist, add
		{
			setCookie(myListCookieName, instrumentId +"#"+ instrlist,cookieExpires,"/");
			mode = "remove";
		}
	}
	else // empty cookie
	{
		setCookie(myListCookieName, instrumentId +"#",cookieExpires,"/");
		mode = "remove";
	}

	if (callerId != null)
	{
		if (mode == "remove")
		{
			document.getElementById(callerId).innerHTML = "<div id='dummy' class='mylist_remove' title='"+ txtRemove +"'></div>";
		}
		else
		{
			document.getElementById(callerId).innerHTML = "<div id='dummy' class='mylist_add' title='"+ txtAdd +"'></div>";
		}
	}
}

function renderMyListAction(instrumentId)
{
	var output = "";
	var linktxt = "";
	var title = "";
	if (instrlist != null)
	{
		if (instrlist.indexOf(instrumentId) >= 0) //instrument exists
		{
			title = " title='"+ txtRemove +"' "; 
			linktxt = "<div id='dummy' class='mylist_remove' "+ title +"></div>";
		}
		else // instrument does not exist
		{
			title = " title='"+ txtAdd +"' "; 
			linktxt = "<div id='dummy' class='mylist_add' "+ title +"></div>";
		}
	}
	else // instrument does not exist
	{
		title = " title='"+ txtAdd +"' "; 
		linktxt = "<div id='dummy' class='mylist_add' "+ title +"></div>";
	}
	
	var divs = document.getElementById(instrumentId);
	if (divs) 
	{
		output = "";
	}
	else
	{
		output += "<div style=\"cursor: pointer; cursor: hand;\" id='"+ instrumentId +"' onclick=\"addremoveInstrument('"+ instrumentId +"',this.id)\" onmouseover=\"window.status=''; return true;\" onmouseout=\"window.status=''; return true;\" "+ title +">"+ linktxt +"</div>";
	}
	
	document.write(output);
}

function myListIsSelected(instrumentId) {
	if (instrlist != null)
	{
		if (instrlist.indexOf(instrumentId) >= 0) //instrument exists
		{
			document.getElementById(instrumentId).className='mylist_remove';
			document.getElementById(instrumentId).title = txtRemove;
		}
	}
}

function refreshCookie() {
	instrlist = getCookie(myListCookieName);
}

function trimAll(sString)
{
 while (sString.substring(0,1) == ' ')
 {
 sString = sString.substring(1, sString.length);
 }
 while (sString.substring(sString.length-1, sString.length) == ' ')
 {
 sString = sString.substring(0,sString.length-1);
 }
 return sString;
}
//-----------------------------------------------------------
// MyList Cookie Function End
//-----------------------------------------------------------
//-----------------------------------------------------------
// Author: mathias.stalas@nasdaqomx.com / mathias.stalas@dynabyte.se
// Description: Holds the ticker logic for omxnordicexchange.com
// TickerComponent Start
//-----------------------------------------------------------
function Inst(id, nm, fnm, isin, ch, chp, lsp, cr,
			  incBg, fallBg, unchBg, 
			  incImg, fallImg, unchImg,
			  fontFace, fontSize) {
	this.id = id;
	this.nm = nm;
	this.fnm = fnm;
	this.isin = isin;
	this.ch = ch;
	this.chp = chp;
	this.lsp = lsp;
	this.cr = cr;
	this.attributes = [id, nm, fnm, isin, ch, chp, lsp];
	this.incBg = isDefault(incBg, "0000FF");
	this.fallBg = isDefault(fallBg, "FF0000");
	this.unchBg = isDefault(unchBg, "000000");
	this.incImg = incImg;
	this.fallImg = fallImg;
	this.unchImg = unchImg;
	this.fontFace = isDefault(fontFace, "Verdana");
	this.fontSize = isDefault(fontSize, 2);
}

Inst.prototype.getImage = function() {
	if (this.chp > 0) return this.incImg;
	else if (this.chp < 0) return this.fallImg;
	else return this.unchImg;
}

Inst.prototype.getColor = function() {
	if (this.chp > 0) return this.incBg;
	else if (this.chp < 0) return this.fallBg;
	else return this.unchBg;
}

Inst.prototype.getId = function() {return this.id;}
Inst.prototype.getNM = function() {return this.nm;}
Inst.prototype.getFNM = function() {return this.fnm;}
Inst.prototype.getISIN = function() {return this.isin;}
Inst.prototype.getCH = function() {return this.ch;}
Inst.prototype.getCHP = function() {return this.chp;}
Inst.prototype.getLSP = function() {return this.lsp;}
Inst.prototype.getCR = function() {return this.cr;}
Inst.prototype.getIncBg = function() {return this.incBg;}
Inst.prototype.getFallBg = function() {return this.fallBg;}
Inst.prototype.getUnchBg = function() {return this.unchBg;}
Inst.prototype.getIncImg = function() {return this.incImg;}
Inst.prototype.getFallImg = function() {return this.fallImg;}
Inst.prototype.getUnchImg = function() {return this.unchImg;}
Inst.prototype.getFontFace = function() {return this.fontFace;}
Inst.prototype.getFontSize = function() {return this.fontFace;}

function Ticker(id, width, height, bgColor, sleep, steps, separator) {
	this.ref = document.getElementById(id);
	this.width = width = isDefault(width, 710);
	this.height = height = isDefault(height, 20);
	clip(this.ref, 0, width, height, 0);
	this.ref.style.backgroundColor = "#" + isDefault(bgColor, "FFFFFF");
	this.left = this.ref.offsetLeft;
	this.top = this.ref.offsetTop;
	this.width = this.ref.offsetWidth;
	this.sleep = isDefault(sleep, 40) // thread sleep, ms
	this.steps = isDefault(steps, 1); // xpos steps for child layers
	this.separator = separator;
	this.lastOut = null;// reference to the last layer that went out of bounds a container rect perspective(xpos)
	this.timer = null;
	this.block = false;
	this.containerIsLoaded = false;	
	this.contentContainers = null;// array for container div elements
	this.calculateBugg = false;
}

Ticker.prototype.tick = function() {
	if (!this.block) {
		var ctx = this;
		this.timer = window.setTimeout(
			function() {
				var length = ctx.contentContainers.length;
				for (var i = 0; i < length; i++) {
					var con = ctx.contentContainers[i];
					var x = con.offsetLeft;
					con.style.left = x - ctx.steps + "px";
					if (!ctx.calculateBugg) {
						if (con.offsetLeft + (con.offsetWidth / 2) <= ctx.left) {
							if (i == length -1) {
								var tmp = ctx.contentContainers[i-1];
								var x = tmp.offsetLeft + tmp.offsetWidth;
								con.style.left = x + "px";				
								ctx.calculateBugg = true;
							}
						}
					}
					if (con.offsetLeft + con.offsetWidth <= ctx.left) {						
						var lastOut;
						if (ctx.lastOut != null) {// find the last elm that was out of bounds or just take the last one from our list
							lastOut = ctx.lastOut;
						} else {
							lastOut = ctx.contentContainers[length -1];
						}
						x = lastOut.offsetLeft + lastOut.offsetWidth;// calculate the x-pos
						con.style.left = x - ctx.steps + "px";// move it beyond the last one
						ctx.lastOut = con;// store this item for next out of bounds.					
					}
				}
				ctx.tick.apply(ctx, [""]);
			}, ctx.sleep
		);
	}
}

Ticker.prototype.load = function(items) {
	if (!this.containerIsLoaded) {
		var ctx = this;
		this.timer = window.setTimeout(function() {ctx.load.apply(ctx, [items]);},1000);
	} else {
		if (this.timer != null) {
			window.clearTimeout(this.timer);		
		}		
		this.contentContainers = this.ref.getElementsByTagName("div");
		var clength = this.contentContainers.length;
		var length = items.length;
		var childs = new Array();
		for (var i = 0; i < clength; i++) {
			childs[i] = new Array();			
			for (var j = 0; j < length; j++) {				
				childs[i][j] = getTable(this, items[j]);
			}
		}
		for (var i = 0; i < clength; i++) {
			var con = this.contentContainers[i];
			var table = createElement("table");
			initTable(table)
			var tr = table.insertRow(table.rows.length);
			disableSelectHandler(tr, this);
			for (var j = 0; j < length; j++) {
				var td = getTD(tr);
				td.appendChild(childs[i][j]);
			}
			con.appendChild(table);
			con.style.left = "0px";
			con.style.top = "0px";			
		}
		this.tick();
	}
}

function getTable(ticker, inst) {
	var color = inst.getColor();
	var face = inst.fontFace;
	var size = inst.fontSize;
	var table = createElement("table");
	initTable(table);	
	var tr = table.insertRow(table.rows.length);
	var nobr = createElement("nobr");
	nobr.appendChild(getFont(face, size, inst.fnm + " ", "000000"));
	var chp = inst.chp > 0 ? "+" + inst.chp : inst.chp;
	//var info = inst.nm + " " + chp + " " + inst.cr + " ";
	nobr.appendChild(getFont(face, size, inst.nm + " ", inst.unchBg));
	nobr.appendChild(getFont(face, size, chp + " ", color));
	nobr.appendChild(getFont(face, size, inst.cr + " ", inst.unchBg));
	nobr.appendChild(getImage(inst.getImage()));
	nobr.appendChild(getFont(face, size, "  ", color));
	var td = getTD(tr);
	disableSelectHandler(td, ticker);
	addMouseHandler(td, ticker);
	td.appendChild(nobr);	
	td = getTD(tr);
	disableSelectHandler(td, ticker);
	var sep = "";// this was the only way i found working..
	for (var i = 0; i < ticker.separator; i++) {
		sep += "&nbsp;";
	}
	td.innerHTML = sep;
	return table;
}

function initTable(table) {
	table.cellpadding = "0";
	table.cellspacing = "0";
	table.border = "0";
	table.margin = "0";
}

function getTD(tr) {
	var td = tr.insertCell(tr.cells.length);
	td.valign = "top";	
	return td;
}

function addMouseHandler(elm, ticker) {
	elm.ticker = ticker;
	elm.onmouseover = function() {
		this.ticker.block = true;
		if (this.ticker.timer != null) {
			window.clearTimeout(this.ticker.timer);
			this.ticker.timer = null;
		}
	}
	elm.onmouseout = function() {
		this.ticker.block = false;
		this.ticker.tick();
	}
	elm.style.cursor = "pointer";
}

function disableSelectHandler(elm) {
	if (typeof elm.onselectstart != "undefined") {
		elm.onselectstart = function() {return false};
	} else if (typeof elm.style.MozUserSelect!= "undefined") {
		elm.style.MozUserSelect = "none";
	} else {
		elm.onmousedown = function() {return false};
	}
	elm.style.cursor = "default";	
}

function getImage(src) {
	var img = createElement("img");
	img.src = src;
	return img;
}

function getFont(face, size, tx, color) {
	var font = createElement("font");
	font.style.font = size + "px " + face;
	font.color = "#" + color;
	font.appendChild(document.createTextNode(tx));
	return font;
}

function createElement(tag) {
	return document.createElement(tag);
}

function clip(layer, t, r, b, l) {
	layer.style.clip = "rect("+t+" "+r+" "+b+" "+l+")";
	layer.style.width = r + "px";
	layer.style.height = b + "px";
}

function isDefault(param, value) {
	if (param == null || param == "Undefined") {
		return value;
	}
	return param;
}

function isLoaded() {
	if (typeof arguments[0] != "undefined") {
		arguments[0].containerIsLoaded = true;
	} else {
		window.setTimeout("isLoaded(" + arguments[0] + ")", 1000);
	}	
}
//-----------------------------------------------------------
// TickerComponent End
//-----------------------------------------------------------


/*
 * Generic table export html content to node
 */ 
function exportExcel( tableId )	{
	var tableHTML = document.getElementById( tableId);
	var content = "<table>" + tableHTML.innerHTML + "</table>";
	exportHtml(content);
}
/*
 * Generic export html content to node include the belowe to use the export form
 * <form id="exportform" name="exportform" method="post" action="/utils/exportexcel/" target="_blank" accept-charset="iso-8859-1">
 * <input type="hidden" id="exportvalue" name="exportvalue"></input>
 * </form>
 */ 
function exportHtml(content)	{
	document.getElementById("exportvalue").value = content;
	document.exportform.submit();
}
