function exportList(viewname, pagefrom, pagesize, sort, filter, fixedfilter, type){
	window.location = viewname+".php?page="+pagefrom+"&pagesize="+pagesize
				+ (sort != null ? '&sfield='+sort['field']+'&sorder='+sort['order'] : '')
				+ (filter != null ? '&ffield='+filter['field']+'&fcomp='+filter['comp']+'&fvalue='+filter['value'] : '')
				+ (fixedfilter && fixedfilter != null ? '&fixed='+fixedfilter : '&fixed='+0)
				+ (type ? "&"+type+"=" : "")
				+ '&__dt=' + new Date();
	return false;
}

var savedViewArray = new Array();

function backToView(viewname){
	var arViewParams = savedViewArray[viewname];
	if (arViewParams == null){
			reloadView(viewname,1,20);
	}else{
		reloadView(viewname,arViewParams['pagefrom'],arViewParams['pagesize'],arViewParams['sort'],arViewParams['filter'],arViewParams['fixedfilter']);
	}
}

function reloadView(viewname, pagefrom, pagesize, sort, filter, fixedfilter, type){
	if (type) return exportList(viewname, pagefrom, pagesize, sort, filter, fixedfilter, type);

	savedViewArray[viewname] = new Array();
	savedViewArray[viewname]['pagefrom'] = pagefrom;
	savedViewArray[viewname]['pagesize'] = pagesize;
	savedViewArray[viewname]['sort'] = sort;
	savedViewArray[viewname]['filter'] = filter;
	savedViewArray[viewname]['fixedfilter'] = fixedfilter;

	$.ajax({
		type: "GET",
		url: viewname+".php",
		data: "page="+pagefrom+"&pagesize="+pagesize
				+ (sort != null ? '&sfield='+sort['field']+'&sorder='+sort['order'] : '')
				+ (filter != null ? '&ffield='+filter['field']+'&fcomp='+filter['comp']+'&fvalue='+filter['value'] : '')
				+ (fixedfilter && fixedfilter != null ? '&fixed='+fixedfilter : '&fixed='+0)
				,
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			$("#div"+viewname).replaceWith(data.responseText);
		}
	});
}
function padZero(num) {
	return (num	< 10)? '0' + num : num ;
}
function fillHiddenDateField(){
	var dt = $(this).datepicker("getDate");
	var id = this.id;
	if (id.indexOf('_') == 0) id = id.substring(1);
	else id = '_'+id;
	document.getElementById(id).value = formatDate(dt);
}
function viewAccount(abnid){
	$.ajax({
		type: "GET",
		url: "account.php",
		data: "abnid="+abnid,
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			$('#divaccounts').replaceWith(data.responseText);
			$('#tabs').tabs('select', 0);
		}
	});
}
function viewCompany(abncompanyid){
	$.ajax({
		type: "GET",
		url: "company.php",
		data: "abncompanyid="+abncompanyid,
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			$('#divcompanies').replaceWith(data.responseText);
			$('#tabs').tabs('select', 5);
		}
	});
}
var selectTab = 0;
function startTransaction(abnid, isprest){
	selectTab = isprest ? 1 : 2;
	$.ajax({
		type: "GET",
		url: "transaction.php",
		data: "abnid="+abnid,
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			$("#divtransaction").replaceWith(data.responseText);
			$('#tabs').tabs('select', selectTab);
		}
	});
}

var busyBatchConfirm = false;
function setBusyBatchConfirm(bbc){
	busyBatchConfirm = bbc;
}
function getBusyBatchConfirm(){
	return busyBatchConfirm;
}

