var xMouse;
var yMouse;

String.prototype.leftTrim = function ()
{
	return (this.replace(/^\s+/,""));
};

String.prototype.rightTrim = function ()
{
	return (this.replace(/\s+$/,""));
};

String.prototype.trim = function ()
{
	return (this.replace(/\s+$/,"").replace(/^\s+/,""));
};


String.prototype.superTrim = function ()
{
	return(this.replace(/\s+/g," ").replace(/\s+$/,"").replace(/^\s+/,""));
};


String.prototype.removeWhiteSpaces = function ()
{
	return (this.replace(/\s+/g,""));
};

String.prototype.get = function(p){
    return (match = this.match(new RegExp("[?|&]?" + p + "=([^&]*)"))) ? match[1] : false;
}

/* debug : fallback */
if (!console) {
	var console = {
		'log' : function (s) {
			return null;
		}
	}
}

/* the following is meant to be used in iFrames, thus the keyword 'parent' */
function conditionalResize(obj) {
	var h = getDocHeight(obj);
	if (obj.parent.$('#cboxContent iframe').height() < h) {
		obj.parent.$.colorbox.resize({'innerHeight' : h+'px'});
	}
}

function getDocHeight(obj) {
	var D = (typeof(obj)==='object') ? obj.document : window.document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}


/* -------------------------------------- */

function number_format(number, decimals, dec_point, thousands_sep)
{
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }

  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ?
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();

  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ?
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }

  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ?
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }

  return sign + integer + fractional + exponent;
}

	function showRate(curr)
	{
		if (!rate)
		{
			return null;
		}
		if(!curr)
		{
			curr='EUR';
		}

		var val = document.getElementById('calc_amount').value;
		if (val == "")
		{
			return false;
		}

		val = val.replace(",",".");
		val = parseFloat(val);

		if (val >= 0.01)
		{
			var dollars = number_format(Math.round(val*rate[curr]['value']*100)/100,2,",");
			var euros   = number_format(Math.round(val/rate[curr]['value']*100)/100,2,",");
			var nval = number_format (val, 2, ",");



			document.getElementById('calc_fromeuro').innerHTML = nval + " " + rate[curr]['sign'];
			document.getElementById('calc_todollar').innerHTML = dollars + " $"
			document.getElementById('calc_fromdollar').innerHTML = nval + " $";
			document.getElementById('calc_toeuro').innerHTML = euros + " " + rate[curr]['sign'];

			/* FOUC thing */
			document.getElementById('currency-converter-equals-a2b').removeAttribute('style');
			document.getElementById('currency-converter-equals-b2a').removeAttribute('style');
		}
	}


	function getElementsByClassName(oElm, strTagName, oClassNames)
	{
		var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
		var arrReturnElements = new Array();
		var arrRegExpClassNames = new Array();

		if(typeof oClassNames == "object")
		{
			for(var i=0; i<oClassNames.length; i++)
			{
				arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
			}
		}
		else
		{
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
		}
		var oElement;
		var bMatchesAll;

		for(var j=0; j<arrElements.length; j++)
		{
			oElement = arrElements[j];
			bMatchesAll = true;

			for(var k=0; k<arrRegExpClassNames.length; k++)
			{
	            if(!arrRegExpClassNames[k].test(oElement.className))
	            {
	                bMatchesAll = false;
	                break;
	            }
			}

			if(bMatchesAll)
			{
				arrReturnElements.push(oElement);
			}
		}

		return (arrReturnElements)
	}

	/* getMouseCoords - used at glossary.js and glossaryHint.js */
	function getMouseCoords(e)
	{
		var posX = 0, posY = 0;

		e = e || window.event;

		if( typeof( e.clientX ) == 'number' )
		{
			posX = e.clientX;
			posY = e.clientY;

			if (document.body && !(window.opera || window.debug || navigator.vendor == 'KDE'))
			{
				if (typeof( document.body.scrollTop) == 'number')
				{
					posX += document.body.scrollLeft;
					posY += document.body.scrollTop;
				}
			}
			if (document.documentElement && !( window.opera || window.debug || navigator.vendor == 'KDE') )
			{
				if (typeof(document.documentElement.scrollTop) == 'number')
				{
					posX += document.documentElement.scrollLeft;
					posY += document.documentElement.scrollTop;
				}
			}
		}

		xMouse = posX;
		yMouse = posY;
	}

	function createCookie(name,value,miliseconds)
	{
		if (miliseconds)
		{
			var date = new Date();
			date.setTime(date.getTime()+miliseconds);
			var expires = "; expires="+date.toGMTString();
		}
		else
		{
			var expires = "";
		}
		var domainParts = window.location.hostname.split(".");
		var domain = "";

		for (var i=1; i<domainParts.length; i++)
		{
			domain += "." + domainParts[i];
		}

		document.cookie = name + "=" + value + expires + "; path=/;domain=" + domain;

	}

	function readCookie(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');

		for (var i=0; i < ca.length; i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ')
			{
				c = c.substring(1, c.length);
			}

			if (c.indexOf(nameEQ) == 0)
			{
				return c.substring(nameEQ.length,c.length);
			}
		}

		return null;
	}

	function getCookies()
	{
		var pairs = document.cookie.split(";");
		var cookies = {};

		for (var i=0; i<pairs.length; i++)
		{
			var pair = pairs[i].split("=");
			cookies[pair[0].trim()] = unescape(pair[1]);
		}

		return cookies;
	}


	function eraseCookie(name)
	{
		createCookie(name,"",-1);
	}




	function initToolTips(cnxtElm)
	{
		/* some vars we gonna need */
		var leftMargin = 10,
		topMargin  = 20,
		viewport = {
			'width'  : $(window).width(),
			'height' : $(window).height()
		};

		/* if a context is passed, use that, otherwise it is the document */
		var cnxtElm = (typeof(cnxtElm)==='object') ? cnxtElm : $(document);

		/* make sure ther is a div at hand to render ToolTips */
		if($('#ToolTipDiv').length < 1)
		{
			$("body").append("<div id='ToolTipDiv'></div>");
		}

		/* applies to any element that has a class which ends with "-to-tooltip" */
		$("[class*=to-toolTip]", $(cnxtElm)).each(function()
		{

			$(this).mouseenter(function(e)
			{
				var attrname, oHtml;

				// In the class name, it is specified which attribute is getting parsed for the tooltip
				// e.g. title-to-tooltip or alt-to-tooltip would do the trick.
				// additionally, nextNode-to-tooltip would fetch the next node's content (subsequent to the triggering element)
				attrname   = $(this).attr('class').match(/([a-z]+)\-to\-toolTip/i)[1];
                                if (attrname=='nextNode') {
                                    oHtml = $(this).next().text();
                                } else {
                                    oHtml = $(this).attr(attrname);
                                }

				var ttHtml =  bbTags(oHtml);

				// to avoid ie 6 + ie7 from displaying their own ToolTips one should add an empty title tag.
				if( attrname!='title' && $(this).attr('title').length<1 ) {
					$(this).attr('title', '');
				}


				$("#ToolTipDiv").html(ttHtml);

				// Get the dimensions of the Tooltip now filled with content
				var toolTip = {
					'width' : $("#ToolTipDiv").outerWidth() +leftMargin,
					'height' : $("#ToolTipDiv").outerHeight() +topMargin
				};


				// Getting scrolling coords
				var scrolling = {
					'left' : $(document).scrollLeft(),
					'top' :  $(document).scrollTop()
				};

				// binded with mousemove
				$(this).mousemove( function (e)
				{

					e = e || window.event;

					// cursor position relative to viewport
					// no need for MSIE e.clientX as jQuery is caretaking on e.pageX
					var cursor = {
						'left' : e.pageX-scrolling.left,
						'top' :  e.pageY-scrolling.top
					};

					// Calulating horizontal position of the tooltip - if it exceeds viewport, turn alignment around
					var tipX = (cursor.left + toolTip.width  > viewport.width) ? cursor.left + scrolling.left - toolTip.width + leftMargin : cursor.left + scrolling.left + leftMargin;

					// Calulating vertical position of the tooltip - if it exceeds viewport, turn alignment around
					var tipY = (cursor.top + toolTip.height  > viewport.height) ? cursor.top + scrolling.top - toolTip.height + topMargin : cursor.top + scrolling.top + topMargin;

					// position it
					$("#ToolTipDiv").css({'top': tipY, 'left': tipX});


				});
				// end of mousemove binding

				// this is just done once, when everything is positioned, filled with html and so on
				// thus, in mouseenter scope
				$("#ToolTipDiv").fadeIn('fast');

			}).mouseleave(function()
				{
					$("#ToolTipDiv").fadeOut('fast');
				}
			);
		});
	}


