var tagesgeld = {
	input_amount: null,
	input_period: null,
	
	info_container: null,
	
	slider_amounts_container: null,
	slider_amounts_areas: ['geringe Einlage', 'mittlere Einlage', 'hohe Einlage'],
	slider_amounts: null,
	slider_periods_container: null,
	slider_periods_areas: ['geringe Laufzeit', 'mittlere Laufzeit', 'hohe Laufzeit'],
	slider_periods: null,
	
	amount: 0,
	period: 0,
	
	former: {
		amount: 0,
		period: 0,
		special: ''
	},
	
	sort: {
		row: 'zinsen',
		direction: 'desc'
	},
	
	amount_range: [1],
	amount_range_fmt: [],
	periods_range: 36,
	
	waiting_timer: null,
	
	init_ready: false,
	isIE6: false,
	
	results: [],

	init: function() {
	  tagesgeld.input_amount = new Element('input',{type:'text',name:'tagesgeld_amount'}).addClassName('textfield euro');
	  tagesgeld.input_period = new Element('input',{type:'text',name:'tagesgeld_period',style:'text-align: right;'}).addClassName('textfield');
	  tagesgeld.slider_amounts_container = new Element('div');
	  tagesgeld.slider_periods_container = new Element('div');
	  
	  tagesgeld.info_container = new Element('div',{id:'tagesgeld_info', style:'display:none;'}).insert(
	    new Element('div').addClassName('info_pos').insert(
				new Element('div').addClassName('info_border')
			).insert(
				new Element('div').addClassName('info_content')
			)
		);
		$(document.body).insert(tagesgeld.info_container);
	  tagesgeld.isIE6 = tagesgeld.info_container.getStyle('position') == 'absolute';

		$('tagesgeld_container').update().insert(
			new Element('table',{border:0,cellpadding:0,cellspacing:0,width:'100%'}).insert(
        new Element('tbody').insert(
          new Element('tr').insert(
            new Element('td').insert(tagesgeld.input_amount)
					).insert(
            new Element('td',{width:'90%',style:'padding-left: 8px;'}).insert(tagesgeld.slider_amounts_container)
					)
				).insert(
          new Element('tr').insert(
            new Element('td').insert(tagesgeld.input_period)
					).insert(
            new Element('td',{width:'90%',style:'padding-left: 8px;'}).insert(tagesgeld.slider_periods_container)
					)
				).insert(
          new Element('tr').insert(
            new Element('td').update('Aktionen:')
					).insert(
            new Element('td',{width:'90%',style:'padding-left: 8px;'}).insert(
              new Element('form',{method:'get',name:'special_form',id:'special_form',action:'#'}).insert(
								new Element('table',{border:0,cellpadding:0,cellspacing:0,width:'100%'}).insert(
					        new Element('tbody').insert(
					          new Element('tr').insert(
	                    new Element('td',{width:'3%'}).insert(
												new Element('input',{type:'radio',name:'special',value:'none',checked:tagesgeld_init_values.special=='none'?'checked':false}).observe('click', tagesgeld.submit)
											)
										).insert(
	                    new Element('td',{width:'12%'}).addClassName('radiolabel').update('&nbsp;ohne')
										).insert(
	                    new Element('td',{width:'3%'}).insert(
												new Element('input',{type:'radio',name:'special',value:'all',checked:tagesgeld_init_values.special=='all'?'checked':false}).observe('click', tagesgeld.submit)
											)
										).insert(
	                    new Element('td',{width:'12%'}).addClassName('radiolabel').update('&nbsp;alle')
										).insert(
	                    new Element('td',{width:'3%'}).insert(
												new Element('input',{type:'radio',name:'special',value:'Neukunden',checked:tagesgeld_init_values.special=='new_customer'?'checked':false}).observe('click', tagesgeld.submit)
											)
										).insert(
	                    new Element('td',{width:'32%'}).addClassName('radiolabel').update('&nbsp;für Neukunden')
										).insert(
	                    new Element('td',{width:'3%'}).insert(
												new Element('input',{type:'radio',name:'special',value:'Neues Geld',checked:tagesgeld_init_values.special=='new_money'?'checked':false}).observe('click', tagesgeld.submit)
											)
										).insert(
	                    new Element('td',{width:'32%'}).addClassName('radiolabel').update('&nbsp;für neues Geld')
										)
									)
								)
							).observe('submit',function(e){e.stop()})
						)
					)
				)
			)
		);
		
		$('tagesgeld_container').select('td.radiolabel').each(function(td){
			td.observe('click',function(e){
				var input = this.previous('td').down('input');
				input.checked = !input.checked;
				tagesgeld.submit();
			}.bindAsEventListener(td));
		});
		
		for (var i=50;i<=250000;) {
		  tagesgeld.amount_range.push(i);
			if (i<500) i+=50;
			else if (i<5000) i+=100;
			else if (i<10000) i+=500;
			else if (i<25000) i+=1000;
			else if (i<50000) i+=5000;
			else if (i<150000) i+=10000;
			else i+=20000;
		}
		
		tagesgeld.amount_range.each(function(amount){
      tagesgeld.amount_range_fmt.push(tagesgeld.fmt.amount(amount));
		});
		

		var table = new Element('table',{border:0,cellpadding:0,cellspacing:0,width:'100%',id:'slider_amounts'}).insert(
			new Element('tbody').insert(
				new Element('tr')
			).insert(
        new Element('tr').insert(
					new Element('td',{colspan:tagesgeld.slider_amounts_areas.length}).insert(
						new Element('div').addClassName('slider_container').insert(
              new Element('div').addClassName('slider')
						).insert(
              new Element('div').addClassName('slider_bar').insert(
                new Element('div').addClassName('slider_bar-rgt')
							)
						)
					)
				)
			)
		);
		var tr = table.down('tr');
		var width = Math.round(1/tagesgeld.slider_amounts_areas.length*100);
		tagesgeld.slider_amounts_areas.each(function(area){
      tr.insert(new Element('td',{style:'width: '+width+'%'}).addClassName('slider_desc').update(area));
		});
		tagesgeld.slider_amounts_container.insert(table);
		tagesgeld.slider_amounts = new Control.Slider(table.down('.slider'),table.down('.slider_bar'),{onChange:function(value){ tagesgeld.setAmount(value,'slide')},onSlide:function(value){tagesgeld.setAmount(value,'slide')}});
		
		tagesgeld.input_amount.observe('focus',function(){
			var input = $(this);
			input.setStyle({textAlign:'left'});
			input.value = input.value.gsub(/[^0-9]/,'');
			input.activate();
		}).observe('blur',function(){
			var input = $(this);
			input.setStyle({textAlign:'right'});
			tagesgeld.setAmount(input.value.gsub(/[^0-9]/,''));
		}).observe('keyup',function(e){
			if (e.keyCode==13)
			  window.setTimeout(function(){tagesgeld.input_period.focus()}, 5);
			var input = $(this);
			input.value = input.value.gsub(/[^0-9]/,'');
		});
		

		var table = new Element('table',{border:0,cellpadding:0,cellspacing:0,width:'100%',id:'slider_periods'}).insert(
			new Element('tbody').insert(
				new Element('tr')
			).insert(
        new Element('tr').insert(
					new Element('td',{colspan:tagesgeld.slider_periods_areas.length}).insert(
						new Element('div').addClassName('slider_container').insert(
              new Element('div').addClassName('slider')
						).insert(
              new Element('div').addClassName('slider_bar').insert(
                new Element('div').addClassName('slider_bar-rgt')
							)
						)
					)
				)
			)
		);
		var tr = table.down('tr');
		var width = Math.round(1/tagesgeld.slider_periods_areas.length*100);
		tagesgeld.slider_periods_areas.each(function(area){
      tr.insert(new Element('td',{style:'width: '+width+'%'}).addClassName('slider_desc').update(area));
		});
		tagesgeld.slider_periods_container.insert(table);
		tagesgeld.slider_periods = new Control.Slider(table.down('.slider'),table.down('.slider_bar'),{values:$R(1,tagesgeld.periods_range),range:$R(1,tagesgeld.periods_range),onChange:function(value){ tagesgeld.setPeriod(value,'slide')},onSlide:function(value){tagesgeld.setPeriod(value,'slide')}});

		tagesgeld.input_period.observe('focus',function(){
			var input = $(this);
			input.setStyle({textAlign:'left'});
			input.value = input.value.gsub(/[^0-9]/,'');
			input.activate();
		}).observe('blur',function(){
			var input = $(this);
			input.setStyle({textAlign:'right'});
			tagesgeld.setPeriod(input.value.gsub(/[^0-9]/,''));
		}).observe('keyup',function(e){
			if (e.keyCode==13)
			  window.setTimeout(function(){tagesgeld.input_amount.focus()}, 5);
			var input = $(this);
			input.value = input.value.gsub(/[^0-9]/,'');
		});
		
		tagesgeld.setAmount(tagesgeld_init_values.amount);
		tagesgeld.setPeriod(tagesgeld_init_values.period);
		
		
		var tbl =  new Element('tbody');
		$('tagesgeld_container').insert('<br /><br />').insert(
			new Element('div',{style:'position:relative'}).insert(
			  new Element('div').addClassName('customer_table').insert(
					new Element('table',{border:0,cellpadding:0,cellspacing:0,width:'100%'}).insert(tbl)
				)
			).insert(
				new Element('div',{style:'display:none'}).addClassName('customer_overlay')
			)
		);

		var span_bank = new Element('span').update('&nbsp;&nbsp;&nbsp;');
		if (tagesgeld.sort.row=='bank')
		  span_bank.addClassName(tagesgeld.sort.direction);

		var span_zinsen = new Element('span').update('&nbsp;&nbsp;&nbsp;');
		if (tagesgeld.sort.row=='zinsen')
		  span_zinsen.addClassName(tagesgeld.sort.direction);

		tbl.insert(
			new Element('tr',{id:'customer_table_header'}).insert(
				new Element('th').insert(
					new Element('a',{title:'Nach Name der Bank sortieren',id:'sort_bank'}).addClassName('sort-order').update('Bank&nbsp;&nbsp;').observe('click',tagesgeld.setSort.bindAsEventListener(tagesgeld,'bank')).insert(span_bank)
				)
			).insert(
				new Element('th',{colspan:3}).insert(
					new Element('a',{title:'Nach Höhe der Zinsen sortieren',id:'sort_zinsen'}).addClassName('sort-order').update('Zinsen&nbsp;&nbsp;').observe('click',tagesgeld.setSort.bindAsEventListener(tagesgeld,'zinsen')).insert(span_zinsen)
				)
			).insert(new Element('th',{colspan:3}))
		).insert(
			new Element('tr',{id:'customer_table_off'}).insert(
				new Element('td',{colspan:6,style:'font-size: 2px; line-height: 4px'}).update('&nbsp;')
			)
		);
		
    for (var slug in tagesgeld_init_values.customer) {
      var tr = new Element('tr',{id:'customer_'+slug}).insert(
				new Element('td',{id:'customer_'+slug+'_name'}).addClassName('customer_name').update(tagesgeld_init_values.customer[slug].name)
			).insert(
				new Element('td').addClassName('customers_bar').insert(
					new Element('div',{id:'customer_'+slug+'_bar'}).addClassName('bar-small-lft')
				).insert(
					new Element('div').addClassName('bar-small-rgt')
				).insert(
          new Element('div',{id:'customer_'+slug+'_info',style:'display:none'})
				)
			).insert(
				new Element('td',{id:'customer_'+slug+'_rate'}).addClassName('customers_rate')
			).insert(
				new Element('td',{id:'customer_'+slug+'_zins'}).addClassName('customers_zins')
			).insert(
				new Element('td').addClassName('customers_button').insert(
					tagesgeld_init_values.customer[slug].type == 'PP' ? new Element('div',{style:'background-image:url(/_site/images/tool_staffel.gif);',title:'Zinsstaffel'}).observe('click',function(e){self.location.href='/leistungsvergleich/tagesgeld/'+this}.bindAsEventListener(slug)) : ''
				)
			).insert(
				new Element('td').addClassName('customers_button').insert(
					new Element('div',{style:'background-image:url(/_site/images/tool_info.gif);',title:'zum Portrait'}).observe('click',function(e){self.location.href='/tagesgeld/'+this}.bindAsEventListener((tagesgeld_init_values.customer[slug].type!='PP'?'weitere-anbieter/':'')+slug))
				)
			).insert(
				new Element('td').addClassName('customers_button').insert(
					tagesgeld_init_values.customer[slug].open ? new Element('div',{style:'background-image:url(/_site/images/tool_go.png);',title:'Infos anfordern'}).observe('click',function(e){window.open(this)}.bindAsEventListener(tagesgeld_init_values.customer[slug].open)) : ''
				)
			);
			tbl.insert(tr);
			
			var tds = tr.select('td');
			for (var i=0,ln=tds.length;i<ln;i++) {
			  tds[i].observe('mouseover',function(e){
					this.up('tr').writeAttribute('class','highlight')
				}).observe('mouseout',function(e){
					this.up('tr').removeClassName('highlight')
				});
				if (i<4) {
				  tds[i].observe('mouseover',function(e,slug){
						var html = $('customer_'+slug+'_info').innerHTML;
						tagesgeld.info.show(e.clientX, e.clientY, html);
					}.bindAsEventListener(null,slug)).observe('mousemove',function(e){
						tagesgeld.info.show(e.clientX, e.clientY);
					}).observe('mouseout',function(e){
						tagesgeld.info.hide();
					});
				}
			}
		}
		
		tagesgeld.update(tagesgeld_init_values.results);
		
		window.setTimeout(function(){tagesgeld.init_ready = true}, 1000);
	},

  amountIgnoreSlide: false,
  setAmount: function(amount, src) {
    switch(src) {
			case 'slide':
		    if (tagesgeld.amountIgnoreSlide) {
		      tagesgeld.amountIgnoreSlide = false;
		      return;
				}
			  amount = tagesgeld.amount_range[Math.round(amount*100)];
			  tagesgeld.input_amount.value = tagesgeld.fmt.amount(amount);
			  tagesgeld.amount = amount;
			  break;
			default:
			  tagesgeld.input_amount.value = tagesgeld.fmt.amount(amount);
				tagesgeld.amount = amount;

        tagesgeld.amountIgnoreSlide = true;
				var tmp = tagesgeld.amount_range.sortBy(function(a){return a<amount?amount-a:a-amount;});
				tagesgeld.slider_amounts.setValue(tagesgeld.amount_range.indexOf(tmp[0])/100);
				
		}

		var tmp = tagesgeld.amount_range.sortBy(function(a){return a<amount?amount-a:a-amount;});
		var td_index = tagesgeld.amount_range.indexOf(tmp[0]);
		td_index = td_index >= 66 ? 2 : (td_index >= 33 ? 1 : 0);
		
  	var tr = $('slider_amounts').down('tr');
		if (tr.down('td.slider_highlight'))
			tr.down('td.slider_highlight').removeClassName('slider_highlight');
		tr.down('td', td_index).addClassName('slider_highlight');
		
		tagesgeld.submit();
	},

	periodIgnoreSlide: false,
  setPeriod: function(period, src) {
    switch(src) {
			case 'slide':
		    if (tagesgeld.periodIgnoreSlide) {
		      tagesgeld.periodIgnoreSlide = false;
		      return;
				}
			  tagesgeld.input_period.value = tagesgeld.fmt.period(period);
			  tagesgeld.period = period;
			  break;
			default:
			  tagesgeld.input_period.value = tagesgeld.fmt.period(period);
				tagesgeld.period = period;
				
				tagesgeld.periodIgnoreSlide = true;
			  tagesgeld.slider_periods.setValue(period);
		}

  	var tr = $('slider_periods').down('tr');
		if (tr.down('td.slider_highlight'))
			tr.down('td.slider_highlight').removeClassName('slider_highlight');
			
    var td_index = period/tagesgeld.periods_range*100;
    td_index = td_index >= 66 ? 2 : (td_index >= 33 ? 1 : 0);
		tr.down('td', td_index).addClassName('slider_highlight');

		tagesgeld.submit();
	},
	
	fmt: {
    period: function(iPeriod) {
			if (iPeriod == 1)
			  return '1 Monat';
			else
				return iPeriod+' Monate';
		},
		amount: function(iAmount) {
			var sAmount = iAmount.toString();
			var sAmountLen = sAmount.length;
			var iAmountMod = sAmountLen%3;
			var transits = Math.floor(sAmountLen/3);
			var result = sAmount.substr(0,iAmountMod);

			for (var i=0;i<transits;i++) {
		  	result += (i>0||iAmountMod>0?'.':'')+sAmount.substr(iAmountMod+(i*3),3);
			}
			return result+' €';
		}
	},

	info: {
		hide: function() {
      tagesgeld.info_container.hide();
		},
		show: function(x,y,html) {
		  if (tagesgeld.isIE6) {
				var ie_height = document.viewport.getDimensions().height;
				y = ie_height-(ie_height-y);
			}
      tagesgeld.info_container.show().setStyle({top:y+'px',left:x+'px'});
      if (html)
      	tagesgeld.info_container.down('.info_border').setStyle({height:tagesgeld.info_container.down('.info_content').update(html).getDimensions().height+'px'});
		}
	},
	
	overlay: {
		hide: function() {
			$('tagesgeld_container').down('.customer_overlay').hide();
		},
		show: function() {
		  var dim = $('tagesgeld_container').down('.customer_table').getDimensions();
      $('tagesgeld_container').down('.customer_overlay').setStyle({width:dim.width+'px',height:dim.height+'px'}).show();
		}
	},
	
	submit: function() {
		window.clearTimeout(tagesgeld.waiting_timer);
		tagesgeld.waiting_timer = window.setTimeout(tagesgeld.startRequest, 300);
	},
	startRequest: function() {
	  if (tagesgeld.init_ready) {
	    var post = {
				amount: tagesgeld.amount,
				period: tagesgeld.period,
				special: $('special_form').serialize(true).special
			};

	    if (tagesgeld.former != post) {
		    tagesgeld.overlay.show();
		    hlp.xhr('tool_zinsen_tagesgeld:renderJson',post,{onSuccess:function(t){tagesgeld.update(t.responseText.evalJSON())}});
		    tagesgeld.former.amount = tagesgeld.amount;
		    tagesgeld.former.period = tagesgeld.period;
			}
		}
	},
	
	update: function(o) {
		if (o.debug)
		  $('debug').innerHTML = o.debug;
	  tagesgeld.results = [];
		for (var slug in o) {
		  if (slug == 'debug') continue;
			$('customer_'+slug+'_rate').update(o[slug].rate>0?o[slug].rateHtml:'');
			$('customer_'+slug+'_zins').update(o[slug].rate>0?o[slug].zinsHtml:'');
			$('customer_'+slug+'_info').update().insert(o[slug].html);
			$('customer_'+slug+'_bar').morph('width:'+o[slug].bar+'px');
			tagesgeld.results.push({slug:slug,rate:o[slug].rate});
		}
		tagesgeld.setSort();
		tagesgeld.overlay.hide();
	},
	
	setSort: function(e, row) {
	  if (row) {
		  if (row == tagesgeld.sort.row) {
				if (tagesgeld.sort.direction == 'asc') {
	        tagesgeld.sort.direction = 'desc';
	        $('sort_'+row).down('span').writeAttribute('class','desc');
				} else {
	        tagesgeld.sort.direction = 'asc';
					$('sort_'+row).down('span').writeAttribute('class','asc');
				}
			} else {
	      $('sort_'+tagesgeld.sort.row).down('span').writeAttribute('class','');
	      tagesgeld.sort.row = row;
	      tagesgeld.sort.direction = 'asc';
	      $('sort_'+row).down('span').writeAttribute('class','asc');
			}
		}


		if (tagesgeld.sort.row == 'bank') {
		  var order = tagesgeld.results.sortBy(function(o){return o.slug});
		  if (tagesgeld.sort.direction == 'asc')
		    order.reverse();
		} else if (tagesgeld.sort.row == 'zinsen') {
		  var order = tagesgeld.results.sortBy(function(o){return o.rate});
		  if (tagesgeld.sort.direction == 'asc')
		    order.reverse();
		}

		var th = $('customer_table_header');
		var off = [];
  	for (var i=0,ln=order.length;i<ln;i++) {
  	  if (order[i].rate!=0)
				th.insert({after:$('customer_'+order[i].slug)});
			else off.push(order[i])
  	}

  	if (off.length > 0) {
			off = off.sortBy(function(o){return o.slug}).reverse();
      th = $('customer_table_off');
      for (var i=0,ln=off.length;i<ln;i++)
      	th.insert({after:$('customer_'+off[i].slug)});
		}
	}
};

FastInit.addOnLoad(tagesgeld.init);
//Event.observe(window,'load',tagesgeld.init);

var hlp = {
	xhr: function(mm, params, options) {
	  var m = mm.split(':');
		return new Ajax.Request('/ajax.php?module='+m[0]+'&method='+m[1]+'&id=&params=', Object.extend({
			method: 'post',
			parameters: params
		},options||{}));
	}
};
