function swap(img, swapper, force) {
	if (!img) return;
	if (!img.src) return;
	if (img.className && img.className.indexOf("selected-noswap")>=0) return;
	if (!swapper) swapper = '_f2';
	var dot = lastIndexOf(img.src, '.');
	var mks = lastIndexOf(img.src, swapper);
	if (mks + swapper.length != dot) {
		if (force=='off') return;
		// original off, swap = make it on
		var newsrc = img.src.substring(0, dot) + swapper + img.src.substring(dot)
		//prompt (mks+' - '+dot, newsrc);
		img.src = newsrc;
	}
	else {
		if (force=='on') return;
		// original on, swap = make if off
		var newsrc = img.src.substring(0, mks) + img.src.substring(dot);
		//prompt (mks+' - '+dot, newsrc);
		img.src = newsrc;
	}
}

function lastIndexOf(str, target) {
	if (!str || !target) return -1;
	for (var i=str.length - target.length; i >=0; --i) {
		if (str.substr(i,target.length)==target) return i;
	}
	return -1;
}

function popup(href,param) {
	if (!param) param = {};
	if (!param.width) param.width = 850;	//664;
	if (!param.height) param.height = 660;	//900;	//660;
	if (!param.left) param.left = (screen.width-param.width)/2;
	if (!param.top) param.top = (screen.height-param.height)/2;
	if (!param.name) param.name = 'popup';
	if (!param.resizable) param.resizable = 0;
	if (!param.scrollbars) param.scrollbars = 0;
	if (!href) href = '';
	else if (!href.href) href = '';
	else href = href.href;
	var paramstr = '';
	for (var k in param) {
		if (param[k]) {
			paramstr += k + '=' + param[k] + ',';
		}
	}
	var popup = window.open(href,param.name,paramstr);
	popup.focus();
	return false;
}

function guestpasspopup(href,param) {
	if (!param) param = {};
	if (!param.width) param.width = 640;	//664;
	if (!param.height) param.height = 750;	//900;	//660;
	if (!param.left) param.left = (screen.width-param.width)/2;
	if (!param.top) param.top = (screen.height-param.height)/2;
	if (!param.name) param.name = 'popup';
	if (!param.resizable) param.resizable = 0;
	if (!param.scrollbars) param.scrollbars = 1;
	if (!href) href = '';
	else if (!href.href) href = '';
	else href = href.href;
	var paramstr = '';
	for (var k in param) {
		if (param[k]) {
			paramstr += k + '=' + param[k] + ',';
		}
	}
	var popup = window.open(href,param.name,paramstr);
	popup.focus();
	return false;
}

function popupMbr(href) {
	return popup(href);	//, {width:850, height:900, name:'popupmbr'});
	/*
	var width = 850;
	var height = 900;
	var left = (screen.width-width)/2;
	var top = 0;
	var popup = window.open(href.href,'popupmbr','resizable=no,width='+width+',height='+height+',left='+left+',top='+top);
	popup.focus();
	return false;
	*/
}

function popupMap(href) {
	var width = 664;
	var height = 520;
	var left = (screen.width-width)/2;
	var top = (screen.height-height)/2
	var popup = window.open(href.href,'popup','resizable=no,width='+width+',height='+height+',left='+left+',top='+top);
	popup.focus();
	setTimeout(function() {
		popup.print();
	}, 100)
	//popup.print();
	return false;
}

/**
 * To create a fancy <select> pull-down menu,
 * wrap your standard <select> with div#id,
 * pass the #id to this function
 *  - 1. <select> will then be un-displayed
 *  - 2. onchange functional behaviour will be fired
 *  - 3. you can still get value from your <select>, as if selected automatically
 *  - 4. new fancy-menu = #ocf-[id], inside your div#id, placed after your <select>
 */
function ocfSelect(id, i) {
	var e = document.getElementById(id);
	var sary = e.getElementsByTagName('select');
	var s = sary[0];
	// - 3.
	s.selectedIndex = i;
	// - 2.
	if (s.onchange) s.onchange();
}
function ocfInitSelect(id) {
	var e = document.getElementById(id);
	var sary = e.getElementsByTagName('select');
	var s = sary[0];
	var o = s.options[s.selectedIndex];
	var ihtml = '';
	ihtml += '<li class="first active"><a href="'+o.value+'">'
		+o.text
		+'</a></li>\n';
	for (var i=0; i < s.options.length; ++i) {
		o = s.options[i];
		var clsName = 'inner';
		if (i == s.selectedIndex) clsName += ' active';
		if (i == s.options.length-1) clsName += ' last';
		// - 2.
		ihtml += '<li class="'+clsName+'"><a href="javascript:ocfSelect(\''+id+'\','+i+')">'
			+o.text
			+'</a></li>\n';
	}
	// - 1.
	s.style.display = 'none';
	// - 4.
	ihtml = '<ul id="ocf-'+id+'">'+ihtml+'</ul>';
	e.innerHTML += ihtml;

	// - 4.
	var jqid = '#ocf-' + id;
	var jqobj = $(jqid);
	jqobj.css({
		position: 'absolute'
		//left: ($('#heading').offset().left + $('#heading-menu').width()) + 'px'
	});
	jqobj.mouseover(function() {
		$(jqid+' li.inner').css({
			display: 'block'
		});
		$(jqid+' li.first').css({
			display: 'none'
		});
	});
	jqobj.mouseout(function() {
		$(jqid+' li.inner').css({
			display: 'none'
		});
		$(jqid+' li.first').css({
			display: 'block'
		});
	});
}

