/**
 * %%INFO 2008-09-26 14:06:36+0200 rgarcia%%
 * @author Rubén García
 * @usage InputWidgetMsisdn(String elementName, Object options)
 * @example
 * <script type="text/javascript">
 * // <![CDATA[
 * var iW1 = new InputWidgetMsisdn('msisdn');
 * var iW2 = new InputWidgetMsisdn('msisdn2', {fixed:true, showCarrierName: true, selectFirstEntry: 'Choose'});
 * // ]]>
 * </script>
 */

//Needed methods for string manipulation
if(typeof 'x'.startsWith != 'function'){
	String.prototype.startsWith=function(pattern){return this.indexOf(pattern)===0;}
}
if(typeof 'x'.purge != 'function'){
	String.prototype.purge=function(){ return this.replace(/[^0-9]/, ''); }
}
if(typeof 'x'.isNumeric != 'function'){
	String.prototype.isNumeric=function(){
		//if(this.length == 0) return false;
		var ValidChars="0123456789";
		var IsNumber=true;
		var Char;
		for(i=0;i<this.length&&IsNumber==true;i++){
			tmp=this.charAt(i);
			if(ValidChars.indexOf(tmp)==-1){IsNumber=false;}
		}
		return IsNumber;
	}
}

InputWidgetMsisdn = Class.create();

