// Copyright 2008, Tobias Deutsch
// eMail: tobias-copyright@strix.at
// Homepage: www.strix.at

function SPLITLINE(line) {
	return line.split(";", 9);
}

function PROCESSFIRSTLINE(line) {
	data = SPLITLINE(line);
	
	if (data.length != 9) {
		return "ERROR processing line:\n"+line+"\n\n"
	}
	
	date = data[1].basicTrim(); //the 2nd date (buchungsdatum) of the first line is very likely to be the newest one ...
	amount = "";
	account = "Mastercard";
	
	return GENERATEQIFHEADENTRY(date, amount, account, "CCard");
}

function PROCESSLINE(line) {
	data = SPLITLINE(line);

	if (data.length == 0) {
		return "";
	}

	if (data.length != 9) {
		return "ERROR processing line:\n"+line+"\n\n"
	}
	
	date = data[1].basicTrim();
	amount = COMMAtoDOT(data[7]).basicTrim();
	memo = REMOVEQUOTES(data[2]).basicTrim();
	if (data[3].length > 0) {
		memo += " ["+data[3]+" "+COMMAtoDOT(data[4])+" (Wechselkurs: "+COMMAtoDOT(data[5])+"; Spesen: "+COMMAtoDOT(data[6])+")]"; 
	}
	memo = memo.basicTrim();
	category = data[8].basicTrim();
	
	return GENERATEQIFSPLITENTRY(date, amount, memo, category);
}

function PREPARETEXT(text) {
	matches = text.match(/"(.*?[\n\r]*?)*?"/g);
	if(matches) {
		for(i=0;i<matches.length;++i) {
			orig = matches[i];
			repl = orig;
			while (repl.search(/\n/) != -1) {
				repl = repl.replace(/\n/,'');
			}
			while (repl.search(/\r/) != -1) {
				repl = repl.replace(/\r/,'');
			}
			
		text = text.replace(orig, repl);
	 	}
	}
	 	
	return text;
}

function PROCESSTEXT(text) {
	text = PREPARETEXT(text);
	
	lines = text.split("\n");
	
	qif = "";
	
	//generate gif header info
	qif = PROCESSFIRSTLINE(lines[1]);
	
	//process all other lines
	for (i=1; i<lines.length; i++) { //first line contains the header -> index 0 skipped
		if (lines[i].length > 0) {
			qif+= PROCESSLINE(lines[i]);
		}
	}
	
	return qif;
}