var activeTrainer = 0;
function showTrainer(href) {
	var trainerId, trainerIdBare, trainer, defaultTrainer = "ptrain-month-body-img";

	// find out which trainer to display
	if (href || location.hash) {
		if (href) {
			trainerId = href.substring(href.indexOf("#"));
		}
		else {
			trainerId = location.hash;
		}
		trainerIdBare = trainerId.substring(1);
		trainerId = "trainer-" + trainerIdBare;
	}
	else {
		trainerIdBare = trainerId = defaultTrainer;
	}
	trainer = document.getElementById(trainerId);

	// goal: do the display job, in css
	if (!trainer) return;
	if (trainer == activeTrainer) return;
	if (!activeTrainer) activeTrainer = document.getElementById("ptrain-month-body-img");
	activeTrainer.style.display = "none";
	trainer.style.display = "block";

	// also: update the selector listing, in terms of css class
	if (activeTrainer.id.indexOf("trainer-")==0) {
		document.getElementById("list-"+activeTrainer.id).className = "inactive";
	}
	if (trainer.id.indexOf("trainer-")==0) {
		document.getElementById("list-"+trainer.id).className = "active";
	}

	// also: update the language switch
	if (trainerIdBare != defaultTrainer) {
		var hlang = $('.heading-menu-site-lang a');
		for (var i=0; hlang && i < hlang.length; ++i) {
			var h = hlang.get(i).href;
			if (h && h.indexOf('#') > 0) {
				hlang.get(i).href = h.substr(0,h.indexOf('#')+1) + trainerIdBare;
			}
			else {
				hlang.get(i).href += '#' + trainerIdBare;
			}
		}
	}

	// done: put trainer to memory, so that next time we [might] save some processing
	activeTrainer = trainer;
}

function findbaseurl()
{
	var urlpattern = new RegExp("(https?://[^/]+)");
	var matches = urlpattern.exec(self.location.href);
	if (matches != null)
	{
		return matches[1] + "/";
	}
}

function findnonsslbaseurl()
{
	var urlpattern = new RegExp("https?://([^/]+)");
	var matches = urlpattern.exec(self.location.href);
	if (matches != null)
	{
		return 'http://' + matches[1] + "/";
	}
}

function getHostname()
{
    var urlpattern = new RegExp("https?://([^/]+)");
    var matches = urlpattern.exec(self.location.href);
	if (matches != null)
		return matches[1];
	else
		return "";
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

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 eraseCookie(name)
{
	createCookie(name,"",-1);
}


//Set Variable to Flash
function doPassVar(args) {
	document.locationswf.SetVariable("flashpath", args);
}

//Set Country+Lang to Flash
function doPassLocation(country,lang) {
	document.homeswf.SetVariable("country", country);
	document.homeswf.SetVariable("lang", lang);
}

function getParameter(pname,frstr)
{
	var pattern = new RegExp("[\\?\\&]" + pname + "=(\\w*)");
	if (!frstr)
		frstr = self.location.href;
	var matches = pattern.exec(frstr);
	if (matches != null)
		return matches[1];
	else
		return null;
}

// Submit a form, with 'act' set to specific value
// Optionally can set any form element values.
// Input
// formname, actvalue
// Optional: form_var1, form_value1, form_var2 ....
function formSubmit()
{
	var tform = document.forms[arguments[0]];
	var actvalue = arguments[1];
	tform.act.value = actvalue;
	if (arguments.length > 3)
	{
		var i;
		for (i = 2; i < arguments.length-1; i=i+2)
		{
			if (arguments[i] == 'target')
				tform.target = arguments[i+1];
			else if (arguments[i] == 'action')
				tform.action = arguments[i+1];
			else if (typeof tform.elements[arguments[i]] != "undefined")				
				tform.elements[arguments[i]].value = arguments[i+1];
		}
	}
	tform.submit();
}

String.prototype.normalize = function() {
    return this.replace(/&#([0-9]{1,7});/,
    function (str, p1, p2, offset, s) {
    return String.fromCharCode(p1);
    }
    );
}

/**
 @id : select element id
 @values : [[key1,value1],[key2,value2],....]
 @defvalues : either single value or array(for multiple select)
 @normalizetext : Optonal. true/false. the value part will be normalized
*/
function buildSelectOption(id,values,defvalues,normalizetext)
{
	var sel = document.getElementById(id);
	if (!sel || !sel.options) return;
	var opts = sel.options;
	opts.length = 0;	
	var selectedIndex = 0;
	
	for (var i = 0; i < values.length; i++)
	{
		var selected = false;
		if ((typeof defvalues == "string" || typeof defvalues == "number") && (defvalues == values[i][0]))
			selected = true;
		else if (typeof defvalues == "object" && defvalues instanceof Array)
		{
			for (var j = 0; j < defvalues.length; j++)
				if (defvalues[j] == values[i][0])
				{
					selected = true;
					break;
				}
				
		}
		
		if (normalizetext)
			values[i][1] = values[i][1].normalize();
		opts[i] = new Option(values[i][1],values[i][0]);
		if (selected)
		{
			opts[i].selected = true;
			opts[i].defaultSelected = true;
		}
	}
}

/**
  * Show/Hide element
  * @id - element id
  * @display - value assigned to style.display property (block/inline/none)
  */
function setDisplay(id, display)
{
	var ele = document.getElementById(id);
	if (ele && ele.style)
	{		
		ele.style.display = display;	
	}
}


function openFooter(ahref) {
	if (opener) {
		opener.location.href = ahref.href;
		window.close();
		return false;
	}
}

