var promotor_id, promotor_info, promotor_tool, domain_id, ip_address, object, extra1, extra2, extra3, transferdata, display,
website_id = 0, location_id = 0, program_id = 0, step = 0, screenLoaded = 0, session_id = 0, secret = 0, timecheck = 0, path,
initialstatusDelay = 10000, statusDelay = 3000, currLanguage = 'nl', pincode, selectedCountry = '', selectedProfile = 0,
selectedProduct = 0, tasProductAmount = 0, directPaymentMethod = 0, tasBankId = 0, tasCardId = 0, tasBankName = '', pack = '',
tasCardName = '', tasMsAccessType = 'min',  tasMsAccessTime = 0, tasMsAccessSessions = 0, tasMsAccessDoCountdown = 0,
tasMsDoCheck = 0, tasMsAccessSessionExpire = 0, doReload = 0, allCountriesId = 'ALL', initCountryId = 'NL', thisProfiles = new Array();

var myCountries = new Object, myProfiles = new Object, profileData = new Object, paymentData = new Object;
var thisUrl = '', sessionApi = 'http://www.pay.nl/ppi/session.php', transactionApi = 'http://www.pay.nl/ppi/transaction.php',
returnUrl = '', tasBaseUrl = 'http://www.paysites.nl/sites/', tasPayUrl = 'http://www.pay.nl/betalen/pay_2.4.5.php';

// $(document).ready(function()
window.onload=function()
{
	website_id 		= new Number( $("#tasPaymentInfo input[name='website_id']").attr("value") );
	location_id 	= new Number( $("#tasPaymentInfo input[name='location_id']").attr("value") );
	program_id 		= new Number( $("#tasPaymentInfo input[name='program_id']").attr("value") );

	var tmpProfileId = $("#tasPaymentInfo input[name='profile_id']").attr("value");
	var tmpProductId = $("#tasPaymentInfo input[name='product_id']").attr("value");

	if (tmpProfileId != '' && tmpProfileId != undefined)  selectedProfile = new Number(tmpProfileId);
	if (tmpProductId != '' && tmpProductId != undefined)  selectedProduct = new Number(tmpProductId);

	promotor_id 		= $("#tasPaymentInfo input[name='promotor_id']").attr("value");
	promotor_info 	= $("#tasPaymentInfo input[name='promotor_info']").attr("value");
	promotor_tool 	= $("#tasPaymentInfo input[name='promotor_tool']").attr("value");
	selectedCountry = $("#tasPaymentInfo input[name='country_id']").attr("value");
	currLanguage 		= $("#tasPaymentInfo input[name='language_id']").attr("value");
	domain_id 			= $("#tasPaymentInfo input[name='domain_id']").attr("value");
	ip_address 			= $("#tasPaymentInfo input[name='ip_address']").attr("value");
	object 					= $("#tasPaymentInfo input[name='object']").attr("value");
	session_id			= new Number( $("#tasPaymentInfo input[name='session_id']").attr("value") );
	secret					= new Number( $("#tasPaymentInfo input[name='secret']").attr("value") );
	pack						= $("#tasPaymentInfo input[name='pack']").attr("value") ;
	extra1					= $("#tasPaymentInfo input[name='extra1']").attr("value") ;
	extra2					= $("#tasPaymentInfo input[name='extra2']").attr("value") ;
	extra3					= $("#tasPaymentInfo input[name='extra3']").attr("value") ;
	transferdata 		= $("#tasPaymentInfo input[name='transferdata']").attr("value") ;
	returnUrl 			= $("#tasPaymentInfo input[name='returnUrl']").attr("value");
	thisUrl 				= $("#tasPaymentInfo input[name='thisUrl']").attr("value");
	display 				= $("#tasPaymentInfo input[name='display']").attr("value");
	path		 				= $("#tasPaymentInfo input[name='path']").attr("value");

	// check vars
	if(currLanguage == '' || !tasText[currLanguage])  currLanguage = 'nl';
	if(selectedCountry == '' || !tasTextCountries[currLanguage][selectedCountry])  selectedCountry = initCountryId;

	// show corresponding flag
	$("#tasLangSelected").attr("src", tasBaseUrl +"images/flag_"+ currLanguage +"_select.gif");

	// add event for possibility to restart payment
	$(".tas_menu_restart").click(function(){
		restartPayment();
	});

	// override initial data if necessary
	if ($("#tasPaymentInfo input[name='direct_status_check']").attr("value") == "1") {

		// payment succeeded, show loading text
		$("body").append("<div class=\"tasPayLoading\"><img src=\""+ tasBaseUrl +"images/loading.gif\" align=\"absmiddle\" style=\"margin-right: 12px;\" />"+ tasTextCommon[currLanguage]["payment_return_status"] +"</div>");

		// set parameters
		timecheck = 1;
		selectedProfile	= tmpProfileId;
		selectedProduct	= tmpProductId;
		directPaymentMethod = 4;
		getPaymentStatus();
	}
	else if((website_id > 0 && program_id > 0) || session_id > 0) {
		// only load screen if website and program is set
		init();
		initScreen();
	}
}


function init() {

	var extraUrlArgs = '';
	if(session_id > 0) {
		extraUrlArgs = '&payment_session_id='+ session_id;
	}

	$.ajax({
		dataType:'jsonp',jsonp: 'jsonp_callback', cache: false,
		data:'mode=get_session&resulttype=jsonp&website_id='+ website_id +'&website_location_id='+ location_id +'&program_id='+ program_id +'&promotor_id='+ promotor_id +'&promotor_tool='+ promotor_tool +'&promotor_info='+ promotor_info +'&domain_id='+ domain_id +'&ip_address='+ ip_address +'&object='+ object +'&extra1='+ extra1 +'&extra2='+ extra2 +'&extra3='+ extra3 +'&transferdata='+ transferdata + extraUrlArgs +'&r='+ Math.random(),
		url: sessionApi,
		success: function (data) {

			// store data
			session_id 		= data.payment_session_id;
			pincode 			= data.pincode;
			secret				= data.secret;
			statusDelay 	= data.refresh_interval ? data.refresh_interval*1000 : 3000;
			timecheck 		= data.timecheck;

			// override initial data if necessary
			if ($("#tasPaymentInfo input[name='direct_status_check']").attr("value") == "1") {

				var tmpSessId = $("#tasPaymentInfo input[name='session_id']").attr("value");
				var tmpSecret = $("#tasPaymentInfo input[name='secret']").attr("value");
				session_id = tmpSessId > 0 ? tmpSessId : data.payment_session_id;
				secret = tmpSecret > 0 ? tmpSecret : data.secret;
				timecheck = 1;
			}
			else if ($("#tasPaymentInfo input[name='direct_status_check']").attr("value") == "2") {

				// payment cancelled / not fully paid
				var tmpSessId = new Number( $("#tasPaymentInfo input[name='session_id']").attr("value") );
				var tmpSecret = $("#tasPaymentInfo input[name='secret']").attr("value");
				session_id = tmpSessId > 0 ? tmpSessId : data.payment_session_id;
				secret = tmpSecret > 0 ? tmpSecret : data.secret;
				timecheck = 1;
				initialstatusDelay = 500;
			}

			// check if a product is provided
			if (selectedProduct > 0)  setProfileProduct();


			// build an usable object
			var _profileDefault = 0;
			var _initCountryIdExists = 0;
			var _initCountryIdFirst = '';
			if (data.paymentprofiles) {
				$.each(data.paymentprofiles, function( profile_id, profile) {
					if(_initCountryIdFirst == '') _initCountryIdFirst = profile[0].countrycode;
					if(_initCountryIdExists == 0 && profile[0].countrycode == initCountryId) _initCountryIdExists = 1;
					if (profile[0].countrycode) {

						if (!myProfiles[profile[0].countrycode])  myProfiles[profile[0].countrycode] = new Object;

						var objProduct  = new Object;
						$.each(profile, function( i, product) {
							if(_profileDefault == 0 && product.use_as_default == 1)  _profileDefault = profile_id;
							myCountries[product.countrycode] = tasTextCountries[currLanguage][product.countrycode];
							objProduct[product.id] = new Product(product.id, product.amount, product.amount_euro,  product.amount_euro_left, product.time, product.use_as_default);
						});

						myProfiles[profile[0].countrycode][profile_id] = new profileCst(profile_id, profile[0].payment_method_id, profile[0].calltype, profile[0].pincode_type, profile[0].number, profile[0].tariff, profile[0].currency_id, profile[0].amount_euro, objProduct);
						profileData[profile_id] = new profileDataCst(profile[0].payment_method_id, profile[0].calltype, profile[0].pincode_type, profile[0].number, profile[0].tariff);
					}
				});
				
				if(_initCountryIdExists == 0) 
				{
					initCountryId = _initCountryIdFirst;
					selectedCountry = _initCountryIdFirst;
				}

				// set initial profile
				if(selectedProfile == 0) selectedProfile = _profileDefault;

				// build and show the countries
				initSteps();
			}

			// start the timeout for checking the payment status
			setTimeout(function() {
				getPaymentStatus();
			}, initialstatusDelay);

		}
	});
}


