/*
   Datei: string.js
   Autor: Struppi struebig@gmx.net
   Datum: 13:09 20.01.2010
   
   String.prototpye Erweiterungen:
   
   .toDate() 		wandelt in ein Date Objekt um. Es wird das deutsche Format TT.MM.YYYY HH::MM::SS geprüft
   .rtrim()/.ltrim()/.trim() Leerzeichen löschen
   .stripNL() 		entfernt alle Newline Zeichen
   .HTMLentinities() alle Zeichen > 128 in HTML Entinities umwandeln
   .stripTags()		alle HTML Tags entfernen (rudimentär)
   .camlize()		entfernt - oder _ und wandelt den Nachfolgenden Buichstaben in ein Großen um
   .format()		Zeichenkette formatieren
   .stringIn()		Zeichen zwischen zwei finden
   .change()		ersetzen von-bis
   .x()				String wiederholen
   .isalnum()		Test auf whitespace
   
*/

/* Konstanten für String.format(); */
var CENTER = 'CENTER';
var LEFT = 'LEFT';
var RIGHT = 'RIGHT';

///////////////////////////////////////////////////////////
//
// String.toDate()
//
// string => TT.MM.YYYY HH:MM:SS
//
// prüft einen String auf ein gültiges Datum
// gibt ein Datum Objekt oder null zurück
// Das Trennzeichen im Datum kann auch ein '/' oder '-' sein

String.prototype.toDate = function() {
	// 1. Trennzeichen normalisieren
	// 2. ungültige Zeichen entfernen
	// 3. doppelte Leerzeichen entfernen
	var string = 
	this.replace(/[-\/]/g, '.').replace(/[^0-9.: ]/g, '').replace(/ +/g, ' ') ;
	var parts = string.split(" "); // Uhrzeit abtrennen
	var split = parts[0].split(".");
	var day = parseInt(split[0], 10);
	var month = parseInt(split[1] || 0, 10);
	var year = parseInt(split[2] || 0, 10);
	
	if(isNaN(year)) year = (new Date()).getFullYear();
	
	var check = new Date(year, month - 1, day);
	
	if(parts[1]) { // wurde eine Uhrzeit angegeben
		var uhr = uhr[1].split(':');
		check.setHours(uhr[0] || 0);
		check.setMinutes(uhr[1] || 0);
		check.setSeconds(uhr[2] || 0);
	}
	// überprüfen ob das Datum gleich dem berechnetem Dateum ist
	return (check.getFullYear() == year && 
	month == (check.getMonth() + 1) && 
	day == check.getDate()) ? 
	check
	: null;
};


String.prototype.trim = function (ws) {
    if(!this.length) return "";
    var tmp = this.ltrim().rtrim();
    return ws ? tmp.replace(/ +/g, ' ') : tmp;
};
String.prototype.rtrim = function () {
    return this.length ? this.replace(/\s+$/g, '') : "";
},
String.prototype.ltrim = function () {
    return this.length ? this.replace(/^\s+/g, '') : '';
};

String.prototype.stripNL = function () {
    return this.length ? this.replace(/[\n\r]/g, '') : '';
};
String.prototype.NL2Br = function () {
    return this.length ? this.replace(/[\n\r]/g, '<br>') : '';
};
String.prototype.camelize = function() {
	return this.replace( /[-_]([a-z])/ig, function(z,b){ return b.toUpperCase()} );
};

////////////////////////////////////////////////////////////////////////
// String.format(width [, char , align])
// returns a string with a fixed length,
// filled with char (default = " ")
// align = CENTER, LEFT, RIGHT
String.prototype.format = function(width, c , align) {
   if(!this.length || !width || width < 0) return '';
   var len = this.length ;
   if(width < len) return this.substr(0, width);
   if(!c) c = " ";
   if(!align) align = LEFT;
   
   var fill = c.x(width - len);

   var start = align === LEFT ? fill.length :
   align === CENTER ? fill.length - (width - len   -1) / 2 : 0;

   return (fill + this + fill).substr(start, width);
};

////////////////////////////////////////////////////////////////////////
// String.stringIn(string1, string1 [, case])
// returns the string which is between two others inside String
// case(bool) 
String.prototype.stringIn = function (t1, t2, noCase){
    if(!this.length) return '';
    
	var tmp = this;
    if(noCase) {
		tmp = tmp.toLowerCase();
		t1 = t1.toLowerCase();
		t2 = t2.toLowerCase();
    }

    var x1 = tmp.indexOf(t1);
    if ( x1 == -1) return '';

    var x2 = tmp.length;
    if(t2) {
		x2 = tmp.indexOf(t2, x1);
		if( x2 == -1) return '';
    }
    return tmp.substring(x1 + t1.length, x2);
};
/*
String.change(from, to, str)
ersetzt die Zeichenkette ab der Position from bis to mit str.
*/
String.prototype.change = function(from, to, str) {
	if(typeof from != 'number' || !from) return this;
	if(from > this.length) return this + str;
	if(typeof to == 'number' && to < from) return this;
	return this.substr(0, from) + str + this.substr(from + to);
};
/*
	String.HTMLentities()
	ersetzt die Zeichen > 128 
*/
String.prototype.HTMLentities = function() {
	var txt = this.replace(/&/g,"&amp;");
	var new_text = '';
	for(var i = 0; i < txt.length; i++) {
		var c = txt.charCodeAt(i);
		if(c < 128) {
			new_text += String.fromCharCode(c);
		}else {
			new_text += '&#' + c +';';
		}
	}
	return new_text.replace(/</g,"&lt;").replace(/>/g,"&gt;");
}

String.prototype.stripTags =  function(){
	// remove all string within tags
	var tmp = this.replace(/(<.*['"])([^'"]*)(['"]>)/g, function(x, p1, p2, p3) { 
	return  p1 + p3;
	});
	// now remove the tags
	return tmp.replace(/<\/?[^>]+>/gi, '');
};

String.prototype.x = function(num) {
	if(!num || num < 0) return '';
	var tmp = this;
	while(--num) { tmp += this; };
	return tmp;
};
String.prototype.isalnum = function() {
	return !this.match(/[^\w\-]/);
}
