$(document).ready(function() {

  // Widget auf BK-Mandant setzen
  if($('form.tariff-calculator input#mandant')) {
    if($('form.tariff-calculator input#mandant').val() == "re")
        $('form.tariff-calculator input#mandant').val('bk');
    else if($('form.tariff-calculator input#mandant').val() == "regw")
        $('form.tariff-calculator input#mandant').val('bkgw');
  }
    
    
  if($('div.privateflash').length){
  

    //swfobject.embedSWF("/tarifberater/media/flash/rheinenergie-privatkunden.swf", "widgetflash", "394", "244", "9.0.0","","",params,params);
    
    var flashvars = {};
    flashvars.clickTAG = "/de/privatkundenportal/heimvorteil/heimvorteil_1.php"; 
    var params = {
      wmode: "opaque"
    }; 
    var attributes = {};

    swfobject.embedSWF("/media/resourcen/flash/belkaw-privatkunden.swf", "widgetflash", "394", "244", "9.0.0",false,flashvars,params,attributes);
    
  }
  
  if($('div.kmuflash').length){
  
    var params = {
      wmode: "opaque"
    }; 
    swfobject.embedSWF("/media/resourcen/flash/belkaw-gewerbekunden.swf", "widgetflash", "394", "244", "9.0.0","","",params,params);
  }

	$("form.tariff").each( function() {
		tariff = $(this).find('input[name="tariff"]').val();
		updateOptions($(this), tariff+"+");
	});
	
	
  $("div.calculate-container  h3.gas").click(function(){
    if($(this).find("#usage_gas").val != "") {
       resetGas();
       isAvailableZip(parseInt($("input[name='tariff-calculator-zip']").val()));
    }   
  });
  
  if($('.carousel').length) {
  $(function() {
	    $(".carousel").jCarouselLite({
	        btnNext: ".next",
	        btnPrev: ".prev",
	        visible: 2
	    });
	});
	}
  
    $("div.calculate-container  h3.power").click(function(){
    if($(this).find("#usage_power").val != "") {
       resetPower();
       isAvailableZip(parseInt($("input[name='tariff-calculator-zip']").val()));
    }   
  });      

  function checkInputBox(inputBox, override,slidertype) {
    var value = inputBox.val();
    if ((value != inputBox.lastValue) || (override)) {   
      inputBox.lastValue = value;
      slidertype.slider("value", value.replace(/\./, ''));
      if($("#tariff-calculator-zip").val().length == 5 && !isNaN(parseInt($("#tariff-calculator-zip").val()))) {
        isAvailableZip(parseInt($("#tariff-calculator-zip").val()));
      }
    }
  }   
  function  timeredZIPcheck(element,slidertype){
      inputBox = element;
      var timerWait = 500;
      var overrideBool = false;
      var energy; 
      var timerCallback = function() {
        checkInputBox(inputBox, overrideBool,slidertype);
      }
      clearTimeout(energy);
      energy = setTimeout(timerCallback, timerWait);

      return false;
  }

	/* Slider Startwidget */
	if($('.tariff-calculator.private-customer #usage_gas').length)
	{
		gasslider = $('<div id="gas_slider"></div>').insertAfter($('#usage_gas')).slider({
			min: 0,
			max: 50000,
			step: 100,
			range: 'min',			
			slide: function(event, ui) {				
				$('#usage_gas').val(formatNumber(ui.value));				
				updateGasEstimate();
			},
			stop: function(event, ui) {
				ui.handle.blur();
				if($("#tariff-calculator-zip").val().length == 5 && !isNaN(parseInt($("#tariff-calculator-zip").val()))) {
					isAvailableZip(parseInt($("#tariff-calculator-zip").val()));								
				}
				if(ui.value == 0)
				{					
					$('#usage_gas').closest('.calculate-container').removeClass('selected');
				}
			}
		});
		       
		$('#usage_gas').change( function () {
			gasslider.slider("value", $(this).val().replace(/\./, ''));
		});
		$('#usage_gas').keyup(function() {
        timeredZIPcheck($(this),gasslider);
        return false;
    });	
	}
	
	if($('.tariff-calculator.private-customer #usage_power').length)
	{
		powerslider = $('<div id="power_slider"></div>').insertAfter($('#usage_power')).slider({
			range: 'min',
			min: 0,
			max: 10000,
			step: 100,			
			slide: function(event, ui) {
				$('#usage_power').val(formatNumber(ui.value));
				updatePowerEstimate();
				
			},
			stop: function(event, ui) {
				ui.handle.blur();
				if($("#tariff-calculator-zip").val().length == 5 && !isNaN(parseInt($("#tariff-calculator-zip").val()))) {
					isAvailableZip(parseInt($("#tariff-calculator-zip").val()));								
				}
				if(ui.value == 0)
				{
					$('#usage_power').closest('.calculate-container').removeClass('selected');
				}
			}
		});
		$('#usage_power').change( function () {			
			powerslider.slider("value", $(this).val().replace(/\./, ''));
		});
		$('#usage_power').keyup(function() {
        timeredZIPcheck($(this),powerslider);
        return false;
    });
	}
	
	if($('.tariff-calculator.commercial-customer #usage_gas').length)
	{
		gasslider = $('<div id="gas_slider"></div>').insertAfter($('#usage_gas')).slider({
			min: 0,
			max: 120000,
			step: 1000,
			range: 'min',			
			slide: function(event, ui) {				
				$('#usage_gas').val(formatNumber(ui.value));				
				updateGasEstimate();
			},
			stop: function(event, ui) {
				ui.handle.blur();
				if($("#tariff-calculator-zip").val().length == 5 && !isNaN(parseInt($("#tariff-calculator-zip").val()))) {
					isAvailableZip(parseInt($("#tariff-calculator-zip").val()));								
				}
				if(ui.value == 0)
				{					
					$('#usage_gas').closest('.calculate-container').removeClass('selected');
				}
			}
		});    
		$('#usage_gas').change( function () {
			gasslider.slider("value", $(this).val().replace(/\./, ''));
		});
		$('#usage_gas').keyup(function() {
        timeredZIPcheck($(this),gasslider);
        return false;
    });	
	}
	
	if($('.tariff-calculator.commercial-customer #usage_power').length)
	{
		powerslider = $('<div id="power_slider"></div>').insertAfter($('#usage_power')).slider({
			range: 'min',
			min: 0,
			max: 120000,
			step: 1000,			
			slide: function(event, ui) {
				$('#usage_power').val(formatNumber(ui.value));
				updatePowerEstimate();
				
			},
			stop: function(event, ui) {
				ui.handle.blur();
				if($("#tariff-calculator-zip").val().length == 5 && !isNaN(parseInt($("#tariff-calculator-zip").val()))) {
					isAvailableZip(parseInt($("#tariff-calculator-zip").val()));								
				}
				if(ui.value == 0)
				{
					$('#usage_power').closest('.calculate-container').removeClass('selected');
				}
			}
		});
		$('#usage_power').change( function () {			
			powerslider.slider("value", $(this).val().replace(/\./, ''));
		});
		$('#usage_power').keyup(function() {
        timeredZIPcheck($(this),powerslider);
        return false;
    });
	}
	
	/* Verbrauchseingaben Startwidget */
	if($(".tariff-calculator .usage").length)
	{
		$(".tariff-calculator .usage").focus( function () {     
			$(this).attr('value', '');			
		});
		
	
	  
		$(".tariff-calculator .usage").keyup( function () {			      		
			var v = formatNumber($(this).val());
			if(v == '' || v == 0) {
				$(this).closest('.calculate-container').removeClass('selected');
				$(this).val('0');				
			}
			else {
				$(this).closest('.calculate-container').addClass('selected');				
			}
			updateUsages();
		});
	}
	
	/* Postleitzahlen-Eingabe Startwidget */
	if($("#tariff-calculator-zip").length)
	{
		$('.tariff-calculator button').attr('disabled','disabled');
		$("#tariff-calculator-zip").focus( function () {
			$(this).attr('value', '');
			$(this).closest('.city-select').find('button').addClass('disabled');			
		});
		
		$("#tariff-calculator-zip").bind('keyup', function () {			
			if($(this).val().length == 5 && !isNaN(parseInt($(this).val()))) {				
				isAvailableZip(parseInt($(this).val()));								
			}			
		});
		/*
		$("#tariff-calculator-zip").bind('change', function () {
		  //workaround, da beim focus der Verbrausfelder das Feld geleert wird und isavailablezip auf leere Vebräucheprüft, change-event also nur, wenn beide Vebräuche gesetzt
      if($("#usage_gas") != "" && $("#usage_power") != ""){			
  			if($(this).val().length == 5 && !isNaN(parseInt($(this).val()))) {				
  				isAvailableZip(parseInt($(this).val()));								
  			}
      }			
		});
		*/
	}

function resetGas(){   
      var calctype=$("#usage_gas").closest('.calculate-container');   
      $("#usage_gas").val("");	
      calctype.removeClass('selected'); 	
      calctype.children(".square_meter-select").empty();
			calctype.children(".square_meter-select").append('<span class="unit">Fläche <b>0</b> m²</span><span>kWh/Jahr</span>');
			for(var i=1; i<=6; i++ ){
				calctype.children(".square_meter-select").removeClass('show_'+i);
			}	 
			gasslider.slider("value", 0);
		
			
}
function resetPower(){   
      var calctype=$("#usage_power").closest('.calculate-container');
      $("#usage_power").val("");	
      calctype.removeClass('selected');
      calctype.children(".human-select").empty();
			calctype.children(".human-select").append('<span class="unit"><b>0</b> Personen</span><span>kWh/Jahr</span>');
			for(var i=1; i<=6; i++ ){
				calctype.children(".human-select").removeClass('show_'+i);
			}			
			powerslider.slider("value", 0);
      
}

function isAvailableZip(zipcode) {

  if($('#marginalwidget').length < 1) {		
		$('.tariff-calculator h2').ajaxStart(function() {
			$(this).css('background','url("/tarifberater/media/bilder/tarifberater/loadingani.gif") no-repeat scroll 500px center white');
		});
  }
       	
	$.ajax({
        type: "GET",
        url: "/tarifberater/belkaw/tarifberater/xml/zipcodes_belkaw.xml",
        dataType: "xml",
        success: function(xml) {

		   $(".tariff-calculator .zipcodeoutput").remove();
		   $('.tariff-calculator button').addClass('disabled');
		   $('.tariff-calculator button').attr('disabled','disabled');
		   var powerstring = "<div class='zipcodeoutput'><h4>" + $(xml).find('content > textnodes > strom > [type="none"] > head').text() + "</h4><p>" + $(xml).find('content > textnodes > strom > [type="none"] > desc').text() + "</p></div>";
		   var gasstring = "<div class='zipcodeoutput'><h4>" + $(xml).find('content > textnodes > gas > [type="none"] > head').text() + "</h4><p>" + $(xml).find('content > textnodes > gas > [type="none"] > desc').text() + "</p></div>";
		   var gasproviderfound = false;
		   var powerproviderfound = false;
          /*
         if($("#usage_power").val() == '' || $("#usage_power").val() == 0){
          var powerstring = "";
         }
         if($("#usage_gas").val() == '' || $("#usage_gas").val() == 0){
          var gasstring = "";
         }
         
         if(powerstring == "" && gasstring == ""){
          return false;
         }
          */
                         	
        /* Prüfung auf Strom bei BELKAW*/
        if(powerproviderfound == false){
          $(xml).find('content > zipcodes > strom > belkaw > zip').each(function(){            
      			  if($(this).text() == zipcode){
                  	powerstring =  "";
                    powerproviderfound = true;           	
                    return false;                	
              }	
          });
        }         
        /* Prüfung auf Gas bei BELKAW*/
         if(gasproviderfound == false){
          $(xml).find('content > zipcodes > gas > belkaw > zip').each(function(){                
      			  if($(this).text() == zipcode){
                  	gasstring =  "";
                  	gasproviderfound = true;
                  	return false;
              }	
          });
        }        
        /* Prüfung auf Strom bei sonstigen Partnern */
    		 if(powerproviderfound == false){
          $(xml).find('content > zipcodes > strom > [type="partner"] > zip').each(function(){
            if($(this).text() == zipcode){
          	    var partner = $(this).parent().attr('name');
          	    var url = "<br/><br /><a href='"+$(this).parent().attr('url')+"' target='_blank'>Zum Partnerunternehmen</a>";
            	var head = $(xml).find('content > textnodes > strom > [type="partner"] > head').text();
            	var text_tmp = $(xml).find('content > textnodes > strom > [type="partner"] > desc').text();
            	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>" + partner + "</strong>");
            	powerstring =  "<div class='zipcodeoutput'><h4>" + head + "</h4><p>" + text + url + "</p></div>";
                return false;
            }	
          });
        }
        /* Prüfung auf Gas bei sonstigen Partnern*/
         if(gasproviderfound == false){
          $(xml).find('content > zipcodes > gas > [type="partner"] > zip').each(function(){
            if($(this).text() == zipcode){
            	var partner = $(this).parent().attr('name');
          	    var url = "<br/><br /><a href='"+$(this).parent().attr('url')+"' target='_blank'>Zum Partnerunternehmen</a>";
            	var head = $(xml).find('content > textnodes > gas > [type="partner"] > head').text();
            	var text_tmp = $(xml).find('content > textnodes > gas > [type="partner"] > desc').text();
            	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>" + partner + "</strong>");
            	gasstring =  "<div class='zipcodeoutput'><h4>" + head + "</h4><p>" + text + url + "</p></div>";
               return false;
            }	
          });
        }
    
       //console.log("gas:"+gasstring+"---power:"+powerstring);
    		var gasarea           = $(".square_meter-select");
    		var gasareaelements   = gasarea.siblings(":not(h3)").andSelf();
    		var powerarea           = $(".human-select");
    		var powerareaelements   = powerarea.siblings(":not(h3)").andSelf();
    		
    		
        if(gasstring == "" && powerstring != ""){
          // strom wird nicht von Rheinenergie direkt versorgt
          resetPower();
          powerareaelements.hide(); 
          gasareaelements.fadeIn();
          powerarea.parent().append(powerstring);
          powerarea.parent().find(".zipcodeoutput").fadeIn();       
        }
        else if(gasstring != "" && powerstring == ""){
          // gas wird nicht von Rheinenergie direkt versorgt
          resetGas();
          gasareaelements.hide();
          powerareaelements.fadeIn();
          gasarea.parent().append(gasstring);
          gasarea.parent().find(".zipcodeoutput").fadeIn();                  
        }
        else if(gasstring != "" && powerstring != ""){
          // beides wird nicht von Rheinenergie direkt versorgt
          resetPower();
          resetGas();
          gasareaelements.hide();
          powerareaelements.hide();
          
          powerarea.parent().append(powerstring);
          gasarea.parent().append(gasstring);
          powerarea.parent().find(".zipcodeoutput").fadeIn();  
          gasarea.parent().find(".zipcodeoutput").fadeIn();            
        }
        else{
          gasareaelements.show();
          powerareaelements.show();   
        }
        
            
    		//$("form.tariff-calculator").append(string);
    		

        if($("#usage_power").val() != '' && $("#usage_power").val() != 0){
          var active = 1;
          if(powerstring!=""){
            active = 0;
          }
        }
            
        if($("#usage_gas").val() != '' && $("#usage_gas").val() != 0){
          if (typeof active == 'undefined') {
            var active = 1;
          }
          if(gasstring!=""){
            active = 0;
          }
        }

        if(active == 1)
        {
           $('.tariff-calculator button').removeClass('disabled');
           $('.tariff-calculator button').removeAttr('disabled');
        }
        $('.tariff-calculator h2').css('background','#fff');
        }
    });    
} 

function isAvailableZipRE(zipcode) {		
  if($('#marginalwidget').length < 1) {		
		$('.tariff-calculator h2').ajaxStart(function() {
			$(this).css('background','url("/tarifberater/media/bilder/tarifberater/loadingani.gif") no-repeat scroll 500px center white');
		});
  }
       	
	$.ajax({
        type: "GET",
        url: "/tarifberater/app/xml/zipcodes.xml",
        dataType: "xml",
        success: function(xml) {

		   $(".tariff-calculator .zipcodeoutput").remove();
		   $('.tariff-calculator button').addClass('disabled');
		   $('.tariff-calculator button').attr('disabled','disabled');
		   var powerstring = "<div class='zipcodeoutput'><h4>" + $(xml).find('content > textnodes > strom > [type="none"] > head').text() + "</h4><p>" + $(xml).find('content > textnodes > strom > [type="none"] > desc').text() + "</p></div>";
		   var gasstring = "<div class='zipcodeoutput'><h4>" + $(xml).find('content > textnodes > gas > [type="none"] > head').text() + "</h4><p>" + $(xml).find('content > textnodes > gas > [type="none"] > desc').text() + "</p></div>";
		   var gasproviderfound = false;
		   var powerproviderfound = false;
              	
	  	   /* Prüfung auf Strom bei RheinEnergie*/
	       if(powerproviderfound == false){   
	         $(xml).find('content > zipcodes > strom > rheinenergie > zip').each(function(){            
	     			  if($(this).text() == zipcode){
	                 	powerstring =  "";
                    powerproviderfound = true;            	
	                  return false;                	
	             }	
	         });
	       }
     
	       /* Prüfung auf Gas bei RheinEnergie*/
	       if(gasproviderfound == false){
	         $(xml).find('content > zipcodes > gas > rheinenergie > zip').each(function(){                
	     			  if($(this).text() == zipcode){
	                 	gasstring =  "";
	                 	gasproviderfound = true;
	                 	return false;
	             }	
	         });
	       }
  
	       /* Prüfung auf Strom bei Rheinenergie Express*/
	       if(powerproviderfound == false){
	 	      $(xml).find('content > zipcodes > strom > rheinenergie-express > zip').each(function(){
	 	        if($(this).text() == zipcode){
	 	      	    var partner = $(this).parent().attr('name');
	 	      	    var url = "<br/><br /><a href='"+$(this).parent().attr('url')+"' target='_blank'>Zur RheinEnergie <i>express</i></a>";
	 	        	var head = $(xml).find('content > textnodes > strom > [type="rex"] > head').text().replace(/express/g, "<em>express</em>");
	 	        	var text_tmp = $(xml).find('content > textnodes > strom > [type="rex"] > desc').text();
	 	        	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>RheinEnergie <em>express</em></strong>");
	 	        	powerstring =  "<div class='zipcodeoutput'><h4>" + head + "</h4><p>" + text + url + "</p></div>";
	 	        	powerproviderfound = true;
              return false;
	 	        }	
	 	      });
	 	    }
        /* Prüfung auf Gas bei Rheinenergie Express*/
	       if(gasproviderfound == false){
	 	      $(xml).find('content > zipcodes > gas > rheinenergie-express > zip').each(function(){
	 	        if($(this).text() == zipcode){
	 	        	var partner = $(this).parent().attr('name');
	 	      	    var url = "<br/><br /><a href='"+$(this).parent().attr('url')+"' target='_blank'>Zur RheinEnergie <i>express</i></a>";
	 	        	var head = $(xml).find('content > textnodes > gas > [type="rex"] > head').text().replace(/express/g, "<em>express</em>");
	 	        	var text_tmp = $(xml).find('content > textnodes > gas > [type="rex"] > desc').text();
	 	        	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>RheinEnergie <em>express</em></strong>");
	 	        	gasstring =  "<div class='zipcodeoutput'><h4>" + head + "</h4><p>" + text + url + "</p></div>";
	 	        	gasproviderfound = true;
	 	           return false;
	 	        }	
	 	      });
	 	    }
	    /* Prüfung auf Gas bei Rhenag */
	       if(gasproviderfound == false && document.URL.indexOf("kmu") == -1) {
	    	   $(xml).find('content > zipcodes > gas > rhenag2 > zip').each(function(){
		 	        if($(this).text() == zipcode){
		 	        	var partner = $(this).parent().attr('name');
		 	      	    var url = '<a class="iframe" id="rhenaggasform" href="/formulare/anfrage_gas_neukunde_rhenaggebiet.php?NEU">Oder klicken Sie hier!</a>';
		 	      	    var head = $(xml).find('content > textnodes > gas > [type="rhenag"] > head').text();
		 	        	var text_tmp = $(xml).find('content > textnodes > gas > [type="rhenag"] > desc').text();
		 	        	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>Rhenag</strong>");
		 	        	gasstring =  '<div class="zipcodeoutput"><h4>' + head + "</h4><p>" + text + url + "</p></div>";
		 	        	gasproviderfound = true;
		 	           return false;
		 	        }	
	    	   });
	       }
        /* Prüfung auf Strom bei sonstigen Partnern */
    		if(powerproviderfound == false){ 
        $(xml).find('content > zipcodes > strom > [type="partner"] > zip').each(function(){      
    	        if($(this).text() == zipcode){
    	      	    var partner = $(this).parent().attr('name');
    	      	    var url = "<br/><br /><a href='"+$(this).parent().attr('url')+"' target='_blank'>Zum Partnerunternehmen</a>";
    	        	var head = $(xml).find('content > textnodes > strom > [type="partner"] > head').text();
    	        	var text_tmp = $(xml).find('content > textnodes > strom > [type="partner"] > desc').text();
    	        	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>" + partner + "</strong>");
    	        	powerstring =  "<div class='zipcodeoutput'><h4>" + head + "</h4><p>" + text + url + "</p></div>";
    	        	powerproviderfound = true; 
    	            return false;
    	        }	
    	      });
    	    }
    	    /* Prüfung auf Gas bei sonstigen Partnern*/
    	    if(gasproviderfound == false){
    	      $(xml).find('content > zipcodes > gas > [type="partner"] > zip').each(function(){
    	        if($(this).text() == zipcode){
    	        	var partner = $(this).parent().attr('name');
    	      	    var url = "<br/><br /><a href='"+$(this).parent().attr('url')+"' target='_blank'>Zum Partnerunternehmen</a>";
    	        	var head = $(xml).find('content > textnodes > gas > [type="partner"] > head').text();
    	        	var text_tmp = $(xml).find('content > textnodes > gas > [type="partner"] > desc').text();
    	        	var text = text_tmp.replace(/--PARTNERNAME--/, "<strong>" + partner + "</strong>");
    	        	gasstring =  "<div class='zipcodeoutput'><h4>" + head + "</h4><p>" + text + url + "</p></div>";
    	        	gasproviderfound = true;
    	           return false;
    	        }	
    	    });
    	  }  
    
       //console.log("gas:"+gasstring+"---power:"+powerstring);
    		var gasarea           = $("#usage_gas");
    		var gasareaelements   = $(".gas").siblings(":not(h3)");
    		var powerarea           = $("#usage_power");
    		var powerareaelements   = $(".power").siblings(":not(h3)");
    		
    		
        if(gasstring == "" && powerstring != ""){
          // strom wird nicht von Rheinenergie direkt versorgt
          resetPower();
          powerareaelements.hide(); 
          gasareaelements.fadeIn();
          powerarea.closest('.calculate-container').append(powerstring);
          powerarea.closest('.calculate-container').find(".zipcodeoutput").fadeIn();       
        }
        else if(gasstring != "" && powerstring == ""){
          // gas wird nicht von Rheinenergie direkt versorgt
          resetGas();
          gasareaelements.hide();
          powerareaelements.fadeIn();
          gasarea.closest('.calculate-container').append(gasstring);
          gasarea.closest('.calculate-container').find(".zipcodeoutput").fadeIn();                  
        }
        else if(gasstring != "" && powerstring != ""){
          // beides wird nicht von Rheinenergie direkt versorgt
          resetPower();
          resetGas();
          gasareaelements.hide();
          powerareaelements.hide();
          
          powerarea.closest('.calculate-container').append(powerstring);
          gasarea.closest('.calculate-container').append(gasstring);
          powerarea.closest('.calculate-container').find(".zipcodeoutput").fadeIn();  
          gasarea.closest('.calculate-container').find(".zipcodeoutput").fadeIn();            
        }
        else{
          gasareaelements.show();
          powerareaelements.show();   
        }    		

        if($("#usage_power").val() != '' && $("#usage_power").val() != 0){
          var active = 1;
          if(powerstring!=""){
            active = 0;
          }
        }
            
        if($("#usage_gas").val() != '' && $("#usage_gas").val() != 0){
          if (typeof active == 'undefined') {
            var active = 1;
          }
          if(gasstring!=""){
            active = 0;
          }
        }

        if(active == 1)
        {  
           $('.tariff-calculator button').removeClass('disabled');
           $('.tariff-calculator button').removeAttr('disabled');
        }
               
        if($('#marginalwidget').length < 1) {
        	$('.tariff-calculator h2').css('background','#fff');
        }
        
    	$('a#rhenaggasform').fancybox({
            width: 2000,
            height: 1000
        });
        
        }        
    });    
} 
 function updateUsages() {	
	$(".tariff-calculator .usage").each(function(index) {
		v = $(this).val();		
		v = formatNumber(v);
		
		if(v == '0') {
			$(this).val('');
		} else {
			$(this).val(v);		
		}
		updateEstimates();
	});		
}

function updateEstimates() {	
	updatePowerEstimate();
	updateGasEstimate();
}

function updatePowerEstimate() {
	      
	var powerPersons = new Array(1, 1, 2, 3, 4, 5, 5);
	var powerEnergy = new Array(1, 1500, 2500, 3000, 4000, 5000, 5500);
	if($('.tariff-calculator.commercial-customer #usage_power').length) {
		powerEnergy = new Array(1, 10000, 20000, 35000, 50000, 70000, 90000);
	}	
	      
	var powerLength = powerEnergy.length;
	var powerTextfield = $("#usage_power");
	if(powerTextfield.length)
	{
		var usage = Math.abs(parseInt(powerTextfield.val().toString().replace(/\./, "")));
		var index = 0;
		if(!isNaN(usage) && usage > 0)
		{
			while(index < powerLength && usage >= powerEnergy[index])
			{
				index ++;
			}
		} else {
		    index = -1;
		}

		var powerResult;
		switch(index)
		{
		case -1:
			powerResult = "";
			break;
		case 0:
			powerResult = "&lt;" + powerPersons[0];
			break;
		case powerLength:
			powerResult = "&gt;" + powerPersons[index-1];
			break;
		default:
			powerResult = Math.round(powerPersons[index-1] + (powerPersons[index] - powerPersons[index-1]) * (usage-powerEnergy[index-1]) / (powerEnergy[index] - powerEnergy[index-1]) );
		}
		  
		if(index == -1)
		{					
			resetPower();
		}
		else if(powerResult == 1)
		{			
			$(".human-select").empty();
			$(".human-select").append('<span class="unit"><b>1</b> Person</span><span>kWh/Jahr</span>');
			for(var i=1; i<=6; i++ ){
				$(".human-select").removeClass('show_'+i);
			}
			$(".human-select").addClass('show_1');
			powerTextfield.closest('.calculate-container').addClass('selected');	
		}
		else
		{							
			$(".human-select").empty();
			$(".human-select").append('<span class="unit"><b>' + powerResult + '</b> Personen</span><span>kWh/Jahr</span>');
			for(var i=1; i<=6; i++ ){
				$(".human-select").removeClass('show_'+i);
			}
			if(!isNaN(powerResult)) {
				$(".human-select").addClass('show_'+powerResult);
			}
			else {
				$(".human-select").addClass('show_6');
			}			
			powerTextfield.closest('.calculate-container').addClass('selected');	
		}				
	}
}

function updateGasEstimate() {
	
	var gasM2 = new Array(35, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200);
	var gasEnergy = new Array(5000, 5265, 5850, 6435, 7020, 7605, 8190, 8775, 9360, 9945, 10530, 11115, 11700, 17220, 18040, 18860, 19680, 20500, 21320, 22140, 22960, 23780, 24600, 25420, 26240, 27060, 27880, 28700, 29520, 30340, 31160, 31980, 32801);
	if($('.tariff-calculator.commercial-customer #usage_power').length) {		
		gasM2 = new Array(35, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200);
		gasEnergy = new Array(15000, 17500, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000, 62500, 65000, 67500, 70000, 72500, 75000, 77500, 80000, 82500, 85000, 87500, 90000, 92500, 95000, 97500, 100000, 102500, 105000, 110000, 115000, 117500, 119999);
	}
	var gasLength = gasEnergy.length;
	var gasTextfield = $("#usage_gas"); 

	if(gasTextfield.length)
	{
		var usage = Math.abs(parseInt(gasTextfield.val().toString().replace(/\./, "")));
		var index = 0;
		if(!isNaN(usage) && usage > 0)
		{
			while(index < gasLength && usage >= gasEnergy[index])
			{
				index ++;
			}
		} else {
			index = -1;
		}

		var gasResult;
		switch(index)
		{
		case -1:
			gasResult = "";
			break;
		case 0:
			gasResult = "&lt;" + gasM2[0];
			break;
		case gasLength:
			gasResult = "&gt;" + gasM2[index-1];
			break;
		default:
			gasResult = Math.round(gasM2[index-1] + (gasM2[index] - gasM2[index-1]) * (usage-gasEnergy[index-1]) / (gasEnergy[index] - gasEnergy[index-1]) );
		}
		
		if(index == -1)
		{
			resetGas();
		}
		else
		{
			$(".square_meter-select").empty();
			$(".square_meter-select").append('<span class="unit">Fläche <b>' + gasResult+ '</b> m²</span><span>kWh/Jahr</span>');
			for(var i=1; i<=4; i++ ){
				$(".square_meter-select").removeClass('show_'+i);
			}
			if(gasResult == '&lt;35') {
				$(".square_meter-select").addClass('show_1');
			}
			else if (!isNaN(gasResult) && gasResult < 91){
				$(".square_meter-select").addClass('show_2');
			}
			else if (!isNaN(gasResult) && gasResult > 90 && gasResult < 151){
				$(".square_meter-select").addClass('show_3');
			}
			else if ((!isNaN(gasResult) && gasResult > 151) || gasResult == '&gt;200'){
				$(".square_meter-select").addClass('show_4');
			}
			gasTextfield.closest('.calculate-container').addClass('selected');	
		}				
	}
}						
	/* Selectboxen ersetzen */
	if($('.selectbox').length)
	{		
		$(function(){ $(".selectbox").uniform(); });
		//$('.selectbox').msDropDown({showIcon:false, style: 'background-color: #fff'});		
//		$(function() {
//			var zIndexNumber = 1000;
//			$('div.row, div.row div').each(function() {
//				$(this).css('zIndex', zIndexNumber);
//				zIndexNumber -= 2;
//			});
//		});
//		$(function() {
//			var zIndexNumber = 99;
//			$('fieldset').each(function() {
//				$(this).css('zIndex', zIndexNumber);
//				zIndexNumber -= 5;
//			});
//		});
	}
	/* IE7 z-index Hack */	
	if($('.tariff-selector').length)
	{
		$(function() {
			var zIndexNumber = 2000;
			$('form, div, li').each(function() {
				$(this).css('zIndex', zIndexNumber);
				zIndexNumber -= 10;
			});
		});
	}
	
	/* Schritt 1 Zusatzoptionen ein- oder ausblenden */
	if($('.tariff-advisor .related-option').length)
	{
		$(".related-option").hide();
		$("form input[name=customer-status]:checked").closest('.row').find(".related-option").fadeIn();				
		$("form input[name=customer-status]").change(function() {
			$(".related-option").hide();
			$(this).closest('.row').find(".related-option").fadeIn();
			$('.hint').fadeOut();
		});
	}
	
	if($('#tarifberater-customer-id').length) {
		$('#tarifberater-customer-id').attr('maxLength','9');
		$('#tarifberater-customer-id').css('width',70);
		$('#tarifberater-customer-id').closest('.row').addClass('infoicon');
		$('#tarifberater-customer-id').after('<div class="information"><img src="/tarifberater/media/bilder/tarifberater/info-icon.png" class="info-icon"><div class="info-text">Die Kundennummer finden Sie am einfachsten auf Ihrer letzten Jahresabrechnung.</div></div>');
	}
	if($('#tarifberater-owner-customer-id').length) {		
		$('#tarifberater-owner-customer-id').css('width',90);				
	}	
	if($('#tarifberater-birthday-year').length) {
    $('#tarifberater-birthday-year').closest('.row').append('<div class="information datecolumn"><img src="/tarifberater/media/bilder/tarifberater/info-icon.png" class="info-icon"><div class="info-text"><strong>Warum benötigen wir Ihr Geburtsdatum?</strong><br/>Die Angabe Ihres Geburtsdatums ist für uns unerlässlich, um Sie eindeutig von anderen Kunden unterscheiden zu können. Auch der Gesetzgeber sieht vor, dass ein Vertrag alle notwendigen Angaben zum Kunden enthält. Dazu gehört neben dem vollständigen Namen u. a. auch das Geburtsdatum. (vgl. § 2 Abs. 3 StromGVV und GasGVV)<br />Wir versichern Ihnen, dass wir mit Ihren Daten sorgfältig umgehen und uns an die Bestimmungen des Datenschutzgesetzes halten.</div></div>');
  }
	/* Basis Frontend Validierung */
	if($('.tariff-advisor form').length)
	{
		/* Bei Click in Felder */
		$(".mandatory .selectbox").change( function () {						
			if($(this).find(":selected").text() != "")
			{
				$(this).closest('.row').removeClass('error');
				$(this).closest('.row').find('.hint').fadeOut();				
			}
			else
			{
				$(this).closest('.row').addClass('error');
				$(this).closest('.row').find('.hint').fadeIn();
			}
		});
		
		if($('#tarifberater-customer-id').val() == '')
		{
			$('#tarifberater-customer-id').val('20');
		}
		
		$('#tarifberater-power-distributor-persons').attr('maxLength','2');
		$('#tarifberater-power-distributor-persons').css('width',20);
		$('#tarifberater-gas-distributor-persons').attr('maxLength','2');
		$('#tarifberater-gas-distributor-persons').css('width',20);

		$("form .mandatory, form .reading").blur( function () {
			$(this).closest('.row').removeClass('error');
			$(this).closest('.row input').removeClass('error');
			$(this).closest('.row').find('.hint').fadeOut();	
			$(this).closest('.row').find('.mailhint').fadeOut();
			$(this).closest('.row').find('.zipcodehint').fadeOut();
			$(this).closest('.row').find('.cidhint').fadeOut();	
			$(this).closest('.row').find('.counterhint').hide();
			$(this).closest('.row').find('.readinghint').hide();
			if($(this).closest('.row').hasClass('address')) {					
				if($(this).hasClass('house-no') && $(this).val() == '')
				{
					$(this).addClass('error');
					var hint = "Bitte geben Sie eine Hausnummer ein.";
					$(this).closest('.row').find('.hint').html(hint);
					$(this).closest('.row').find('.hint').fadeIn();
					valid = false;										
				}
				if($(this).hasClass('street') && $(this).val() == '')
				{
					$(this).addClass('error');
					var hint = "Bitte geben Sie eine Strasse ein.";
					$(this).closest('.row').find('.hint').html(hint);
					$(this).closest('.row').find('.hint').fadeIn();
					valid = false;										
				}
				if($(this).hasClass('city') && $(this).val() == '')
				{
					$(this).addClass('error');
					var hint = "Bitte geben Sie einen Ort ein.";
					$(this).closest('.row').find('.hint').html(hint);
					$(this).closest('.row').find('.hint').fadeIn();
					valid = false;										
				}
				if($(this).hasClass('zipcode'))
				{
					if(!isValidZipcode($(this).val()))
					{
						$(this).addClass('error');
						$(this).closest('.row').find('.zipcodehint').fadeIn();
						valid = false;
					}					
				}
					
			}
						
			else if($(this).attr('id') == 'tarifberater-email' && $(this).val() != '')
			{
				if(!isValidEmailAddress($(this).val()))
				{
					$(this).closest('.row').addClass('error');
					$(this).closest('.row').find('.mailhint').fadeIn();
				}
			}
			else if($(this).attr('id') == 'tarifberater-customer-id' && $(this).val() != '')
			{
				if(!isValidCustomerId($(this).val()))
				{
					$(this).closest('.row').addClass('error');
					$(this).closest('.row').find('.cidhint').fadeIn();
				}
			}
			else if($(this).hasClass('counter') && $(this).val() != '')
			{					
				if(!isValidCounterNo($(this).val()))
				{
					$(this).closest('.row').addClass('error');					
					$(this).closest('.row').find('.counterhint').fadeIn();					
				}					
			}
			else if($(this).hasClass('reading'))
			{
				if($(this).val() != '' && !isValidReading($(this).val()))
				{
					$(this).closest('.row').addClass('error');					
					$(this).closest('.row').find('.readinghint').fadeIn();					
				}					
			}
			else if($(this).hasClass('zipcode') && $(this).val() != '')
			{
				if(!isValidZipcode($(this).val()))
				{
					$(this).closest('.row').addClass('error');
					$(this).closest('.row').find('.zipcodehint').fadeIn();
				}
			}
			else if($(this).val() == '')
			{
				$(this).closest('.row').addClass('error');
				$(this).closest('.row').find('.hint').fadeIn();
			}
		});
		
		/* Bei Submit */
		$('.tariff-advisor form.step').submit(function() {
			//alert('submit');
			$('.hint').hide();	
			$('.mailhint').hide();
			$('.zipcodehint').hide();
			$('.cidhint').hide();
			$('.counterhint').hide();
			$('.readinghint').hide();
			var valid = true;
			var firstnonvalidelement = "";
			$("form input[type=text].mandatory:visible, form input[type=text].reading:visible").each(function() {
				if($(this).closest('.row').hasClass('address')) {					
					if($(this).hasClass('house-no') && $(this).val() == '')
					{
						$(this).addClass('error');
						if(firstnonvalidelement == ""){
               firstnonvalidelement =  $(this);
            }
						
						if($('.street').val() != '') {
							var hint = "Bitte geben Sie eine Hausnummer ein.";
						}
						else {
							$('.street').addClass('error');
							var hint = "Bitte geben Sie eine Strasse und Hausnummer ein.";
						}
						$(this).closest('.row').find('.hint').html(hint);
						$(this).closest('.row').find('.hint').fadeIn();
						valid = false;										
					}
					if($(this).hasClass('street') && $(this).val() == '')
					{
						$(this).addClass('error');
						if(firstnonvalidelement == ""){
               firstnonvalidelement =  $(this);
            }
						if($('.house-no').val() != '') {
							var hint = "Bitte geben Sie eine Strasse ein.";
						}
						else {
							$('.house-no').addClass('error');
							var hint = "Bitte geben Sie eine Strasse und Hausnummer ein.";
						}						
						$(this).closest('.row').find('.hint').html(hint);
						$(this).closest('.row').find('.hint').fadeIn();
						valid = false;										
					}
					if($(this).hasClass('city') && $(this).val() == '')
					{
						$(this).addClass('error');
						if(firstnonvalidelement == ""){
               firstnonvalidelement =  $(this);
            }
						if($('.zipcode').val() != '') {
							var hint = "Bitte geben Sie einen Ort ein.";
						}
						else {
							$('.zipcode').addClass('error');
							var hint = "Bitte geben Sie eine Postleitzahl und Ort ein.";
						}						
						$(this).closest('.row').find('.hint').html(hint);
						$(this).closest('.row').find('.hint').fadeIn();
						valid = false;										
					}
					if($(this).hasClass('zipcode'))
					{
						if(!isValidZipcode($(this).val()))
						{
						  if(firstnonvalidelement == ""){
               firstnonvalidelement =  $(this);
              }
							if($('.city').val() != '') {
								$(this).addClass('error');
								$(this).closest('.row').find('.zipcodehint').fadeIn();
							}
							else {
								$('.city').addClass('error');
								var hint = "Bitte geben Sie eine Strasse und Hausnummer ein.";
							}							
							valid = false;
						}						
					}
						
				}
				else if($(this).attr('id') == 'tarifberater-email' && $(this).val() != '') {
					if(!isValidEmailAddress($(this).val()))
					{
						$(this).closest('.row').addClass('error');
						if(firstnonvalidelement == ""){
			               firstnonvalidelement =  $(this);
			            }
						$(this).closest('.row').find('.mailhint').fadeIn();
						valid = false;
					}					
				}
				
				else if($(this).attr('id') == 'tarifberater-email' && $(this).val() != '') {
					if(!isValidEmailAddress($(this).val()))
					{
						$(this).closest('.row').addClass('error');
						if(firstnonvalidelement == ""){
			               firstnonvalidelement =  $(this);
			            }
						$(this).closest('.row').find('.mailhint').fadeIn();
						valid = false;
					}					
				}
				
				else if($(this).attr('id') == 'tarifberater-customer-id' && $(this).val() != '')
				{					
					if(!isValidCustomerId($(this).val()))
					{
						$(this).closest('.row').addClass('error');
						if(firstnonvalidelement == ""){
		               firstnonvalidelement =  $(this);
		            }
						$(this).closest('.row').find('.cidhint').fadeIn();
						valid = false;
					}					
				}
				else if($(this).hasClass('counter') && $(this).val() != '')
				{					
					if(!isValidCounterNo($(this).val()))
					{
						$(this).closest('.row').addClass('error');
						if(firstnonvalidelement == ""){
		               firstnonvalidelement =  $(this);
		            }
						$(this).closest('.row').find('.counterhint').fadeIn();
						valid = false;
					}					
				}
				else if($(this).hasClass('reading'))
				{					
					if($(this).val() != '' && !isValidCounterNo($(this).val()))
					{
						$(this).closest('.row').addClass('error');
						if(firstnonvalidelement == ""){
							firstnonvalidelement =  $(this);
						}
						$(this).closest('.row').find('.readinghint').fadeIn();
						valid = false;
					}					
				}
				else if($(this).val() != '')
				{
					if (valid == true) { valid = true; }
				}
				else
				{
					$(this).closest('.row').addClass('error');
					if(firstnonvalidelement == ""){
               firstnonvalidelement =  $(this);
          }
					$(this).closest('.row').find('.hint').fadeIn();
					valid = false;
				}				
			});
						
			$("select.mandatory option:selected, .mandatory select option:selected").each( function () {			
				if($(this).text() == "")
				{
          if(firstnonvalidelement == ""){
               firstnonvalidelement =  $(this);
          }   
          			$(this).addClass('error');
          			$(this).closest('.row').addClass('error');
					$(this).closest('.row').find('.hint').fadeIn();	
					valid = false;
				}				
			});
						
			if($("form input:radio[name=customer-status]").length)
			{				
				if(!(typeof $("form input:radio[name=customer-status]:checked").val() === "undefined"))
				{
					valid = true;				
				}
				else {
					valid = false;				
					$("form .hint").show();
				}
			}
      if(valid == false){
          var new_position = $(firstnonvalidelement).offset();
          window.scrollTo(0,new_position.top);     
      }
			return valid;
		});
	}
	
	/* Schritt 3 - Zähler hinzufügen */
	if($('#tarifberater-power-counter-reading-1').length || $('#tarifberater-gas-counter-reading-1').length)
	{
		$("a.fancyimage").fancybox();
		
		var counter = 0;
				
		$('#tarifberater-further-counter').append('<div class="row pt20"><span class="add add-counter">Weiteren Zähler hinzufügen</span></div>');
		$('#tarifberater-further-counter').append('<div class="row"><span class="hide hide-counter">Letzten Zähler entfernen</span></div>');
		
		for(var i=1; i<=10; i++ )
		{
			$('#tarifberater-further-counter-energytype-'+i).closest('.row').addClass('border');
			if($('#tarifberater-further-counter-no-'+i).val() == '')
			{				
				$('#tarifberater-further-counter-reading-'+i).parent('.row').hide();
				$('#tarifberater-further-counter-no-'+i).parent('.row').hide();
				$('#tarifberater-further-counter-energytype-'+i).closest('.row').hide();
				$('#tarifberater-further-counter-meter-reading-date-'+i+'-day').closest('.row').hide();				
			}
			else {
				counter++;
			}
			if(counter == 0) {				
				$('.hide-counter').hide();
			}
		}
		
		$(".add-counter").click( function () {
			counter++;
			
			$('#tarifberater-further-counter-reading-'+counter).parent('.row').fadeIn();
			$('#tarifberater-further-counter-no-'+counter).parent('.row').fadeIn();
			$('#tarifberater-further-counter-energytype-'+counter).closest('.row').fadeIn();
			$('#tarifberater-further-counter-meter-reading-date-'+counter+'-day').closest('.row').fadeIn();			
			if(counter == 1)
			{
				$('.hide-counter').fadeIn();
			}
			
			if(counter == 10)
			{
				$(this).fadeOut();
			}			
		});
		
		$(".hide-counter").click( function () {			
			$('#tarifberater-further-counter-reading-'+counter).parent('.row').fadeOut();
			$('#tarifberater-further-counter-reading-'+counter).val('');
			$('#tarifberater-further-counter-no-'+counter).parent('.row').fadeOut();
			$('#tarifberater-further-counter-no-'+counter).val('');
			$('#tarifberater-further-counter-energytype-'+counter).closest('.row').fadeOut();
			$('#tarifberater-further-counter-energytype-'+counter).attr('selectedIndex', 'false');			
			$('#tarifberater-further-counter-meter-reading-date-'+counter+'-day').closest('.row').fadeOut();
			$('#tarifberater-further-counter-meter-reading-date-'+counter+'-day').attr('selectedIndex', 'false');			
			$('#tarifberater-further-counter-meter-reading-date-'+counter+'-month').attr('selectedIndex', 'false');			
			$('#tarifberater-further-counter-meter-reading-date-'+counter+'-year').attr('selectedIndex', 'false');			
			
			if(counter == 1)
			{
				$(this).fadeOut();
			}			
			if(counter == 10)
			{
				$('.add-counter').fadeIn();
			}
			counter--;
		});
				
	}
	if($('.Step_Auftragsdaten #tarifberater-power-counter-old').length || $('.Step_Auftragsdaten #tarifberater-gas-counter-old').length) {
		$('#tarifberater-power-counter-old').before('<h5>Daten zur Abmeldeadresse</h5>');
		
		var counter_old = 0;
		
		$('#tarifberater-further-counter-old').append('<div class="row pt20"><span class="add add-counter-old">Weiteren Zähler hinzufügen</span></div>');
		$('#tarifberater-further-counter-old').append('<div class="row"><span class="hide hide-counter-old">Letzten Zähler entfernen</span></div>');
		
		for(var i=1; i<=10; i++ )
		{
			$('#tarifberater-further-counter-energytype-old-'+i).closest('.row').addClass('border');
			if($('#tarifberater-further-counter-no-old-'+i).val() == '')
			{				
				$('#tarifberater-further-counter-reading-old-'+i).parent('.row').hide();
				$('#tarifberater-further-counter-no-old-'+i).parent('.row').hide();
				$('#tarifberater-further-counter-energytype-old-'+i).closest('.row').hide();
				$('#tarifberater-further-counter-meter-reading-date-old-'+i+'-day').closest('.row').hide();				
			}
			else {
				counter_old++;
			}
			if(counter_old == 0) {				
				$('.hide-counter-old').hide();
			}
		}
		
		$(".add-counter-old").click( function () {
			counter_old++;
			
			$('#tarifberater-further-counter-reading-old-'+counter_old).parent('.row').fadeIn();
			$('#tarifberater-further-counter-no-old-'+counter_old).parent('.row').fadeIn();
			$('#tarifberater-further-counter-energytype-old-'+counter_old).closest('.row').fadeIn();
			$('#tarifberater-further-counter-meter-reading-date-old-'+counter_old+'-day').closest('.row').fadeIn();			
			if(counter_old == 1)
			{
				$('.hide-counter-old').fadeIn();
			}
			
			if(counter_old == 10)
			{
				$(this).fadeOut();
			}			
		});
		
		$(".hide-counter-old").click( function () {			
			$('#tarifberater-further-counter-reading-old-'+counter_old).parent('.row').fadeOut();
			$('#tarifberater-further-counter-reading-old-'+counter_old).val('');
			$('#tarifberater-further-counter-no-old-'+counter_old).parent('.row').fadeOut();
			$('#tarifberater-further-counter-no-old-'+counter_old).val('');
			$('#tarifberater-further-counter-energytype-old-'+counter_old).closest('.row').fadeOut();
			$('#tarifberater-further-counter-energytype-old-'+counter_old).attr('selectedIndex', 'false');			
			$('#tarifberater-further-counter-meter-reading-date-old-'+counter_old+'-day').closest('.row').fadeOut();
			$('#tarifberater-further-counter-meter-reading-date-old-'+counter_old+'-day').attr('selectedIndex', 'false');			
			$('#tarifberater-further-counter-meter-reading-date-old-'+counter_old+'-month').attr('selectedIndex', 'false');			
			$('#tarifberater-further-counter-meter-reading-date-old-'+counter_old+'-year').attr('selectedIndex', 'false');			
			
			if(counter_old == 1)
			{
				$(this).fadeOut();
			}			
			if(counter_old == 10)
			{
				$('.add-counter-old').fadeIn();
			}
			counter_old--;
			$.uniform.update();
		});
	}
	
	/* Schritt 3 - Daten kopieren*/
	if($(".Step_Auftragsdaten #tarifberater-gas-distributor").length && $(".Step_Auftragsdaten #tarifberater-power-distributor").length) { 	
		$("#tarifberater-gas-distributor .row:first").css('position', 'relative');	
		$("#tarifberater-gas-distributor .row:first").append('<div class="radio copy-option"><input type="checkbox" id="copy-data" value="copy-data" name="copy-data" /><label for="copy-data">Daten des Stromanbieters übernehmen</label></div>');		
		
		$("#copy-data").click( function () {
			if($(this).is(":checked"))
			{								
				$('#tarifberater-power-distributor input').each(function(){
					var oldID = $(this).attr('id');	
					if(oldID == "tarifberater-power-distributor-usage"){
             return true;
          } 
          var newID = oldID.replace(/power/g, "gas");
					$('#'+newID).val($(this).val());
					if($(this).val() != '') {
						$('#'+newID).closest('.row').removeClass('error');
						$('#'+newID).closest('.row').find('.hint').fadeOut();	
						$('#'+newID).closest('.row').find('.mailhint').fadeOut();
						$('#'+newID).closest('.row').find('.zipcodehint').fadeOut();
						$('#'+newID).closest('.row').find('.cidhint').fadeOut();
					}
				});
				/*
				$('#tarifberater-power-distributor select').each(function(){
					var oldID = $(this).attr('id');
					var selectedVal = $(this).find('option:selected').val();  
					var newID = oldID.replace(/power/g, "gas");				
					$('#'+ newID + ' option').each(function(){
						//alert($(this).val());
						if($(this).val() == selectedVal) {
							$(this).attr('selected', 'selected');
						}
					});	
				});
				$('.selectbox').msDropDown({showIcon:false, style: 'background-color: #fff'});
			*/	
			}
		});		
	}
	
	/* Schritt 3 - Kündigungsvollmacht */
	if($('input[id="authorize-denouncement-rheinenergie"]:checked').length) {
		$('#tarifberater-power-distributor').show();
		$('#tarifberater-gas-distributor').show();
	}
	else
	{
		$('#tarifberater-power-distributor').hide();
		$('#tarifberater-gas-distributor').hide();
	}
	
	$('input[name="authorize-denouncement"]').click( function () {
		
		if($(this).val() == "authorize-denouncement-rheinenergie") {
			$('#tarifberater-power-distributor').fadeIn();
			$('#tarifberater-gas-distributor').fadeIn();
			$('#uniform-tarifberater-power-distributor-endate-day').parent().addClass('mandatory');
			$('#uniform-tarifberater-gas-distributor-endate-day').parent().addClass('mandatory');
		}
		else
		{
			$('#tarifberater-power-distributor').fadeOut();
			$('#tarifberater-gas-distributor').fadeOut();
			$('#uniform-tarifberater-power-distributor-endate-day').parent().removeClass('mandatory');
			$('#uniform-tarifberater-gas-distributor-endate-day').parent().removeClass('mandatory');

		}
		
	})
	
	/* Schritt 4 - Rechnungsadresse einblenden */
	if($("'#Step_Rechnungsdaten #other-bill-address").length)
	{
		$("#other-bill-address").hide();
		if($("form input[name=bill-address]:checked").val() == 'diffrent-bill-address')
		{
			$("#other-bill-address").show();
		}
		$("form input[name=bill-address]").click( function () {
			if($("form input[name=bill-address]:checked").val() == 'diffrent-bill-address')
			{
				$("#other-bill-address").fadeIn();
			}
			else
			{
				$("#other-bill-address").fadeOut();
			}
		});
	}
	
	/* Schritt 4 - Rechnungsadresse einblenden */
	if($("'#Step_Rechnungsdaten #bank-data").length)
	{
		$("#bank-data").hide();
		if($("form input[name=debit-full]:checked").val() == 'debit-accept' || $("form input[name=debit-short]:checked").val() == 'debit-accept')
		{
			$("#bank-data").show();
		}
		$("form input[name=debit-full], form input[name=debit-short]").click( function () {
			if($("form input[name=debit-full]:checked").val() == 'debit-accept' || $("form input[name=debit-short]:checked").val() == 'debit-accept')
			{
				$("#bank-data").fadeIn();
			}
			else
			{
				$("#bank-data").fadeOut();
			}
		});
	}
	
	/* Schritt 5 - Vertragsdaten */
	if($(".tarifberater-print").length)
	{
		$(".tarifberater-print").show();
		$(".tarifberater-print").click( function () {
			window.print();
		});
	}
	
	/* Infotext in Tabelle anzeigen oder ausblenden */
	if($(".information").length)
	{
		$(".information").mouseenter( function () {
			$('.information-option').css('z-index', '2');
			$('.information').css('z-index', '1');
			$(this).find(".info-text").show();
			$(this).css('zIndex', '999');
		});
		
		$(".information").mouseleave( function () {
			$(this).find(".info-text").hide();
			$('.information').css('z-index', '1');			
		});
	}
	
	/* Tarife ein- ausklappen */
	if($(".tariff-selector form.tariff").length) {		
		$( ".tariff-advisor .checkbox" ).buttonset();
        $( ".tariff-advisor .checkbox a" ).button("destroy");
		$(".tariff-advisor .checkbox input").each(function() {
			if($(this).hasClass('not-available')) {
				$(this).button( "disable" );
			}
		});
		$("form.tariff").each(function(index) {
			if(index == 0)	 {
				$(this).addClass('selected');
			}
			else {
				$(this).addClass('disabled');
			}
		});

		$("form.tariff h3.toggle").click( function () {
			$(this).closest('form').toggleClass('disabled');						
		});
		$("form.tariff").click( function () {
			$("form.tariff").removeClass('selected');
			$(this).addClass('selected');
		});
		
	}		
	
	/* Auswahl Optionen */
	if($(".tariff-selector form.tariff").length) {
		var aktiv = '';
		$(".checkbox input").change( function (event) {			
			window.clearTimeout(aktiv);
			$('.option-infotext').hide();
			$('.information').css('z-index', '1');	
			$('.information-option').css('z-index', '2');
			var name = $(this).attr('name');
			$(this).closest('td').append('<div class="information-option"></div>');
			var item = $(this).closest('td').find('.information-option');
			item.css('zIndex', '1000');
			var text = "";
			if(name.match(/cleverweb/) && ($('.nebenzeit input:checked').length > 0 || $('.online input:checked').length > 0)){
				if($("input[name='company']").val() == 'bk' || $("input[name='company']").val() == 'bkgw') {
					text += "Die CleverWeb-Option kann nicht mit der Nebenzeit-Option kombiniert werden.";
				}
				else {
					text += "Die CleverWeb-Option kann nicht mit der Nebenzeit-Option oder der Online-Option kombiniert werden.";
				}
			}			
			if(name.match(/nebenzeit/) && $('.clever input:checked').length > 0) {				
				text += "Die Nebenzeit-Option kann nicht mit der CleverWeb-Option kombiniert werden.";
			}
			if(name.match(/online/) && $('.clever input:checked').length > 0) {				
				text += "Die Online-Option kann nicht mit der CleverWeb-Option kombiniert werden.";
			}
			if(name.match(/gas-option-cleverweb/) && $('input[name="power-option-cleverweb"]:checked').length == 0) {
				text += 'Die CleverWeb-Option für Gas kann nicht ohne die CleverWeb-Option für Strom gewählt werden.';
			}
			if(name.match(/power-option-cleverweb/) && $('input[name="gas-option-cleverweb"]:checked').length != 0) {
				text += 'Die CleverWeb-Option für Gas kann nicht ohne die CleverWeb-Option für Strom gewählt werden.';
			}
			if(text != ""){
				item.append('<div class="option-infotext"><strong class="boldred">Hinweis:</strong><br />'+text+'<br />Ihre Auswahl wird automatisch angepasst.</div>');
				item.find('.option-infotext').show();
				aktiv = window.setTimeout("$('.option-infotext').fadeOut(); $('.information-option').detach();", 7000);
			}
			updateOptions($(this).closest('form'), event.target.id);
		});
	}
	    
	function hideOptionInfo(item) {
		$('.option-info').hide();
	}
	
	
	/*  Adressdaten Kreuzvalidierung Einwilligung Telefon/Feld Telefon*/
		if ($("input#accept-contact-phone").attr('checked') == true){
	        $("label[for='tarifberater-phone']").append(' *');
	        $("input#tarifberater-phone").addClass('mandatory');
	        $("input#tarifberater-phone").after('<div class="hint">Geben Sie bitte Ihre Telefonnummer ein.</div>');
	        $("input#tarifberater-phone").bind('focus change', function () {
				$(this).closest('.row').removeClass('error');
				$(this).closest('.row').find('.hint').fadeOut();
			});
	        $("input#tarifberater-phone").bind('blur', function () {
	        	if($(this).val() == '')
				{
					$(this).closest('.row').addClass('error');
					$(this).closest('.row').find('.hint').fadeIn();
				}						
			});	        
	    }
		
	   	$("input#accept-contact-phone").change( function (event) {
          if ($(event.target).attr('checked') == true){
              $("label[for='tarifberater-phone']").append(' *');
              $("input#tarifberater-phone").addClass('mandatory');
              $("input#tarifberater-phone").after('<div class="hint">Geben Sie bitte Ihre Telefonnummer ein.</div>');
              $("input#tarifberater-phone").bind('focus change', function () {
  				$(this).closest('.row').removeClass('error');
  				$(this).closest('.row').find('.hint').fadeOut();
  			  });
            $("input#tarifberater-phone").bind('blur', function () {
  	        	if($(this).val() == '')
  				{
  					$(this).closest('.row').addClass('error');
  					$(this).closest('.row').find('.hint').fadeIn();
  				}						
  			});
          }
          else{
              $("label[for='tarifberater-phone']").empty();
              $("label[for='tarifberater-phone']").prepend("Telefon:");
              $("input#tarifberater-phone").removeClass('mandatory');
              $("input#tarifberater-phone").closest('.row').removeClass('error');
			  $("input#tarifberater-phone").closest('.row').find('.hint').remove();
              $("input#tarifberater-phone").unbind('blur focus change');
          }
      });
});