function initScreen() {

	// hide loading div
	$("div.tasAfterPayLoading").hide();

	// build the language options
	if (tasTextLanguages) {

		langCount = 0;
		$("#tasLanguageDrop li").remove();

		$.each(tasTextLanguages, function(i,cData) {
			langCount++;
			$("#tasLanguageDrop").append('<li class="tasLangSel" title="'+ cData.code +'"><img src="'+ tasBaseUrl +'images/flag_'+ cData.code +'.gif" /> '+ cData.name +' </li>');
		});

		// check amount of available languages
		if(langCount == 1)  $(".tas_menu_lang").hide();
		else if (langCount > 1)  $("#tasLangSelected").attr("src", tasBaseUrl +"images/flag_"+ currLanguage +"_select.gif");
	}

	// activate the menu
	$(function() {

		$('ul.langMenu').jdMenu();

		// Add menu hiding on document click
		$(document).bind('click', function(){
			$('ul.langMenu ul:visible').jdMenuHide();
		});

		// change language
		$(".tasLangSel").click(function() {
			// check whether the selected language is available
			var newLang = $(this).attr("title");

			if (tasTextCommon[newLang]){

				// set the language
				currLanguage = newLang;

				// show corresponding flag
				$("#tasLangSelected").attr("src", tasBaseUrl +"images/flag_"+ currLanguage +"_select.gif");
				$("#tasCopyright").text( tasTextCommon[currLanguage]["copyright"] );

				// reload the screen
				initSteps();
			}
		});
	});

	// show the paymentscreen
	$("#tasCopyright").text( tasTextCommon[currLanguage]["copyright"] );
	$("#tas2Container, #tasCopyFooter").show();
}


function initSteps() {
	$('.tasStep').remove();
	step=0;
	buildCountrySelect();
	buildPaymentProfiles();
	buildPaymentMethodProducts();
	buildPaymentInstructions();
}


function buildCountrySelect() {

	// check amount of countries
	var i= 0;
	$.each(myCountries, function(countryCode, countryName) {
		i++;
		if (selectedCountry == '')  selectedCountry = countryCode;
	});

	if (i < 2)  return;


	step++;
	$("#tas2Content").append('<div class="tasStep"><input type="hidden" name="step" value="'+ step +'" /><h1>'+ step +'. '+ tasTextCommon[currLanguage]["countryHeader"] +'</h1><p>'+ tasTextCommon[currLanguage]["countryDesc1"] +'</p><select id="tasCountrySelect" class="tasSelect"></select></div>')

	// define the countries
	$.each(myCountries, function(countryCode, countryName){
		$('#tasCountrySelect').append('<option value="'+ countryCode +'"> '+ countryName +'</option>');
	});

	// preselect default country
	$('#tasCountrySelect').val( selectedCountry );

	// add country change event
	$('#tasCountrySelect').change(function() {

		if (selectedCountry == this.value)  return true;

		selectedCountry = this.value;
		selectedProfile	= selectedProduct	= 0;
		initSteps();
	});

	return true;
}

function array_merge(arr1, arr2) {
	var newArr = new Object;
	$.each(arr1, function(key, values) { if(key > 0) { newArr[key] = values; } });
	$.each(arr2, function(key, values) { if(key > 0) { newArr[key] = values; } });
	return newArr;
}

function buildPaymentProfiles() {

	if (selectedCountry == '' || selectedCountry == undefined || selectedCountry == 0)  return;
	if (!myProfiles[selectedCountry] && !myProfiles[allCountriesId])  return;


	if(selectedCountry != allCountriesId && myProfiles[allCountriesId] && myProfiles[selectedCountry]) {
		thisProfiles = array_merge(myProfiles[selectedCountry], myProfiles[allCountriesId]) ;
	}
	else if(myProfiles[selectedCountry]) {
		thisProfiles = myProfiles[selectedCountry];
	}
	else if(myProfiles[allCountriesId]) {
		thisProfiles = myProfiles[allCountriesId];
	}

	// check amount of countries
	var i= 0;
	$.each(thisProfiles, function(foo, profileArgs) {

		i++;
		if (selectedProfile == 0)  selectedProfile = profileArgs.id;
	});

	if (i < 2) return;

	step++;
	$("#tas2Content").append('<div class="tasStep"><input type="hidden" name="step" value="'+ step +'" /><h1>'+ step +'. '+ tasTextCommon[currLanguage]["profilesHeader"] +'</h1><p>'+ tasTextCommon[currLanguage]["profilesDesc1"] +'</p><div class="tasMethodsList"></div></div>')

	// define the countries
	var mCount=0;
	var methodDesc, methodIcon = '';
	$.each(thisProfiles, function(profileId, profileArgs) {

		if (profileArgs.paymentMethod == "4") {

			methodDesc = tasTextMethods[currLanguage][4][profileId].desc;
			methodIcon = tasTextMethods[currLanguage][4][profileId].icon;
		}
		else {

			methodDesc = tasTextMethods[currLanguage][profileArgs.paymentMethod].desc;
			methodIcon = tasTextMethods[currLanguage][profileArgs.paymentMethod].icon;
		}

		// add profiles as a vertical list
		$('.tasMethodsList:last').append('<div id="tasMethod_'+ profileArgs.id +'" class="tasPayMethodSelect hand"><img class="tasMethodCheckbox" src="'+ tasBaseUrl +'images/tas2Checkbox.gif" align="absmiddle" /><img class="tasPayMethodIcon" src="'+ tasBaseUrl +'images/'+ methodIcon +'" title="'+ methodDesc +'" align="absmiddle" /> '+ methodDesc +'</div>');
	});

	// preselect default country
	$(".tasMethodsList input[value='" + selectedProfile + "']:radio").attr("checked", "checked");

	$('.tasMethodsList img.tasMethodCheckbox').attr("src", tasBaseUrl +"images/tas2Checkbox.gif");
	$('#tasMethod_'+ selectedProfile +' img.tasMethodCheckbox').attr("src", tasBaseUrl +"images/tas2CheckboxChecked.gif");

	// add profile change event
	$('.tasPayMethodSelect').click(function() {
		selectedProfile = $(this).attr("id").substr(10);
		selectedProduct	= 0;
		initSteps();
	});

	return true;
}