InputWidgetMsisdn.prototype= {
	initialize: function(element, options){
		this.input = $(element);
		if(!this.input) return;
		this.options = Object.extend({
			showCarrierName:   false,
			sortPrefixes:      true,
			fixed:             false,
			purgeNumber:       true,
			changeEvent:       'keyup',
			selectChangeEvent: 'change',
			selectName:        element + 'mSelect',
			selectFirstEntry:  'Wähle',
			msisdnInputName:   element + 'mNumber',
			msisdnHint:        'msisdnhint'
		}, options || {});
		this.inputName = element;
		this.enhanced = false;

		this.writeBackListener  = this.writeBack.bindAsEventListener(this);
		this.checkListener = this.checkMsisdn.bindAsEventListener(this);

		if(this.options.fixed) {
			this.enhanceMsisdn();
		}

		this.input.observe(this.options.changeEvent, this.checkListener);
	},
	destroy: function() {
		this.input.stopObserving(this.options.changeEvent, this.checkListener);
		$(this.options.selectName).stopObserving(this.options.selectChangeEvent, this.writeBackListener);
		$(this.options.msisdnInputName).stopObserving(this.options.changeEvent, this.writeBackListener);
		$(this.options.msisdnInputName).stopObserving(this.options.changeEvent, this.checkListener);
	},
	enhanceMsisdn: function(){
		this.input.stopObserving(this.options.changeEvent, this.checkListener);
		this.input.hide();
		if($(this.options.msisdnHint)) $(this.options.msisdnHint).hide();
		var mChoice = $(this.options.selectName);
		if(!mChoice) {
			mChoice = this.createPrefixSelect();
			this.input.up().insertBefore(mChoice,this.input)
		} else {
			mChoice.show();
		}
		var mNumber = $(this.options.msisdnInputName);
		if(!mNumber) {
			mNumber = this.createMsisdnInput();
			this.input.up().insertBefore(mNumber,this.input)
		} else {
			mNumber.show();
		}
		if(this.input.value != '') {
			this.showNormalizedMsisdn()
		}
		if(this.options.sortPrefixes) {
			this.sortPrefixSelect();
		}
		if(!this.options.fixed) {
			$(mNumber).focus();
			$(mNumber).value = $(mNumber).value; // fix for ie cursor positioning
		}
		$(mNumber).observe(this.options.changeEvent, this.checkListener);
		$(mNumber).observe(this.options.changeEvent, this.writeBackListener);
		$(mChoice).observe(this.options.selectChangeEvent, this.writeBackListener);
	},
	simplifyMsisdn: function(){
		if($(this.options.selectName)) {
			this.input.value = $(this.options.msisdnInputName).value;
			this.input.show();
			$(this.options.selectName).stopObserving(this.options.selectChangeEvent, this.writeBackListener);
			$(this.options.msisdnInputName).stopObserving(this.options.changeEvent, this.writeBackListener);
			$(this.options.msisdnInputName).stopObserving(this.options.changeEvent, this.checkListener);
			$(this.options.selectName).hide();
			$(this.options.selectName).selectedIndex = 0
			$(this.options.msisdnInputName).hide();
	  		this.input.focus();
	  		this.input.value = this.input.value; // fix for ie cursor positioning
			this.input.observe(this.options.changeEvent, this.checkListener);
		}
	},
	checkMsisdn: function(){
		this.input.value = this.input.value.replace('+', '00');
		if(this.options.fixed || this.input.value.isNumeric()){
			if(!this.enhanced) {
				this.enhanced = true;
				this.enhanceMsisdn();
			}
		} else {
			if(this.enhanced) {
				this.enhanced = false;
				this.simplifyMsisdn();
			}
		}
	},
	createPrefixSelect: function() {
		var select = document.createElement('select');
		select.setAttribute('id', this.options.selectName);
		select.setAttribute('name','prefix');
		var d = document.createElement('option');
		d.setAttribute('value', '');
		d.appendChild(document.createTextNode(this.options.selectFirstEntry));
		select.appendChild(d);
		for(var x in this.choices) {
			d = document.createElement('optgroup');
			d.setAttribute('label', this.choices[x].name);
			for(var y in this.choices[x].providers) {
				for(var z = 0; z < this.choices[x].providers[y].prefixes.length; z++) {
					var e = document.createElement('option');
					e.setAttribute('id', this.inputName + this.choices[x].country + this.choices[x].mobPrefix.substr(1) + this.choices[x].providers[y].prefixes[z]);
					e.setAttribute('value', this.choices[x].prefix + this.choices[x].mobPrefix.substr(1) + this.choices[x].providers[y].prefixes[z]);
					var label = '';
					if(this.options.showCarrierName) {
						label += this.choices[x].providers[y].name + ': ';
					}
					label += this.choices[x].mobPrefix + this.choices[x].providers[y].prefixes[z];
					e.appendChild(document.createTextNode(label));
					d.appendChild(e);
				}
			}
			select.appendChild(d);
		}
		return select;
	},
	sortPrefixSelect: function() {
		var list = $$('#'+ this.options.selectName + ' optgroup');
		var lists = {};
		var sorted = [];
		var j = 0;
		var selected = '';
		for(var sList in list) {
			if(typeof list[sList] == 'object' && typeof list[sList] != 'undefined') {
				sorted[j] = [];
				var i = 0;
				for(var o in list[sList].childNodes) {
if(!isNaN(o)) {
					if(typeof list[sList].childNodes[o] == 'object' && typeof list[sList].childNodes[o] != 'undefined') {
						if(list[sList].childNodes[o].selected) {
							selected = list[sList].childNodes[o].id;
						}
						lists[list[sList].childNodes[o].id] = {val: '', text: ''};
						lists[list[sList].childNodes[o].id].val = list[sList].childNodes[o].value;
						lists[list[sList].childNodes[o].id].text = list[sList].childNodes[o].childNodes[0].nodeValue;
						sorted[j][i++] = list[sList].childNodes[o].id;
					}
}
				}
				j++;
			}
		}
		for(l in sorted) {
			if(typeof sorted[l] == 'object' && typeof sorted[l] != 'undefined') {
				sorted[l].sort();
				for(i=0; i<sorted[l].length; i++) {
					list[l].childNodes[i].childNodes[0].nodeValue = lists[sorted[l][i]].text;
					list[l].childNodes[i].value = lists[sorted[l][i]].val;
					list[l].childNodes[i].id = sorted[l][i];
					if(selected == list[l].childNodes[i].id) {
						list[l].childNodes[i].selected = 'selected';
					}
				}
			}
		}
	},
	createMsisdnInput: function() {
		var mNumber = document.createElement('input');
		mNumber.setAttribute('id', this.options.msisdnInputName);
		mNumber.setAttribute('name', 'number');
		return mNumber;
	},
	normalizeMsisdn: function(prefix, number) {
		if(number.startsWith('00')) {
			for(var x in this.choices) {
				if(number.startsWith(this.choices[x].prefix) && number.substr(this.choices[x].prefix.length).length > 8) {
					number = '0' + number.substr(this.choices[x].prefix.length);
				}
			}
		}
		if(number.startsWith('0')) {
			for(var x in this.choices) {
				for(var y in this.choices[x].providers) {
					for(var z = 0; z < this.choices[x].providers[y].prefixes.length; z++) {
						if(number.startsWith(this.choices[x].mobPrefix + this.choices[x].providers[y].prefixes[z])) {
							number = number.substr(this.choices[x].mobPrefix.length + this.choices[x].providers[y].prefixes[z].length);
							$(this.inputName + this.choices[x].country + this.choices[x].mobPrefix.substr(1) + this.choices[x].providers[y].prefixes[z]).selected = 'selected';

						}
					}
				}
			}
		}
		return prefix + number;
	},
	showNormalizedMsisdn: function() {
		var norm = this.input.value;
		$(this.options.msisdnInputName).value = norm;
		for(var x in this.choices) {
			for(var y in this.choices[x].providers) {
				for(var z = 0; z < this.choices[x].providers[y].prefixes.length; z++) {
					if(norm.startsWith(this.choices[x].prefix + this.choices[x].mobPrefix.substr(1) + this.choices[x].providers[y].prefixes[z])) {
						$(this.inputName + this.choices[x].country + this.choices[x].mobPrefix.substr(1) + this.choices[x].providers[y].prefixes[z]).selected = 'selected';
						$(this.options.msisdnInputName).value = norm.substr(this.choices[x].prefix.length + this.choices[x].mobPrefix.substr(1).length + this.choices[x].providers[y].prefixes[z].length);
						return;
					}
				}
			}
		}
	},
	writeBack: function() {
		var prefix = $(this.options.selectName).value;
		var number = $(this.options.msisdnInputName).value;
		if(this.options.purgeNumber) { number = number.purge(); }
		this.input.value = this.normalizeMsisdn(prefix, number);
		this.showNormalizedMsisdn();
	},
	choices:{
		germany:{
			country:'de',prefix:'0049',mobPrefix:'01',name:'Deutschland',
			providers:{
				d1:{name:'T-Mobile D1',prefixes:['51','60','70','71','75']},
				d2:{name:'Vodafone D2',prefixes:['52','62','72','73','74']},
				ep:{name:'e-plus',prefixes:['55','57','63','77','78']},
				o2:{name:'O2',prefixes:['59','76','79']},
				mc:{name:'mobilcom',prefixes:['56']},
				qu:{name:'Quam',prefixes:['50']}
			}
		},
		austria:{
			country:'at', prefix:'0043', mobPrefix:'06', name:'Österreich',
			providers:{
				x:{name:'3',prefixes:['60']},
				a1:{name:'Mobilkom Austria(A1)',prefixes:['64']},
				d1:{name:'T-Mobile Austria',prefixes:['76']},
				one:{name:'One',prefixes:['99']},
				tr:{name:'Telering',prefixes:['50']},
				bob:{name:'Bob',prefixes:['80']},
				y:{name:'Yesss',prefixes:['81','998']},
				ee:{name:'Eety',prefixes:['8183']},
				t2:{name:'Tele2',prefixes:['88']},
				et:{name:'eTel',prefixes:['991599']}
			}
		},
		switzerland:{
			country:'ch',prefix:'0041',mobPrefix:'07',name:'Schweiz',
			providers:{
				sunrise:{name:'Sunrise',prefixes:['6']},
				tele2:{name:'Tele2',prefixes:['7']},
				orange:{name:'Orange',prefixes:['8']},
				sc:{name:'Swisscom Mobile',prefixes:['9']}
			}
		}
	}
}