function updateOptions(form, item) {
	var inputs = new Object();
	inputs = form.find('input');
	var datacontainer = new Object(); 
	$.each(inputs, function () {				
		if($(this).attr("type") == 'hidden') {
			datacontainer[$(this).attr("name")] = $(this).val();
		}
		else if($(this).attr("type") == 'checkbox') {
			datacontainer[$(this).attr("name")] = $(this).attr('checked');	
		}
	});
	datacontainer['totalcosts'] = form.find('.hidden-totalcosts').val();			
	datacontainer['powercost'] = form.find('.hidden-powercost').val();
	datacontainer['gascost'] = form.find('.hidden-gascost').val();
	datacontainer['power-usage'] = form.find('.user-power-usage').val();
	datacontainer['gas-usage'] = form.find('.user-gas-usage').val();
	datacontainer['clicked'] = item;
	
	form.find(".checkbox input").attr('disabled', 'disabled');
	form.find("div.tariff-advisor button.submit").attr('disabled', 'disabled');
	calculatePrices(datacontainer);

}

function calculatePrices(datacontainer) {
	$.ajax({
        type: "GET",
        dataType: "json",
        url: "?ajax=calculate",
        data: {
			container: datacontainer
		},
        success: function(response) {
			form = $('input[name="tariff"][value="' + response[0] + '"]').closest("form");
			
			form.find(".checkbox input").removeAttr('disabled');
			form.find("div.tariff-advisor button.submit").removeAttr('disabled');
			setFormState(response[0], response[1]);
			form.find('.totalcosts').html(germanFormat(response[2][0]));
			form.find('.powercost').html(germanFormat(response[2][1]));
			form.find('.gascost').html(germanFormat(response[2][2]));
			form.find('.onetimepower').html(germanFormat(response[2][3]));
			form.find('.onetimegas').html(germanFormat(response[2][4]));
			form.find('.onetimetotal').empty();
			form.find('.onetimetotal-text').empty();
			form.find('.bonustotal').empty();
			form.find('.bonus-text').empty();
			var hits = 0;
			$(".checkbox input:checked").each(function() {
				var name = $(this).attr('name');
				if(name.match(/cleverweb/) || name.match(/nebenzeit/)){
					hits++;
				}
			});
			if(hits > 0) {
				form.find('.totalcosts-text').html('Gesamtkosten pro Jahr unter der Annahme 58%-Anteil in der Nebenzeit');
			}
			else {
				form.find('.totalcosts-text').html('Gesamtkosten pro Jahr');
			}
			if(response[2][5] != '0') {
				form.find('.onetimetotal').html(germanFormat(response[2][5]) + ' Euro');
				var texthint = 'Zuzüglich einmalige Einrichtungskosten für die gewählte ';
				var optionhit = 0;
				for(var i = 0; i < response[1].length; i++) {					
					if(response[1][i].match(/cleverweb/) || response[1][i].match(/nebenzeit/)){
						var label = $('input[name="' + response[1][i] + '"]').closest('td').find('label span').text();						
						if(optionhit == 0) {
							optionhit++;
							texthint += label + ':';
						}
					}
				}
			}				
			form.find('.onetimetotal-text').html(texthint);
								
			for(var i = 0; i < response[1].length; i++) {					
				if(response[1][i].match(/power-option-oeko/) && response[2][6][0] != '0'){
					form.find('.bonustotal').html(germanFormat(response[2][6][0]) + ' Euro');
					var texthint = '<span>Abzüglich einmaliger Bonus für die Öko-Option Strom:</span><div class="information" style="z-index: 1;"><img src="/tarifberater/media/bilder/tarifberater/info-icon.png" class="info-icon"><div class="info-text" style="z-index: 660;">' + response[2][6][1] + '</div></div>';					
										
					form.find('.bonus-text').html(texthint);
					$(".bonus-text .info-icon").mouseenter( function () {
						$('.information-option').css('z-index', '2');
						$('.information').css('z-index', '1');
						$(this).parent('.information').find(".info-text").show();			
						$(this).parent('.information').css('zIndex', '999');
					});
					$(".bonus-text .info-icon").mouseleave( function () {
						$(this).parent('.information').find(".info-text").hide();
						$('.information').css('z-index', '1');			
					});
				}
			}			
		}        
    });
}