function buildPaymentMethodProducts(){

	if (selectedCountry == '' || selectedCountry == undefined || selectedCountry == 0)  return;
	if (selectedProfile == '' || selectedProfile == undefined || selectedProfile == 0)  return;
	if (!thisProfiles)  return;
	if (!thisProfiles[selectedProfile])  return;

	// check amount of countries
	tasProductAmount = 0;
	var newProductId = 0;
	var defaultProductId = 0;

	$.each(thisProfiles[selectedProfile].products, function(foo, productArgs){
		tasProductAmount++;
		if (productArgs.isDefault == "1")  defaultProductId = productArgs.id;
		if (newProductId == 0)  newProductId = productArgs.id;
	});

	// check if there is a preselected product
	if (selectedProduct == 0) {

		// no preselected product, check if there is a default product
		if (defaultProductId > 0)  newProductId = defaultProductId;

		selectedProduct = newProductId;
		setProfileProduct();
	}

	//	if(tasProductAmount < 2)
	if (thisProfiles[selectedProfile].paymentMethod == "3" || thisProfiles[selectedProfile].paymentMethod == "5")  return;

	// place the second step
	step++;

	// use selected placement type
	$("#tas2Content").append('<div class="tasStep"><input type="hidden" name="step" value="'+ step +'" /><h1>'+ step +'. '+ tasTextCommon[currLanguage]["productsHeader"] +'</h1><p>'+ tasTextCommon[currLanguage]["productsDesc1"] +'</p><div id="tasProductSelectList" class="tasSelectList"></div></div>');

	// define the countries
	$.each(thisProfiles[selectedProfile].products, function(foo, productArgs) {

		var prod_desc = '';

		if (tasTextProducts[currLanguage][productArgs.id]) {

			prod_desc = tasTextProducts[currLanguage][productArgs.id];
			$.each(['amount','time','minutes','seconds'],function(i, toBeReplaced) {
				prod_desc = prod_desc.replace('%'+ toBeReplaced +'%', productArgs[toBeReplaced]);
			});
		}
		else  prod_desc = productArgs.amount; // +' '+ tasTextCommon[currLanguage]["productsPrice"];

		if(productArgs.amount_euro_left < productArgs.amount_euro) {
			prod_desc = prod_desc +' ('+  tasTextCommon[currLanguage]["productsPriceLeft"].replace("%amount%", productArgs.amount_left) +')';
		}
		
		$('#tasProductSelectList').append('<div class="tasProductSelectOption hand" id="tas_prod_'+ productArgs.id +'"><img class="tasProductCheckbox" src="'+ tasBaseUrl +'images/tas2Checkbox.gif" align="absmiddle" /> '+ prod_desc +' </div>');
	});

	// select product
	$('#tasProductSelectList img.tasProductCheckbox').attr("src", tasBaseUrl +"images/tas2Checkbox.gif");
	$('#tas_prod_'+ selectedProduct +' img.tasProductCheckbox').attr("src", tasBaseUrl +"images/tas2CheckboxChecked.gif");

	// add click event
	$('#tasProductSelectList div.tasProductSelectOption').click(function() {
		selectedProduct = $(this).attr("id").substr(9);
		setProfileProduct();
		initSteps();
	});

	return true;
}


function buildPaymentInstructions() {

	if (selectedCountry == '' || selectedCountry == undefined || selectedCountry == 0) return;
	if (selectedProfile == '' || selectedProfile == undefined || selectedProfile == 0) return;
	if (!thisProfiles) return;
	if (!thisProfiles[selectedProfile]) return;

	// place the second step
	step++;
	$("#tas2Content").append('<div class="tasStep"><input type="hidden" name="step" value="'+ step +'" /><h1>'+ step +'. '+ tasTextCommon[currLanguage]["paymentHeader"] +'</h1></div>')

	switch ( thisProfiles[selectedProfile].paymentMethod ) {

		case "1": // sms
		buildSmsContent();
		break;

		case "2":	// pfp
		buildPpmContent();
		break;

		case "3":
		buildPpmContent();
		break;

		case "5": // ppm
		buildPpmContent();
		break;

		case "4": // ideal, cc, wallie
		if( selectedProfile == "10")  buildIdealContent();
		else if( selectedProfile == "11")  buildCreditCardContent();
		else if( selectedProfile == "136")  buildBankTransferContent();
		else  buildCommonPaymentInfoContent();
		break;

		case "6": // out
		break;

		case "7": // tts
		break;
	}
}


function buildPpmContent() {

	var paymentMethod = thisProfiles[selectedProfile].paymentMethod;
	var callType = thisProfiles[selectedProfile].callType;
	var pincodeType = thisProfiles[selectedProfile].pincodeType;
	var phonenumber = thisProfiles[selectedProfile].number;
	var tariff = thisProfiles[selectedProfile].tariff;
	var currency_id = thisProfiles[selectedProfile].currency_id;
	var currText = tasTextProfiles[currLanguage][paymentMethod];
	var cstStr = '';
	
	if(selectedCountry.toUpperCase() == "DE") {
		if(paymentMethod == "5" || paymentMethod == "2") cstStr = "&euro; "+ tariff + " pro Minute a.d. Festnetz,<br />Mobilfunkpreise ggf. abweichend";
		if(paymentMethod == "3") cstStr = "&euro; "+ tariff + " pro Gesprach a.d. Festnetz,<br />Mobilfunk leider nicht moglich";
	}
	else cstStr = tasTextCommon[currLanguage]["costs"][currency_id] +' '+ tariff +' '+ currText.call_type;

	$('.tasStep:last').append('<p>'+ currText.desc +'</p><div id="tasPhoneInfo"><div id="tasPhonenumber">'+ phonenumber +'<div id="tasPhoneCosts">'+ cstStr +'</div></div></div>');

	// show the pinbox
	if(pincodeType == "2") {

		// presspincode
		$('#tasPhoneInfo').append('<div id="tasPinboxCnt"><label>'+ tasTextCommon[currLanguage]["pincode"] +'</label><input class="tasPinbox" type="text" name="tasPincode" value="'+ pincode +'" /></div>');
	}
	else if(pincodeType == "3") {

		// saypincode
		$('#tasPhoneInfo').append('<form class="pin"><div id="tasPinboxCnt"><label>'+ tasTextCommon[currLanguage]["pincode"] +'</label><input class="tasPinbox pinbox_yellow" type="text" name="tasPincode" value="" align="absmiddle" /><img class="submit hand" src="'+ tasBaseUrl +'images/tasButtonGoXl.gif" align="absmiddle" /></div></form>');

		$("form.pin .submit").click(function() {
			checkPincode( $("input[name='tasPincode']", $(this).parent() ).val() );
		});

		$("form.pin").submit(function() {
			checkPincode( $("input[name='tasPincode']", $(this).parent() ).val() );
			return false;
		});
	}
}


