var inputAutoFill = function(){
	// start up routine
	$('.nofocus').each(function(index, value){
		var elm = $(value);
		
		if (elm.val() != elm.attr('title')) {
			if (elm.val() == '') {
				elm.val($(value).attr('title'));

			} else {
				elm.removeClass('nofocus');
				elm.addClass('focus');								
			};
		};
	});
	
	// event bindings
	$('.nofocus').live('focus', function(){
		var elm = $(this);
		
		elm.removeClass('nofocus');
		elm.addClass('focus');
		elm.val('');
	});
	
	$('.focus').live('change', function(){
		var elm = $(this);
		if (elm.val() == '') {
			elm.removeClass('focus');
			elm.val(elm.attr('title'));
			elm.addClass('nofocus');
		};
	});
};


var animateTeaser = function(){
	$('#main').removeClass('bg_people');
	$('#main .teaser_block, #main .teaser_block h1, #main .teaser_block #step1').hide();
	$('#main .teaser_block').slideDown(750,function(){
		$('#main .teaser h1').fadeIn(250,function(){
			$('#main .teaser_block #step1').fadeIn(450, function(){
				$('#main').addClass('bg_people');
			});
		});
	});
};

var initForm = function(){
	$('document').ready(function(){
		$('input.error').live('focus', function(){
			$(this).removeClass('error');
		});
	});
};

function calculatePricePerYear(basicPrice, variablePrice, powerConsumption) {
    var pricePerYear = 
        powerConsumption 
        * (variablePrice / 100)  // variable price is given in ct. but needs to be calclated as Euro -> divide by 100
        + (basicPrice * 12) // multiply by 12 to get price per year
    ;
    
    return pricePerYear;
}

function floatFromTextById(id) {
    return parseFloat($(id).text().replace(",",".")); // we need to replace "," with "." because english float format is x.y not x,y
}

var sliderInit = function() {
  //setStartingValues
  var pricePerYear = calculatePricePerYear(floatFromTextById("#power_basicprice"), floatFromTextById("#power_variableprice"), 2500);
  var bonusAmount = floatFromTextById("#bonus_amount");
  $("#power_price_per_year").html(pricePerYear.toFixed(2).toString().split(".").join(",")); // we need to display 2 digits after the , even if these are zero      
  $("#power_price_per_year_bonus").html((pricePerYear-bonusAmount).toFixed(2).toString().split(".").join(",")); // we need to display 2 digits after the , even if these are zero      
  
  $("#slider").slider({
    value:2500,
    min: 100,
    max: 10400,
    step: 100,
    slide: function(event, consumptionSlider) {
      $("#power_consumption_value").text(consumptionSlider.value); // value of the slider = consumption per year
      
      var pricePerYear = calculatePricePerYear(floatFromTextById("#power_basicprice"), floatFromTextById("#power_variableprice"), consumptionSlider.value);      
      
      $("#power_price_per_year").html(pricePerYear.toFixed(2).toString().split(".").join(",")); // we need to display 2 digits after the , even if these are zero
      $("#power_price_per_year_bonus").html((pricePerYear-bonusAmount).toFixed(2).toString().split(".").join(","));
    }
  });
};

function initAccordion() {
    /*---------------------------------------------------------------------------------------------------- */
    /* ACCORDIONS */
    var accordions = $('.accordion_container');

    if (accordions.length > 0) {
        accordions.find('.accordion_content').hide();

		accordions.find('.drop_arrow').removeClass('up');

        $(".accordion-open").click(function(){
            var elm = $(this)
            var parent = elm.parent();
            var content = parent.find('.accordion_content');
            var arrow = parent.find('.drop_arrow');        
            
            arrow.removeClass('up');
        
            if(content.is(':hidden')) {
                accordions.find('.accordion_content').slideUp();
                arrow.addClass('up');                
                content.slideDown();
            } else {
                accordions.find('.accordion_content').slideUp();
            };
        });
    };   
};

function preSupplierAutoComplete() {
	var preSupplier = $('input#changing_pre_supplier');
	if (preSupplier.hasClass('error')) {		
		$('input#changing_pre_supplier_id').before('<div>Bitte wählen Sie Ihren Versorger aus dem ermittelten Ergebnis aus.</div>');
	}
	preSupplier.autocomplete({
		search: function(event, ui) {
		preSupplier.attr('readonly',true);			
		},
		source: function(request, response) {
			$.get(
				"redaktion/kohana.php/stromissimoenet/preSuppliers/",
				{
					term: encodeURIComponent(request.term)
				},
				function(data){
					preSupplier.removeAttr('readonly');					
					response(data);
				}
			);
		},
		minLength: 3,
		select: function(event, ui) {
			$('input#changing_pre_supplier_id').attr('value',ui.item.evu_nr);
		}		
	});
}

function streetsAutoComplete() {
	var street = $('input#address_street');
	street.autocomplete({
		search: function(event, ui) {
		street.attr('readonly',true);			
		},
		source: function(request, response) {	
			$.get(
				"redaktion/kohana.php/stromissimoenet/streets/",
				{
					 term: encodeURIComponent(request.term),
					 zipCode: $('input#address_zip_code').attr('value')
				},
				function(data){		
					street.removeAttr('readonly');					
					response(data);
				}
			);			
		},
		minLength: 1,
		delay: 150
	});	
}

function citiesAutoComplete() {
	var city = $('input#address_city');
	city.autocomplete({
		search: function(event, ui) {
			city.attr('readonly',true);			
		},
		source: function(request, response) {	
			$.get(
				"redaktion/kohana.php/stromissimoenet/cities/",
				{
					 term: encodeURIComponent(request.term),
					 zipCode: $('input#address_zip_code').attr('value')
				},
				function(data){		
					city.removeAttr('readonly');					
					response(data);
				}
			);			
		},
		minLength: 1,
		delay: 150
	});	
}

$('document').ready(function() {
    initForm();
    inputAutoFill();
    //animateTeaser();
    initAccordion();
    sliderInit();
    $('.jquery-selectbox').each(function(index) {
        $(this).selectbox({listboxMaxSize:30});
    });  
    preSupplierAutoComplete();
    streetsAutoComplete();
    citiesAutoComplete();
    
    if ($('input.autocomplete.error').length) {
    	$('input.autocomplete.error').first().parent().parent().after('<tr><td class="autocomplete-advice" colspan="2"><span>Nicht bekannt? Bitte geben Sie mindestens einen Buchstaben ein und treffen Sie eine Auswahl aus dem Suchergebnis. </span></td></tr>');    	
    } 
    
    if($('.basic_price_description').length) {
      $('.basic_price_description').tooltip({
        bodyHandler: function() {
          return $(this).children('#price_tooltip_content').html();
        }
      });
    }
});