function setFormState(tariff, list) {
	form = $('input[type="hidden"][value="' + tariff + '"]').closest('form');
	form.find('input:checkbox"').each(function() {
		
		found = false;
		for(i = 0; i < list.length; i++)
		{
			if($(this).attr('name') == list[i])
			{
				found = true;
				break;
			}
		}
		if(found)
		{
			$(this).attr('checked', 'checked');
		}
		else
		{
			$(this).attr('checked', '');
		}
		$(this).closest('.checkbox').buttonset();
        $( ".tariff-advisor .checkbox a" ).button("destroy");
		$(".tariff-advisor .checkbox input").each(function() {
			if($(this).hasClass('not-available')) {
				$(this).button( "disable" );
			}
		});
	});
}
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function isValidZipcode(zip) {
	var pattern = new RegExp(/^([0-9]{5})$/);
	return pattern.test(zip);
}
function isValidCounterNo(no) {
	var pattern = new RegExp(/^[0-9a-zA-Z]+((-|\s)*[0-9a-zA-Z]+)+$/);
	return pattern.test(no);
}
function isValidReading(no) {
	var pattern = new RegExp(/^[0-9]+$/);
	return pattern.test(no);
}

function isValidCustomerId(cid) {
	var pattern = new RegExp(/^(20[0-9]{7})$/);
	return pattern.test(cid);
}