function buildSmsContent() {

	var paymentMethod = thisProfiles[selectedProfile].paymentMethod;
	var callType = thisProfiles[selectedProfile].callType;
	var pincodeType = thisProfiles[selectedProfile].pincodeType;
	var phonenumber = thisProfiles[selectedProfile].number;
	var tariff = thisProfiles[selectedProfile].tariff;
	var currency_id = thisProfiles[selectedProfile].currency_id;
	var currText = tasTextProfiles[currLanguage][paymentMethod];

	// show the pinbox
	if (pincodeType == "2") {

		// customer will submit pincode by a textmessage
		var tmp = phonenumber.split(" ");
		$('.tasStep:last').append('<p>'+ currText.desc +'</p><div id="tasPhoneInfo">Stuur <label class="tasSmsInfo">'+ tmp[1] +'</label> <label class="tasSmsInfo">'+ pincode +'</label> naar telefoonnummer <label class="tasSmsInfo">'+ tmp[0] +'</label><div id="tasPhoneCosts">'+ tasTextCommon[currLanguage]["costs"][currency_id] +' '+ tariff +' '+ currText.call_type +'</div></div>');
	}
	else if (pincodeType == "3") {

		// saypincode
		var tmp = phonenumber.split(" ");
		thisPincode = selectedProduct;

		if(callType == "0" && tasProductAmount == 1)  thisPincode = '';

		$('.tasStep:last').append('<p>'+ currText.desc +'</p><div id="tasPhoneInfo"><div class="tasSmsInfoForm">Stuur <label class="tasSmsInfo">'+ tmp[1] +'</label> <label class="tasSmsInfo">'+ thisPincode +'</label><br />naar nummer <label class="tasSmsInfo">'+ tmp[0] +'</label></div><div id="tasPhoneCosts">'+ tasTextCommon[currLanguage]["costs"][currency_id] +' '+ tariff +' '+ currText.call_type +'</div></div>');
		$('#tasPhoneInfo').append('<form class="pin"><div id="tasPinboxCnt"><label>'+ tasTextCommon[currLanguage]["pincode"] +'</label><input class="tasPinbox pinbox_yellow" type="text" name="tasPincode" value="" align="absmiddle" /><img class="submit hand" src="'+ tasBaseUrl +'images/tasButtonGoXl.gif" align="absmiddle" /></div></form>');

		$("form.pin .submit").click(function() {
			checkPincode( $("input[name='tasPincode']", $(this).parent() ).val() );
		});

		$("form.pin").submit(function() {
			checkPincode( $("input[name='tasPincode']", $(this).parent() ).val() );
			return false;
		});
	}
}


function buildIdealContent() {
	var currText = tasTextProfiles[currLanguage][thisProfiles[selectedProfile].paymentMethod][selectedProfile];

	$('.tasStep:last').append('<p>'+ currText.desc +'</p><div class="tasIdealBanks"></div>');
	$.each(tasIdealBank ,function(i, tasBank) {
		$("div.tasIdealBanks").append('<div id="tasIdeal_'+ tasBank.id +'" class="tasIdealBank hand"><img class="tasProductCheckbox" src="'+ tasBaseUrl +'images/tas2Checkbox.gif" /> <img class="tasBankName" src="'+ tasBaseUrl +'images/'+ tasBank.img +'" title="'+ tasBank.name +'" /></div>');
	});

	// add a nice button for opening the iDealscreen
	$("div.tasIdealBanks").append('<button id="tasIdealBankButton">'+ tasTextCommon[currLanguage]["button_start_payment_ideal"] +'</button>')

	// click events for the banks
	$("div.tasIdealBanks div.tasIdealBank").click(function() {
		tasBankId = $(this).attr("id").substr(9);
		tasBankName = $("img.tasBankName", $(this)).attr("title");

		// select product
		$('div.tasIdealBanks div.tasIdealBank img.tasProductCheckbox').attr("src", tasBaseUrl +"images/tas2Checkbox.gif");
		$('#tasIdeal_'+ tasBankId +' img.tasProductCheckbox').attr("src", tasBaseUrl +"images/tas2CheckboxChecked.gif");
		$("#tasIdealBankButton").text(tasTextCommon[currLanguage]["button_start_payment_ideal"] +' : '+ tasBankName)	;
	});

	// click event for the start button
	$("#tasIdealBankButton").click(function() {
		if (tasBankId == 0)  alert(tasTextCommon[currLanguage]["payment_ideal_select_bank"]);
		else  document.location.href = tasPayUrl +'?profile_id=10&product_id='+ selectedProduct +'&session_id='+ session_id +'&bank_id='+ tasBankId +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&pack='+ pack +'&display='+ display +'&path='+ path +'&return_url='+ returnUrl +'&r='+ Math.random();
	});
}


function buildCreditCardContent() {

	var currText = tasTextProfiles[currLanguage][thisProfiles[selectedProfile].paymentMethod][selectedProfile];

	$('.tasStep:last').append('<p>'+ currText.desc +'</p><div class="tasCreditCards"></div>');
//	$.each(tasCreditCard ,function(i, tasCard) {
//		$("div.tasCreditCards").append('<div id="tasCredit_'+ tasCard.id +'" class="tasCreditCard hand"><img class="tasProductCheckbox" src="'+ tasBaseUrl +'images/tas2Checkbox.gif" /> <img class="tasCardName" src="'+ tasBaseUrl +'images/'+ tasCard.img +'" title="'+ tasCard.name +'" /></div>');
//	})

	// add a nice button for opening the iDealscreen
	$("div.tasCreditCards").append('<button id="tasCreditCardButton">'+ tasTextCommon[currLanguage]["button_start_payment"] +'</button>');


	// click events for the cards
//	$("div.tasCreditCards div.tasCreditCard").click(function() {
//		tasCardId = $(this).attr("id").substr(10);
//		tasCardName = $("img.tasCardName", $(this)).attr("title");
//
//		// select product
//		$('div.tasCreditCards div.tasCreditCard img.tasProductCheckbox').attr("src", tasBaseUrl +"images/tas2Checkbox.gif");
//		$('#tasCredit_'+ tasCardId +' img.tasProductCheckbox').attr("src", tasBaseUrl +"images/tas2CheckboxChecked.gif");
//		$("#tasCreditCardButton").text(tasTextCommon[currLanguage]["button_start_payment_cc"] +" "+ tasCardName)	;
//	});

	// click event for the start button
	$("#tasCreditCardButton").click(function() {
//		if (tasCardId == 0)  alert(tasTextCommon[currLanguage]["payment_cc_select_card"]);
//		else {
//			var windowArgs = buildWindowArgs(currText.windowsize.height, currText.windowsize.width);
//			var tasPaymentWindow = window.open('','TPS_245', windowArgs);
//
//			if (!tasPaymentWindow)  tasPaymentWindow = top;
//
//			tasPaymentWindow.location.href = tasPayUrl +'?session_id='+ session_id +'&card_id='+tasCardId +'&profile_id='+ selectedProfile +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&pack='+ pack +'&return_url='+ returnUrl +'&r='+ Math.random();
			document.location.href = tasPayUrl +'?session_id='+ session_id +'&card_id='+tasCardId +'&profile_id='+ selectedProfile +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&pack='+ pack +'&return_url='+ returnUrl +'&r='+ Math.random();
			// tasPaymentWindow.focus();
//		}
	});
}