function confirmTransaction(transactionid, statusflag){
	var confirmed = true;
	if (!getBusyBatchConfirm()){
		confirmed = confirm('Are you sure?');
	}
	if (confirmed){
		$.ajax({
			type: "GET",
			url: "/ctrl/transaction/confirm.php",
			data: "transactionid="+transactionid+"&statusflag="+statusflag,
			dataType: "xml",
			cache: false,
			complete : function(data, status) {
				if (data.responseXML.documentElement.firstChild.nodeValue == 'ok'){
					var statText = 'ok';
					if (statusflag == 1) statText = 'confirmed';
					if (statusflag == 2) statText = 'cancelled';
					document.getElementById('transactionid_'+transactionid).innerText = document.getElementById('transactionid_'+transactionid).innerHTML = statText;
					document.getElementById('transactionid_'+transactionid).className = 'transactionstatus transactionstatus'+statusflag;
				}
				setBusyBatchConfirm(false);
			}
		});
	}
}
function setSelVal(objref, val){
	for (var i = 0; i < objref.options.length;i++){
		if (objref.options[i].value == val){
			objref.options[i].selected = true;
			return;
		}
	}
}
function getSortOptions(type){
	if (!type) type = '';
	return { field:$('#'+type+'sortfield').val(), order:$('#'+type+'sortorderDESC').hasClass('selected') ? 'DESC' : 'ASC' }
}
function getFilterOptions(type){
	if (!type) type = '';
	return { field: $('#'+type+'searchfield').val(), comp: $('#'+type+'searchcomp').val(), value: $('#'+type+'searchvalue').val() }
}
function getFixedFilter(type){
	if (!type) type = '';
	for (var ii = 0;ii < 20;ii++){
		if ($('#'+type+'fixedfilter_'+ii).hasClass('selected')) return ii;
	}
}
function saveUser(){
	if ($('#changeduid')){
		if ($('#originalAbnuid').val() != $('#Abnuid').val() && $('#changeduid').val() == 'false'){
			alert('Please verify login first');
			return false;
		}
	}
	var _abnid = $('#AbnId').val();
	var params = val('AbnId') + val('Lastname') + val('Firstname') + val('Language') + val('AdrStreet') + val('AdrCP') + val('AdrCity')
			+ (document.getElementById('ShopId') != null ? val('ShopId') : '')
			+ (document.getElementById('changeduid') != null && $('#originalAbnuid').val() != $('#Abnuid').val() ? val('Abnuid') : '')
			+ val('Phone')
			+ (!$('#Email').attr('disabled') ? val('Email') : '')
			+ (document.getElementById('CompanyName') != null ? val('CompanyName') : '')
			+ (document.getElementById('SodexoNr') != null ? val('SodexoNr') : '')
			+ '&Title='
				+ (document.getElementById('TitleF') != null && $('#TitleF').attr('checked') ? 'F' : 'M')
			+ '&TSType='
				+ (document.getElementById('TSTypeP') != null && $('#TSTypeN').attr('checked') ? 'N' : '')
				+ (document.getElementById('TSTypeP') != null && $('#TSTypeP').attr('checked') ? 'P' : '')
				+ (document.getElementById('TSTypeP') != null && $('#TSTypeE').attr('checked') ? 'E' : '')
			+ '&onSite='
				+ (document.getElementById('onSiteY') != null && $('#onSiteY').attr('checked') ? 'Y' : '')
				+ (document.getElementById('onSiteN') != null && $('#onSiteN').attr('checked') ? 'N' : '')
				+ (document.getElementById('onSiteP') != null && $('#onSiteP').attr('checked') ? 'P' : '')
			+ (document.getElementById('UnpaidTS') != null ? '&UnpaidTS='+$('#UnpaidTS').attr('checked') : '')
			+ (document.getElementById('UnpaidTSE') != null ? '&UnpaidTSE='+$('#UnpaidTSE').attr('checked') : '')
			+ '&EasyBox=' + ( (document.getElementById('EasyBox1') != null && !$('#EasyBox1').attr('disabled') && $('#EasyBox1').attr('checked')) || ( document.getElementById('EasyBox2') != null && !$('#EasyBox2').attr('disabled') && $('#EasyBox2').attr('checked')) ? 'Y' : 'N')
			+ (document.getElementById('Company') != null ? (($('#Company').val() != '' ? '&compupdate='+$('#Company').val() : '')) : '')
			+ (document.getElementById('prevUnpaidTS') != null ? '&prevUnpaidTS='+$('#prevUnpaidTS').val() : '')
			+ (document.getElementById('prevUnpaidTSE') != null ? '&prevUnpaidTSE='+$('#prevUnpaidTSE').val() : '')
			+ (document.getElementById('ConfortUnitLimit') != null ? '&ConfortUnitLimit='+$('#ConfortUnitLimit').val() : '')
			+ (document.getElementById('isValidated') != null ? '&isValidated=' + $('#isValidated').val() : '')
			+ (document.getElementById('CashLimit') != null ? '&CashLimit=' + $('#CashLimit').val() : '')
			+ ($('#homeaddressvalidated').attr('lang') == 'go' ? '&homeaddressvalidated='+$('#homeaddressvalidated').attr('lang') : '')
			;
	$.ajax({
		type: "POST",
		url: "/ctrl/account/update.php",
		data: params,
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			if (data.responseXML.documentElement.firstChild.nodeValue == 'ok'){
				viewAccount(_abnid);
			}
		}
	});
}
function saveCompany(){
	var _abnid = $('#ABNCompanyId').val();
	var params = val('ABNCompanyId') + val('cCompanyValidated') + val('cCompanyName') + val('cCompanyAdrStreet') + val('cCompanyAdrCP') + val('cCompanyAdrCity') + val('cPhone') + val('cEmail')
				+ val('cContactName') + val('cContactPhone') + val('cContactEmail') + val('cCompanySearchable') + val('cEasyBox')
				+ '&cCompanySearchable='+$('#cCompanySearchable').attr('checked')
				+ '&cEasyBox='+$('#cEasyBox').attr('checked')
				;
	$.ajax({
		type: "POST",
		url: "/ctrl/company/update.php",
		data: params,
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			if (data.responseXML.documentElement.firstChild.nodeValue == 'ok'){
				viewCompany(_abnid);
			}
		}
	});
}
function val(fieldname){
	if (!$('#'+fieldname)) return '';
	return '&'+fieldname+'='+URLEncode($('#'+fieldname).val());
}
function URLEncode(sXml){
    for (var i = 0; i<sXml.length; i++) {
    	if(/*sXml.charCodeAt(i)>128 || */sXml.charCodeAt(i)==60 || sXml.charCodeAt(i)==62 || sXml.charCodeAt(i)==38 || sXml.charCodeAt(i)==39 || sXml.charCodeAt(i)==43 ) {
    		var charint = sXml.charCodeAt(i);
    		sXml = sXml.substring(0,i)+'%'+charint.toString(16)+sXml.substring(i+1,sXml.length);
    	}
    }
    return sXml;    
}
function XMLEncode(sXml){
    for(var i = 0; i < sXml.length; i++) {
    	if(sXml.charCodeAt(i)==60 || sXml.charCodeAt(i)==62 || sXml.charCodeAt(i)==34  || sXml.charCodeAt(i)==39 || sXml.charCodeAt(i)==38 ) {
    		var charint = sXml.charCodeAt(i);
    		sXml = sXml.substring(0,i)+'&#'+charint+';'+sXml.substring(i+1,sXml.length);
    	}
    }
    return sXml;    
}
function checkDouble(obj, evt){
	switch(evt.keyCode){
		case 8: // back
		case 9: // tab
		case 9: // shift
		case 9: // ctrl
		case 37: // cursor right
		case 38: // cursor left
		case 39: // cursor up
		case 40: // cursor bottom
		case 35: // home
		case 36: // end
		case 46: // del
				return true;
	}
	var string = "1234567890,";
	var tmp = '';
	var pointTrouV = false;
	for (var i = 0;i < obj.value.length;i++){
		if (string.indexOf(obj.value.charAt(i)) >= 0){
			if (pointTrouV && obj.value.charAt(i) == ',') continue;
			if (obj.value.charAt(i) == ',') pointTrouV = true;
			tmp += obj.value.charAt(i);
		}
	}
	obj.value = tmp;
}
function getTransactionType(){
	if ($('#typeflag0p').hasClass('btntstypeselected')) return 0;
	if ($('#typeflag1p').hasClass('btntstypeselected')) return 1;
	if ($('#typeflag2p').hasClass('btntstypeselected')) return 2;
	if ($('#typeflag0m').hasClass('btntstypeselected')) return 0;
	if ($('#typeflag1m').hasClass('btntstypeselected')) return 1;
	if ($('#typeflag2m').hasClass('btntstypeselected')) return 2;
}
function formatDate(dt){
	return dt.getFullYear()+"-"+padZero(dt.getMonth()+1)+"-"+padZero(dt.getDate());
}
function btnsearchclient(){
	$.ajax({
		type: "GET",
		url: "/ctrl/account/get.php",
		data: 'searchclient=' + $('#searchclient').val(),
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			var doc = data.responseXML;
			if (doc.getElementsByTagName('auth')[0].firstChild.nodeValue == 'ok'){
				var searchcount = doc.getElementsByTagName('searchcount')[0].firstChild.nodeValue;
				
				$('#divsearchcount').addClass('hidden');

				if (parseInt(searchcount) >= 3){
					$('#divsearchcount').removeClass('hidden');
					document.getElementById('spansearchcount').innerText = document.getElementById('spansearchcount').innerHTML = searchcount;
				}
				if (doc.getElementsByTagName('found')[0].firstChild.nodeValue == 'true'){
					document.getElementById('searchresult').innerHTML = 
					'<a href="#" onclick="startTransaction('+doc.getElementsByTagName('AbnId')[0].firstChild.nodeValue+','+(doc.getElementsByTagName('AccType')[0].firstChild.nodeValue == 2) +')">'
					+ doc.getElementsByTagName('Lastname')[0].firstChild.nodeValue + ' '
					+ doc.getElementsByTagName('Firstname')[0].firstChild.nodeValue
					+ '</a><br/>'
					+ doc.getElementsByTagName('Info')[0].firstChild.nodeValue
					;
				}else if (doc.getElementsByTagName('found')[0].firstChild.nodeValue == 'forbidden'){
					document.getElementById('searchresult').innerHTML = 'You have no right to see this client';
				}else{
					document.getElementById('searchresult').innerHTML = 'AbnId not found';
				}
			}else{
				$('#divsearchcount').addClass('hidden');
				$('#divsearchblocked').removeClass('hidden');
			}
		}
	});	
}
function contactABN(){
	$.ajax({
		type: "POST",
		url: "/ctrl/email/contactabn.php",
		data: 'message='+$('#contactabnmessage').val(),
		dataType: "xml",
		cache: false,
		complete : function(data, status) {
			if (data.responseXML.documentElement.firstChild.nodeValue == 'ok'){
				$("#divabncontactrequest").addClass('hidden');
				$("#divabncontactresponse").removeClass('hidden');
			}
		}
	});	
}
function getEventSourceObject(e){
	if (!e) e = window.event;

	var returnedobj = null;

	if (document.all) {	// IE
		returnedobj = window.event.srcElement;
	} else if (document.getElementById) {	// Netscape 6
		if (e.target) returnedobj = e.target;
		else if (e.currentTarget) returnedobj = e.currentTarget;
		else returnedobj = e.srcElement;
	}
	if (returnedobj != null && returnedobj.nodeType == Node.TEXT_NODE){		// defeat Safari bug
		returnedobj = returnedobj.parentNode;
	}
	return returnedobj;
}
function removeNonDigit(fi){
	switch(event.keyCode){
		case 8: // back
		case 9: // tab
		case 37: // cursor right
		case 38: // cursor left
		case 39: // cursor up
		case 40: // cursor bottom
		case 35: // home
		case 36: // end
		case 46: // del
				return true;
	}
	var string = "1234567890";
	var tmp = '';
	for (var i = 0;i < fi.value.length;i++){
		if (string.indexOf(fi.value.charAt(i)) >= 0 || (i == 0 && fi.value.charAt(i) == '-')){
			tmp += fi.value.charAt(i);
		}
	}
	fi.value = tmp;
}
function removeNonDigitFromEvent(e){
	if (!e && window.event) e = window.event;

	removeNonDigit(getEventSourceObject(e));
}
function checkEnter(e){         // e is event object passed from function invocation
	if (!e) e = window.event;
	var characterCode           // literal character code will be stored in this variable
	if (e && e.which){      // if which property of event object is supported (NN4)
		characterCode = e.which;     // character code is contained in NN4's which property
	}else{
		characterCode = e.keyCode   // character code is contained in IE's keyCode property
	}
	if (characterCode == 13){       // if generated character code is equal to ascii 13 (if enter key)
		return true
	}else{
		return false
	}
}