function germanFormat(x) {
  var k = (Math.round(x * 100) / 100).toString();
  var sEnding;
  var sReturn;
  if (k.indexOf('.') == -1)
    sEnding = '.00';
  else
    sEnding = '00';
 
  k = k + sEnding;
 
  var p = k.indexOf('.');
  var s = 0;
  sReturn = k.substring(0, p);
  
  //Tausenderpunkte setzen
  for( i = sReturn.length-3; i > s; i-=3 ){
    sReturn = sReturn.substring( 0, i ) + "." + sReturn.substring( i );
  }
  
  sReturn = sReturn + ',';
  sReturn = sReturn + k.substring(p+1, p+3);
  return sReturn;
}
/*
function germanFormat(x) {
  formatt(x);
  var k = (Math.round(x * 100) / 100).toString();
  var sEnding;
  var sReturn;
  if (k.indexOf('.') == -1)
    sEnding = '.00';
  else
    sEnding = '00';
 
  k = k + sEnding;
 
  var p = k.indexOf('.');
  sReturn = k.substring(0, p);
  sReturn = sReturn + ',';
  sReturn = sReturn + k.substring(p+1, p+3);
  
  return sReturn;
}
*/
function formatNumber(v) {
	v = v.toString();
	v = v.replace(/\./, "");
	v = Math.abs(parseInt(v));
		
	r = "";
	n = 0;
	if(isNaN(v) || v == 0)
	{
		r = '0';
	}
	else
	{
		while(v > 0)
		{
			if(n%3 == 0 && n > 0)
			{
				r = '.' + r;
			}
			n++;
			r = (v%10) + "" + r;
			v = Math.floor(v/10);
		}
	}
	return r;
}