function buildBankTransferContent() {
	var currText = tasTextProfiles[currLanguage][thisProfiles[selectedProfile].paymentMethod][selectedProfile];
	var thisProductData = thisProfiles[selectedProfile].products[selectedProduct];

	$('.tasStep:last').append('<p>'+ currText.desc +'</p><div class="tasBankTransfer"></div>');

	var tmpLabel = '';
	var tmpInfo = '';
	$.each(tasBankTransferItem[currLanguage] ,function(i, tasItem) {

		if(tasItem.field_type == "text")  tmpLabel = '<input class="tasBankTransferText" type="text" name="'+ tasItem.text_key +'" value="" />';
		else {

			if (tasItem.text_type == "config")  tmpInfo = tasConfig[tasItem.text_key];
			else if (tasItem.text_type == "product")  tmpInfo = thisProductData.amount + " euro";
			else if (tasItem.text_type == "desc") {
				var tmpDesc = strPad(session_id, 8, "0") + strPad(selectedProduct, 8, "0");
				tmpInfo = tmpDesc.substr(0, 4) +' '+ tmpDesc.substr(4, 4) + ' '+ tmpDesc.substr(8, 4) + ' '+ tmpDesc.substr(12,4);
			}
			else  tmpInfo = '';

			tmpLabel = '<input class="tasBankTransferText tasBankTransferTextValue" type="text" value="'+ tmpInfo +'" />';
		}

		if (tasItem.field_type == "info")  $("div.tasBankTransfer").append('<p style="margin-top: 18px;">' + tasItem.item_label + '</p>');
		else  $("div.tasBankTransfer").append('<div id="tasIdeal_' + tasItem.id + '" class="tasBankTransferItem"><label class="tasBankTransferLabel">' + tasItem.item_label + '</label>' + tmpLabel + '</div>');
	});

	$("input.tasBankTransferTextValue").click(function() {
		// $(this).focus().select();
	});

	// add a nice button for opening the iDealscreen
	$("div.tasBankTransfer").append('<button id="tasBankTransferItemButton">'+ tasTextCommon[currLanguage]["button_start_payment_bank"] +'</button>');


	// click event for the start button
	$("#tasBankTransferItemButton").click(function() {

		// get submitted values
		var tmpBankaccountOwner = $("input.tasBankTransferText[name='bankaccountowner']").val();
		var tmpBankaccountNumber = $("input.tasBankTransferText[name='bankaccountnumber']").val();
		var tmpEmailAddress = $("input.tasBankTransferText[name='emailaddress']").val();

		if(checkemail(tmpEmailAddress)) {
			var windowArgs = buildWindowArgs(currText.windowsize.height, currText.windowsize.width);
			var tasPaymentWindow = window.open('','TPS_245', windowArgs);
			if(!tasPaymentWindow)  tasPaymentWindow = top;
			tasPaymentWindow.location.href = tasPayUrl +'?session_id='+ session_id +'&language_id='+ currLanguage +'&profile_id='+ selectedProfile +'&email='+ tmpEmailAddress +'&country_id='+ selectedCountry +'&pack='+ pack +'&return_url='+ returnUrl +'&r='+ Math.random();
		}
	});
}

function buildCommonPaymentInfoContent( post ) {
	var currText = tasTextProfiles[currLanguage][thisProfiles[selectedProfile].paymentMethod][selectedProfile];
	var thisProductData = thisProfiles[selectedProfile].products[selectedProduct];

	$('.tasStep:last').append('<p>'+ currText.desc +'</p>').append('<button id="tasCommonButton">'+ tasTextCommon['nl']["button_start_payment"] +'</button>');

	// click event for the start button
	$("#tasCommonButton").click(function() {

		if (selectedProfile == "139")  document.location.href = tasPayUrl +'?session_id='+ session_id +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&profile_id='+ selectedProfile +'&product_id='+ selectedProduct +'&return_url='+ returnUrl +'&pack='+ pack +'&r='+ Math.random();
		else if (selectedProfile == "138")  document.location.href = tasPayUrl +'?session_id='+ session_id +'&language_id='+ currLanguage +'&profile_id='+ selectedProfile +'&product_id='+ selectedProduct +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&pack='+ pack +'&r='+ Math.random();
		else if (selectedProfile == "436")  document.location.href = tasPayUrl +'?session_id='+ session_id +'&language_id='+ currLanguage +'&profile_id='+ selectedProfile +'&product_id='+ selectedProduct +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&pack='+ pack +'&r='+ Math.random();
		else {
			var windowArgs = buildWindowArgs(currText.windowsize.height, currText.windowsize.width);
			var tasPaymentWindow = window.open('','TPS_245', windowArgs);

			if(!tasPaymentWindow)  tasPaymentWindow = top;

			tasPaymentWindow.location.href = tasPayUrl +'?session_id='+ session_id +'&language_id='+ currLanguage +'&profile_id='+ selectedProfile +'&product_id='+ selectedProduct +'&country_id='+ selectedCountry +'&language_id='+ currLanguage +'&pack='+ pack +'&return_url='+ returnUrl +'&r='+ Math.random();
			// tasPaymentWindow.focus();
		}
	});
}

function buildWindowArgs(h,w) {

	var t = (h/2)-15;
	var l = (w/2)-5;

	if (window.screen) {

		if(h > (screen.availHeight-30))  h = screen.availHeight - 30;
		if(w > (screen.availWidth-30))  w = screen.availWidth - 6;

		t = (screen.availHeight - h)/2-15;
		l = (screen.availWidth - w)/2-5;

		return "left="+ l +",screenX="+ l +",top="+ t +",screenY="+ t +",height="+ h +",innerHeight="+ h +",width="+ w +",innerWidth="+ w +",resizable,scrollbars";
	}
	return "left="+ l +",screenX="+ l +",top="+ t +",screenY="+ t +",resizable,scrollbars";
}

function strPad(str, newLength, padChar) {

	str = str.toString();
	var newStr = '';
	var key = 0;
	var strLength = str.length;

	if (strLength > newLength)  return str;

	for(i=0;i<newLength;i++) {
		key = strLength - (i+1);
		newStr = (str.charAt(key) ? str.charAt(key) : padChar) + newStr;
	}

	return newStr;
}



function profileDataCst(paymentMethod, callType, pincodeType, number, tariff) {

	tariff = new Number(tariff);
	this.paymentMethod = paymentMethod;
	this.callType = callType;
	this.pincodeType = pincodeType;
	this.number = number;
	this.tariff = tariff.toFixed(2);
}

function profileCst(id, paymentMethod, callType, pincodeType, number, tariff, currency_id, amount, products) {

	tariff = new Number(tariff);
	this.id = id;
	this.paymentMethod = paymentMethod;
	this.callType = callType;
	this.pincodeType = pincodeType;
	this.number = number;
	this.tariff = tariff.toFixed(2);
	this.currency_id = currency_id;
	this.products = products;
	this.amount = Math.ceil(amount*100);
}

function Product(id, amount, amount_euro, amount_euro_left, total_seconds, is_default) {

	var minutes = Math.floor(total_seconds/60);
	var seconds = total_seconds-(minutes*60);
	this.id = id;
	this.time = total_seconds;
	this.seconds = seconds;
	this.minutes = minutes;
	this.amount = amount;
	this.amount_left = amount_euro_left;
	this.amount_euro = Math.round(amount_euro*100);
	this.amount_euro_left = Math.round(amount_euro_left*100);
	this.isDefault = is_default;
}


function checkPincode( pincode ) {
	if (!checkPincodeSyntax(pincode))  alert(tasTextCommon[currLanguage]["pincode_false_alert"]);
	else {

		var paymentMethodId = thisProfiles[selectedProfile].paymentMethod;

		$.ajax({
			dataType: 'jsonp', jsonp: 'jsonp_callback', url: sessionApi,
			data: 'mode=check_pincode&resulttype=jsonp&payment_session_id='+ session_id +'&website_location_id='+ location_id +'&pincode='+ pincode +'&website_id='+ website_id +'&program_id='+ program_id +'&payment_method_id='+ paymentMethodId +'&promotor_id='+ promotor_id +'&promotor_tool='+ promotor_tool +'&promotor_info='+ promotor_info +'&domain_id='+ domain_id +'&ip_address='+ ip_address +'&object='+ object +'&extra1='+ extra1 +'&extra2='+ extra2 +'&extra3='+ extra3 +'&transferdata='+ transferdata +'&product_id='+ selectedProduct +'&r='+ Math.random(),
			success: function(data) {

				if (data.check == "1") {
					// a new session is added, so change the session id
					session_id = data.payment_session_id;
					secret = data.secret;
					timecheck = 1;
					getPaymentStatus(0);
				}
				else
				alert(tasTextCommon[currLanguage]["pincode_false_alert"]);

				setTimeout(function(){
					$("form.pin input[name='tasPincode']").val('');
					// $("form.pin input[name='tasPincode']").focus();
				}, 1500);
			}
		});
	}
}