/* basic BB Tags
 * converts [i], [b], [u], [p] and [br /]
 * to appropriate html equivalents
 *
 */
function bbTags (str) {
	var pattern = /\[(\/?)((i|b|u|p)|br\s*\/?)\]/gi;
	return (str.replace(pattern, "<$1$2>"));

}


/* tries to select sth, eg in input fields and stuff */
function selectIn(obj) {
	try {
		obj.select();
	} catch(e) {
		try {
			obj.focus();
			} catch(e) {
			/* no drama :) */
		}
	}
}


if (typeof(init) != 'object') {
    init = {
    }
}


/* init methods for tools */
init.tools = {
    toggling: function () {
        /**
         * the following function assumes the click-event is fired from an element -- with css-class
         * "toggle-next-tr" applied -- somewhere inside a TR, given there is a subsequent TR to toggle visible / hidden.
         * the element which fires the onclick event is toggled between css-classes 'is-on' and 'is-off'
         */
        $('.toggle-next-tr').click(
		function () {
			var elm = $(this).closest('tr');
			$(elm).next().toggleClass('hidden');
			$('.toggle-next-tr',  $(elm)).toggleClass('is-off is-on');
			$(elm).toggleClass('is-off is-on');
		});
	},
	// end of toggling method


    tooltips: function () {
        initToolTips();
    },
    // end of tooltips method


    currencies: function () {
        try {
            showRate($('#currTo').val());
        } catch (e) {};
    },
	// end of currencies


	clientHint: function () {
		var ua = navigator.userAgent.toLowerCase(),
		rwebkit = /(webkit)[ \/]([\w.]+)/,
		rchrome = /(chrome)[ \/]([\w.]+)/,
		ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
		rmsie = /(msie) ([\w.]+)/,
		rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;
		var match = rchrome.exec( ua ) || rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || [];
		var appName = match[1] ? match[1] : '';
		$('body').addClass(appName+' version-'+parseInt($.browser.version));
	},

	defferedThickBox: function() {
		var relevantNodes = $('a.thickbox, area.thickbox, input.thickbox').not('.thickbox-been-bound');
		if (relevantNodes.length>0){
		   var tb = document.createElement('script');
		   tb.type = 'text/javascript';
		   tb.async = true;
		   tb.src = 'http://static.pokerstrategycdn.com/front/js/Jquery/thickbox.min.js';
		   var s = document.getElementsByTagName('script')[0];
		   s.parentNode.insertBefore(tb, s);
		}
	},

    /*
     * NOTE: This code had to be copied in v4.main/current/html/display/templates/includes/ankerRedirection.html,
     * because of problems with the anker in IE and Safari. Please ensure that maded changes here are also be done
     * in the above mentioned file. Thank you.
     */
	processReferrer: function() {
        var setReferrerCookie = function(cookieName, referrer) {
			var exdays = 14;
			var expireDate = new Date();
			expireDate.setDate(expireDate.getDate() + exdays);
			var cookieDomain = document.location.hostname.replace(/[^\.]+/, '');
            var value = escape(referrer) + '; expires=' + expireDate.toUTCString() + '; path=/; domain=' + cookieDomain;
			document.cookie = cookieName + '=' + value;
		}

		var hash = document.location.hash;
		if(hash)
		{
			var hasReferrer = hash.match(/^#(?:referrer=(.*$))|([uk][A-Z0-9]{5})/);
			if(hasReferrer) {
				var referrer;
				var cookieName;

				// variant 1: http://www.pokerstrategy.com/#referrer=xxx
				if(hasReferrer[1] != undefined) {
					referrer = hasReferrer[1];
					cookieName = 'referrer';

				// variant 2: http://www.pokerstrategy.com/#uxxx
				} else if(hasReferrer[2] != undefined) {
					referrer = hasReferrer[2];
					cookieName = 'source';
				}

				if(referrer) {
                    setReferrerCookie(cookieName, referrer);
					var href = document.location.href.replace(/#.*/g, '');
					document.location.href = href;
				}
			}
		}
	}
};

/* init methods for styles */
init.styles = {
	/* overwrite style settings one for all  */
	colorbox : function () {
		if (typeof  $.colorbox ==='function') {
			/* just mimic community style here */
			$.extend($.colorbox.settings, {
				'opacity': .72,
				'onOpen' : function () {
					if ($.colorbox.settings.slideshow==false) {
						/* custom class to silently dismiss the bottom area which is a background for controls (e.g. in Slideshows) */
						$('#cboxBottomLeft, #cboxBottomCenter, #cboxBottomRight').addClass('noCtrls');
					} else {
						/* this is a slideshow, so controls are needed */
						$('#cboxBottomLeft, #cboxBottomCenter, #cboxBottomRight').removeClass('noCtrls');
					}
				}
			});
		}
	}
}

/* common configurations *************************************************************** */
if (typeof(conf) != 'object') {
	var conf = {}
}

/* 	configurations for modal Boxes - powered by jQuery Plugin $.colorbox
	those are to be viewed as general configurations, which can be
	overwritten / extended for any occassion using jQuery:
		var cBoxConfig = $.extend(conf.modalLoginPanel, { 'href' : '/custom/path...', [...] });
	to call the modal box by the following:
		$.colorbox(cBoxConfig);
*/
conf.modalLoginPanel = {
	'slideshowAuto' : false,
	'fastIframe':     false,
	'iframe':         false,
	'initialWidth':  '310px',
	'innerWidth':    '310px',
	'initialHeight': '108px',
	'innerHeight':   '108px',
	'scrolling' :     false,
	'href' : '/page/thickbox/loginThickbox.php'
}

conf.modalBigBox = {
	'slideshowAuto' : false,
	'fastIframe':     false,
	'iframe':         true,
	'initialWidth':  '490px',
	'innerWidth':    '490px',
	'initialHeight': '280px',
	'innerHeight':   '280px',
	/*
	assuming there is taken care for extensive heights inside the iframe itself
	simply using <body onload="conditionalResize(this);">
	we set scrolling to false:
	*/
	'scrolling' :     false
}



/* common initializations ************************************************************** */
$(document).ready(
     function ()
     {
		init.tools.tooltips();
		init.tools.currencies();
		init.tools.toggling();
		init.tools.defferedThickBox();
		init.tools.processReferrer();
		init.tools.clientHint();
		init.styles.colorbox();
     }

);