function addcashtoconfortline(){
	$.ajax({
		type: "POST",
		url: "/ctrl/cashtoconfort/add.php",
		data: '',
		dataType: 'xml',
		cache: false,
		complete : function(data, status) {
			$.ajax({
				type: "GET",
				url: "admin.php",
				data: "",
				dataType: "xml",
				cache: false,
				complete : function(data, status) {
					$('#divadmin').replaceWith(data.responseText);
					$('#tabs').tabs('select', 4);
				}
			});
		}
	});
}
function updatecashtoconfortline(buyid, confortvalue, cashvalue, comment, active){
	$.ajax({
		type: "POST",
		url: "/ctrl/cashtoconfort/update.php",
		data: 'buyid='+buyid+'&confortvalue='+confortvalue+'&cashvalue='+cashvalue+'&active='+active+'&comment='+URLEncode(comment),
		dataType: 'xml',
		cache: false,
		complete : function(data, status) {
			newid = data.responseXML.documentElement.firstChild.nodeValue;
			if (newid >= 0){
				$.ajax({
					type: "GET",
					url: "admin.php",
					data: "",
					dataType: "xml",
					cache: false,
					complete : function(data, status) {
						$('#divadmin').replaceWith(data.responseText);
						$('#tabs').tabs('select', 4);
					}
				});
			}
		}
	});
}
var tr_abnid = -1;
function transfertCashToCU(buyid, abnid){
	tr_abnid = abnid;
	$.ajax({
		type: "POST",
		url: "/ctrl/cashtoconfort/buy.php",
		data: 'buyid='+buyid+'&abnid='+abnid,
		dataType: 'xml',
		cache: false,
		complete : function(data, status) {
			viewAccount(tr_abnid);
			reloadView('transactions',1,20,{ field:'t.CreationDate', order:'DSC' },getFilterOptions('t'),getFixedFilter('t'));
		}
	});
}