function checkPincodeSyntax(pin) {
	var vChrs = "0123456789";

	if(pin.length == 0)   return false;
	if(pin == undefined)  return false;

	for (i=0; i<pin.length; i++) {
		if (vChrs.indexOf(pin.charAt(i)) == -1)  return false;
	}

	return true;
}


function getPaymentStatus( skipSetTimeout ) {

	if (timecheck == 0)  return false;

	// check necessary data
	if (session_id == 0 || session_id == undefined)  return false;

	$.ajax({
		// dataType:'json',
		dataType:'jsonp',jsonp: 'jsonp_callback',
		data:'mode=get_status&resulttype=jsonp&payment_session_id='+session_id +'&r='+Math.random(),
		url: sessionApi,
		success: function (data) {

			var status = data.status.toString();

			// select the correct status action
			switch(status) {

				case "3":  // pincode ok - filled the box on the screen
				case "4":  // pincode ok - pushed the code on the phone
				case "5":  // access without pincode (eg. number pool)
				paymentScreen(status, 1);

				if (paymentData.method_id == "3")  foo = 1;
				else if (skipSetTimeout != 1)  setTimeout(function(){ getPaymentStatus(); }, statusDelay);
				break;

				case "6":
				// not fully paid yet, show the payment progress bar (pfp)
				paymentScreen(status, 1);
				if (skipSetTimeout != 1)  setTimeout(function(){ getPaymentStatus(); }, statusDelay);
				break;

				case "8":
				// payment finished, show forward url
				paymentScreen(status);
				screenLoaded = 0;
				break;

				case "7":
				// access but exchange is not called (error)
				screenLoaded = 0;
				paymentScreen(status, 0);
				break;

				case "9":
				// pfp hung up not fully paid / ppm hung up further access denied
				if (paymentData.method_id == "5")  restartPayment();
				else if (paymentData.method_id == "2") {
					screenLoaded = 0;
					paymentScreenOpener(status);
				}
				break;

				case "11":
				// payment completed, multisession screen.
				// paymentScreen(status);
				multiSessionData();
				break;

				case "13":
				// payment successfull
				multiSessionData(status);
				break;

				case "0":
				case "1":
				case "2":
				case "10":
				default:
				if (skipSetTimeout != 1) {
					setTimeout(function() {
						getPaymentStatus();
					}, statusDelay);
				}
			}
		}
	});
}


function multiSessionData(status) {
	$.ajax({
		dataType:'jsonp',
		jsonp:'jsonp_callback',
		data:'mode=ms_login&resulttype=jsonp&access_code='+ paymentData.access_code +'&payment_session_id='+ session_id +'&secret='+ secret +'&r='+Math.random(),
		url: sessionApi,
		success: function (data) {

			if (data.result != "FALSE") {

				// show screen
				screenLoaded = 0;
				if(status == 13) {

					// direct access, use MS to fetch session data
					data.next = data.forward_url;
					paymentData = new paymentDetails(data);
					paymentScreenOpener(13);

				}
				else {

					// tasMsAccessTime = data.access_time;
					paymentData.access_code = data.access_code;
					paymentData.access_code_display = data.access_code ? data.access_code.substr(0, 4) + ' ' + data.access_code.substr(4, 4) + ' ' + data.access_code.substr(8, 4) + ' ' + data.access_code.substr(12, 4) : '';
					paymentData.ms_access_time = data.access_time;
					paymentData.ms_access_sessions = data.access_sessions;
					paymentData.ms_access_time_expire = data.access_expire_time;
					paymentData.ms_access_sessions_expire = data.access_expire_sessions;
					paymentData.forward_url = data.forward_url;

					// multisession
					paymentScreenOpener(11);

					if (paymentData.ms_access_time > 0 || paymentData.ms_access_sessions > 0) {

						if (paymentData.ms_access_time == 0 && paymentData.ms_access_sessions > 0) {
							tasMsAccessType = 'ses';
							$(".tasMsAccessTime").text(paymentData.ms_access_sessions + ' ' + tasTextCommon[currLanguage]["access_sessions_unit"]);
							$(".multiSessionStop").hide();
						}
						else {
							tasMsAccessType = 'min';
							$(".tasMsAccessTime").text(convertSeconds2MinSec(paymentData.ms_access_time) + ' ' + tasTextCommon[currLanguage]["access_time_unit"]);
							$(".multiSessionStop").show();
						}

						$(".tasMsAccessSessions").text(paymentData.ms_access_sessions);
						$(".tasMsAccessTimeExpire").text(convertSeconds2MinSec(paymentData.ms_access_time_expire));
						$(".tasMsAccessSessionsExpire").text(paymentData.ms_access_sessions_expire);

						// $("#tasMsAccessCountdown, div.tasInfo, .multiSessionStart").show();
						tasMsAccessTime = paymentData.ms_access_time
						multiSessionAccessCountdown();


						// add start event
						$(".multiSessionStop").attr("src", tasBaseUrl +"images/tasButtonStopToegangGrey.gif").removeClass("hand");

						$(".multiSessionStart").attr("src", tasBaseUrl +"images/tasButtonStartToegang.gif").addClass("hand").bind("click", function(){
							startAccess();
						});
					}
					else {
						if (tasMsAccessType == 'ses')  $(".tasMsAccessTime").text(paymentData.ms_access_sessions + ' ' + tasTextCommon[currLanguage]["access_sessions_unit"]);
						else  $(".tasMsAccessTime").text(convertSeconds2MinSec(paymentData.ms_access_time) + ' ' + tasTextCommon[currLanguage]["access_time_unit"]);

						// $(".tasInfo, .multiSessionStop, .multiSessionStart, div.tasDialogSuccess").hide();
						$("div.tasDialogMsExpire").show();
					}

					if(paymentData.ms_access_sessions_expire == "1") {
						$(".multiSessionStop, .tasMailInfo").remove();
					}

					if(tasMsAccessType == 'ses' && paymentData.ms_access_sessions < 2) {
						$(".tasMailInfo").remove();
					}
				}
			}
			else {

				$(".tasClock, .tasClockOptions, #divForwardUrl").hide();
				$("div.tasDialogMsExpire").show();
				$(".tasMailInfo").remove();

				// check if payment info is known
				if (website_id > 0 && program_id > 0) {

					$("div.tasPayLoading").html("<span>"+ tasTextCommon[currLanguage]["access_ended"] +" "+ tasTextCommon[currLanguage]["access_click_start"] +"</span>").addClass("hand").click(function(){ reloadPaymentScreen(); });
				}
				else {
					$("div.tasPayLoading").text(tasTextCommon[currLanguage]["access_ended"]);
				}
			}
		}
	});
}



function startAccess(){

	// unbind click event for startbutton
	if (tasMsAccessType != "ses") {
		$(".multiSessionStart").attr("src", tasBaseUrl +"images/tasButtonStartToegangGrey.gif").removeClass("hand").unbind("click");
	}

	$.ajax({
		dataType:'jsonp',
		jsonp:'jsonp_callback',
		url: sessionApi,
		data:'mode=ms_start&resulttype=jsonp&access_code='+ paymentData.access_code +'&r='+Math.random(),
		success: function(data){
			if (tasMsAccessType == "ses") {

				// show url
				$("#divForwardUrl").show();

				// start the countdown
				startTimer();

				// hide start button
				$(".multiSessionStart").unbind("click").remove();
			}
			else {

				if (data.result == "TRUE") {

					// set clickevent for stopbutton with a litte delay
					$(".multiSessionStop").attr("src", tasBaseUrl +"images/tasButtonStopToegang.gif").addClass("hand").bind("click", function(){ stopAccess(); });

					// start the countdown
					startTimer();

					// start checking access
					tasMsAccessDoCountdown = 1;
					setTimeout(function(){
						multiSession( 'check' );
					}, 3000);

					tasMsAccessTime = paymentData.ms_access_time - 1;
					tasMsAccessSessions = paymentData.ms_access_sessions;

					// show url
					$("#divForwardUrl").show();
				}
				else {

					// rebind click event for startbutton
					$(".multiSessionStart").attr("src", tasBaseUrl +"images/tasButtonStartToegang.gif").addClass("hand").bind("click", function(){ startAccess(); });
				}
			}
		},
		error: function(){

			// unbind click event for startbutton
			$(".multiSessionStart").attr("src", tasBaseUrl +"images/tasButtonStartToegang.gif").addClass("hand").bind("click", function(){ startAccess(); });
		}
	});
}

function stopAccess(){

	// unbind click event for stopbutton
	$(".multiSessionStop").attr("src", tasBaseUrl +"images/tasButtonStopToegangGrey.gif").removeClass("hand").unbind("click");

	$.ajax({
		dataType:'jsonp',jsonp:'jsonp_callback',
		url: sessionApi,
		data:'mode=ms_stop&resulttype=jsonp&access_code='+ paymentData.access_code +'&r='+ Math.random(),
		success: function(data){

			if (data.result == "TRUE") {

				// start the countdown
				stopTimer();

				// hide url
				$("#divForwardUrl").hide();

				// fetch renewed data
				multiSessionData();
			}
			else {
				$(".multiSessionStop").attr("src", tasBaseUrl +"images/tasButtonStopToegang.gif").addClass("hand").bind("click", function(){ stopAccess(); });
			}
		},
		error: function(){
			$(".multiSessionStop").attr("src", tasBaseUrl +"images/tasButtonStopToegang.gif").addClass("hand").bind("click", function(){ stopAccess(); });
		}
	});
}



function convertSeconds2MinSec(seconds) {

	var tmp = new Number(seconds);
	var min = Math.floor(seconds/60);
	var sec = seconds - Math.floor(min*60);

	if(sec < 10) return min+':0'+sec;
	else return min+':'+sec;
}


function  multiSession( mode ) {

	if (tasMsDoCheck != 1 || tasMsAccessType == "ses")  return;

	// get the payment data
	$.ajax({
		dataType:'jsonp',
		jsonp:'jsonp_callback',
		data:'mode=ms_check&resulttype=jsonp&access_code='+ paymentData.access_code +'&r='+Math.random(),
		url: sessionApi,
		success: function (data) {

			// check if stop button isn't pressed
			if (tasMsDoCheck == 1) {

				// set the payment data
				if (data.result == "TRUE") {

					// user has still access, keep on checking
					setTimeout(function(){
						multiSession('check');
					}, statusDelay);
				}
				else {

					// stop checking
					tasMsDoCheck = 0;

					// stop the countdown
					stopTimer();

					// fetch renewed data
					multiSessionData();

					// hide url
					$("#divForwardUrl").hide();

				}
			}
		}
	});
}


function startTimer() {
	tasMsDoCheck = 1;
	tasMsAccessDoCountdown = 1;
	multiSessionAccessCountdown();
}

function stopTimer() {
	tasMsDoCheck = 0;
	tasMsAccessDoCountdown = 0;
}

function multiSessionAccessCountdown() {

	var seconds, minutes, hours = 0;
	var str = '';

	// define the data
	if (tasMsAccessType == 'ses') {

		// use sessions
		if (tasMsAccessTime != -1 && tasMsAccessDoCountdown == 1) tasMsAccessSessions = paymentData.ms_access_sessions -1;
		else tasMsAccessSessions = paymentData.ms_access_sessions;


		$(".tasInfo").html(tasMsAccessSessions +' '+ tasTextCommon[currLanguage]["access_sessions_unit"]);
	}
	else {

		// use time
		hours 	= Math.floor(tasMsAccessTime/3600);
		minutes = Math.floor((tasMsAccessTime - (hours*3600)) / 60);
		seconds = tasMsAccessTime - (hours*3600) - (minutes*60);

		if (hours > 0) str = str + hours + ' <span>uur</span> ';

		if (minutes > 1 || hours > 0) str = str + minutes + ' <span>min.</span> ';
		else if (minutes == 1) str = str + minutes + ' <span>min.</span> ';

		if (seconds != 1) str = str + seconds + ' <span>sec.</span> ';
		else if (seconds == 1) str = str + seconds + ' <span>sec.</span> ';

		$(".tasInfo").html(str);
		if (tasMsAccessTime != -1 && tasMsAccessDoCountdown == 1) {
			tasMsAccessTime--;
			setTimeout(function(){ multiSessionAccessCountdown(); }, 1000);
		}
	}
}


function paymentScreen(status, checkLoaded) {

	if (checkLoaded == 1 && screenLoaded == 1)
	return true;

	// get the payment data
	$.ajax({
		dataType: 'jsonp',
		jsonp: 'jsonp_callback',
		data: 'mode=get_session_details&resulttype=jsonp&payment_session_id='+ session_id +'&secret='+ secret +'&r='+Math.random(),
		url: sessionApi,
		success: function (data) {

			// set the payment data
			if (data.payment_profile_id) {

				paymentData = new paymentDetails(data);
				paymentScreenOpener(status);

				if(data.refresh_interval && data.refresh_interval > 0) {
					statusDelay = data.refresh_interval*1000;
				}

				if (status == 11)  multiSessionData();
			}
		}
	});
}


function paymentScreenOpener(status) {

	// check data
	if (paymentData.method_id == undefined) {

		if (directPaymentMethod > 0) paymentData.method_id = directPaymentMethod;
		else if (profileData && profileData[selectedProfile]) paymentData.method_id = new Number(profileData[selectedProfile].paymentMethod);
	}

	// get the appropriate content
	var title 			= 	tasText[currLanguage][paymentData.method_id][status]['title'];
	var content 		= 	tasText[currLanguage][paymentData.method_id][status]['content'];
	var screenHeight 	= 	tasText[currLanguage][paymentData.method_id][status]['screen_height'];


	// place the data in the content
	$.each(paymentData, function(name, value) {
		try {
			content = content.replace('%'+ name +'%', value);
		}
		catch (err)	{
		}
	});


	// open the screen with the appropriate data
	openScreen(title, content, screenHeight);

	// add close click event
	$('.tasOverlayCloser').click(function()	{ restartPayment(); });
	$('.tasRestartPayment').click(function() { restartPayment(0); });
	$('.multiSessionRestart').click(function() { reloadPaymentScreen(); });


	$('#tasMsEmailSend').click(function() {

		var emailaddress = $('#tasMsEmailInput').val();
		if (emailaddress != '') {

			// submit e-mailaddress and send access instructions
			$.ajax({
				dataType:'jsonp',jsonp:'jsonp_callback',
				data:'mode=ms_mail_info&resulttype=jsonp&payment_session_id='+ session_id +'&email='+ emailaddress +'&access_code='+ paymentData.access_code +'&r='+Math.random(),
				url: sessionApi,
				success: function (data) {

					// set the payment data
					if (data.result == "TRUE") {

						alert(tasTextCommon[currLanguage]["email_send_success"]);

						// reset email field
						setTimeout(function(){ $('#tasMsEmailInput').val(''); }, 1500);
					}
					else {
						alert(tasTextCommon[currLanguage]["email_send_error"]);
					}
				}
			});
		}
	});

	$('.multiSessionVisit, .tasForwardUrl').click(function() {
		if(pack == "download")  return true;
		var nw = window.open();
		if(!nw)   nw = top;
		nw.document.location = paymentData.forward_url;
		return false;
	});
}

function checkemail(str){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)) {

		return true;
	}

	window.alert( tasTextCommon[currLanguage]["email_incorrect"] );
	return false;
}


function paymentDetails(data) {

	if (profileData[data.payment_profile_id]) var thisProfileData = data.payment_profile_id
	if (data.payment_method_id)	this.method_id = data.payment_method_id;
	else if (profileData[data.payment_profile_id] && profileData[data.payment_profile_id].paymentMethod) this.method_id = profileData[data.payment_profile_id].paymentMethod;

	this.access_code  				= 	data.access_code ? data.access_code : 0;
	this.access_code_display 	= 	data.access_code ? data.access_code.substr(0,4) +' '+ data.access_code.substr(4,4) +' '+ data.access_code.substr(8,4) +' '+ data.access_code.substr(12,4) : 0;
	this.profile_id 					= 	data.payment_profile_id ? data.payment_profile_id : 0;
	this.forward_url 					= 	data.next ? data.next : '';
	this.tariff 							= 	data.tariff ? data.tariff : 0;
	this.object 							= 	data.object ? data.object : '';
	this.info 								= 	data.info ? data.info : '';
	this.tool 								= 	data.tool ? data.tool : '';
	this.transfer_data 				=		data.transfer_data ? data.transfer_data : '';

	if (data.total) {
		this.total_minutes 		=	data.total.minutes ? data.total.minutes : 0;
		this.total_seconds 		=	data.total.seconds ? data.total.seconds : 0;
		this.total_amount 		=	data.total.amount ? data.total.amount : 0;
		this.paidSoFar 				=	data.total.amount ? data.total.amount : 0;
	}

	if (data.active) {
		this.holding_minutes 	=	data.active.minutes ? data.active.minutes : 0;
		this.holding_seconds 	=	data.active.seconds ? data.active.seconds : 0;
		this.holding_amount 	=	data.active.amount ? data.active.amount : 0;
		this.holding_total 	=	data.active.total ? data.active.total : 0;
	}

	if (data.remaining) {
		this.remaining_total 	=	data.remaining.total ? data.remaining.total : 0;
		this.remaining_minutes 	=	data.remaining.minutes ? data.remaining.minutes : 0;
		this.remaining_seconds 	=	data.remaining.seconds ? data.remaining.seconds : 0;
		this.remaining_amount 	=	data.remaining.amount ? data.remaining.amount : 0;
	}

	this.ms_access_time 						=		data.access_time ? data.access_time : '';
	this.ms_access_sessions 				= 	data.access_sessions ? data.access_sessions : '';
	this.ms_access_time_expire 			= 	data.access_expire_time ? data.access_expire_time : '';
	this.ms_access_sessions_expire 	= 	data.access_expire_sessions ? data.access_expire_sessions : '';
}


function setProfileProduct() {

	
	return;
	
	// check product
	if (selectedProduct == '' || selectedProduct == undefined || selectedProduct == 0)  return false;
	if (session_id == '' || session_id == 0 || session_id == undefined)  return false;

	// set the values
	$.ajax({
		dataType:'jsonp',jsonp: 'jsonp_callback',
		data:'mode=set_product&resulttype=jsonp&payment_session_id='+ session_id +'&product_id='+ selectedProduct +'&extra1='+ extra1 +'&extra2='+ extra2 +'&extra3='+ extra3 +'&transferdata='+ transferdata +'&r='+ Math.random(),
		url: sessionApi,
		success: function (data) {
		}
	});
}

function restartPayment(resetSession) {

	// use this function only if the customer has not been redirected back to this screen
	if ($("#tasPaymentInfo input[name='direct_status_check']").attr("value") == "1") {
		reloadPaymentScreen();
	}
	else {

		if(resetSession != 0) session_id = 0;
		screenLoaded = 0;
		$("#tas2AccessContainer").hide();
		$("#tas2AccessContent").text('');
		$("#tas2ContentContainer").show();
		timecheck = 1;
		tasMsDoCheck = 0;
		tasMsAccessDoCountdown = 0;
		init();
	}
}


function reloadPaymentScreen() {

	// define url for reloading the window
	var tmpUrl =  thisUrl +'?program_id='+ program_id +'&website_id='+ website_id +'&country_id='+ selectedCountry +'&language_id='+ currLanguage;

	if (selectedProfile != '' && selectedProfile != undefined)  	tmpUrl = tmpUrl +'&profile_id='+ selectedProfile;
	if (selectedProduct != '' && selectedProduct != undefined)  	tmpUrl = tmpUrl +'&product_id='+ selectedProduct;
	if (promotor_id != '' && promotor_id != undefined)  					tmpUrl = tmpUrl +'&promotor_id='+ promotor_id;
	if (promotor_info != '' && promotor_info != undefined)  			tmpUrl = tmpUrl +'&info='+ promotor_info;
	if (promotor_tool != '' && promotor_tool != undefined)  			tmpUrl = tmpUrl +'&tool='+ promotor_tool;
	if (domain_id != '' && domain_id != undefined)								tmpUrl = tmpUrl +'&domain_id='+ domain_id;
	if (location_id != '' && location_id != undefined)						tmpUrl = tmpUrl +'&location_id='+ location_id;
	if (object != '' && object != undefined) 											tmpUrl = tmpUrl +'&object='+ object;
	if (pack != '' && pack != undefined) 													tmpUrl = tmpUrl +'&pack='+ pack;
	if (extra1 != '' && extra1 != undefined) 											tmpUrl = tmpUrl +'&extra1='+ extra1;
	if (extra2 != '' && extra2 != undefined) 											tmpUrl = tmpUrl +'&extra2='+ extra2;
	if (extra3 != '' && extra3 != undefined) 											tmpUrl = tmpUrl +'&extra3='+ extra3;
	if (display != '' && extra3 != undefined) 										tmpUrl = tmpUrl +'&display='+ display;
	if (path != '' && extra3 != undefined) 												tmpUrl = tmpUrl +'&path='+ path;
	if (transferdata != '' && transferdata != undefined && transferdata != "[=]") 	tmpUrl = tmpUrl +'&raw_transferdata='+ transferdata;

	// get new paymentscreen
	document.location.href = tmpUrl;
}

/**** OVERLAYING SCREEN ****/
function openScreen(screenTitle, screenContent, screenHeight){

	if (screenLoaded != 0)
		return;

	screenLoaded = 1;

	// hide loading div
	$("div.tasPayLoading").hide();

	$("#tas2AccessContent *").remove();
	$("#tas2AccessContent").append( '<div class="tasStep"><h1 class="title">'+ screenTitle +'</h1><div class="scrContent">'+ screenContent +'</div></div>' );

	$("#tas2ContentContainer").hide();
	$("#tas2AccessContainer").show();
	$("#tas2Container, #tasCopyFooter").show();

	// add event for possibility to restart payment
	$(".restartPayment").click(function(){
		restartPayment();
	});
}

