$(document).ready(function() {
  $("#tilaus_katuosoite").hide()
  $("#tilaus_postinumero").hide()
  $("#tilaus_paikkakunta").hide()
  $("#tilaus_faksinumero").hide()
  
  $("#tilaus_sahkopostilla").attr("checked", "checked")
  
  $("#tilaus_form input[type=text], #sms_form input[type=text]").css("margin-left", "12px")
  $("#tilaus_form input[type=text], #sms_form input[type=text]").css("width", "170px")
  $("#tilaus_form textarea").css("width", "256px")
  $("#tilaus_form textarea").css("height", "70px")
  
  $("#tilaus_sahkopostilla").click(function(e) {
    $("#tilaus_faksinumero").hide()
  })
  $("#tilaus_faksilla").click(function(e) {
    $("#tilaus_faksinumero").show()
  })
  $(".tilaus_posti").click(function(e) {
    var n = $(".tilaus_posti:checked").length
    if(n > 0) {
      $("#tilaus_katuosoite").show()
      $("#tilaus_postinumero").show()
      $("#tilaus_paikkakunta").show()
    } else {
      $("#tilaus_katuosoite").hide()
      $("#tilaus_postinumero").hide()
      $("#tilaus_paikkakunta").hide()
    }
  })
  
  function color_valid(e) {
    e.css({ backgroundColor:"white", border:"1px solid #bbbbbb" });
  }
  
  function color_error(e) {
    e.css({ backgroundColor:"#e99", border:"1px solid #f00" });
  }
  
  function check_hasinput(e) {
    if(e.val() == '') {
      color_error(e)
      return 1
    } else {
      color_valid(e)
      return 0
    }
  }
  
  $("#tilaus_form input[type=text], #sms_form input[type=text]").each(function() {
    color_valid($(this))
    $(this).css("margin-bottom", "3px")
  })
  $("#tilaus_form textarea").each(function() {
    color_valid($(this))
  })
  
  $("#tilaus_form").submit(function() {
    var error = check_hasinput($("#nimi")) + check_hasinput($("#puhelin"))
    
	if(check_hasinput($("#sahkoposti"))===1){
		error += 1;
		
	}
	
     /*if($("input[@name='fdelivery']:checked").val() == "sahkopostilla") {
      error += check_hasinput($("#sahkoposti"))
      color_valid($("#faksi"))
    } else {
      error += check_hasinput($("#faksi"))
      color_valid($("#sahkoposti"))
    }
    
   if($(".tilaus_posti:checked").length > 0) {
      error += check_hasinput($("#osoite")) + check_hasinput($("#postinumero")) + check_hasinput($("#paikkakunta"))
    } else {
      color_valid($("#osoite"))
      color_valid($("#postinumero"))
      color_valid($("#paikkakunta"))
    }*/
    
    /*if($(".tilaus_posti:checked").length == 0 && $(".tilaus_tiedote:checked").length == 0) {
      error += check_hasinput($("#kysymys"))
    } else {
      color_valid($("#kysymys"))
    }*/
    
    if(error > 0) {
      $("#tilaus_form .error").html("Tarkista viel&auml; punaisella merkityt pakolliset kent&auml;t.")
      return false
    }
    return true
  })

  $("#sms_form").submit(function() {
    var error = check_hasinput($("#smsphone"))

    if(error > 0) {
      $("#sms_form .error").html("Tarkista viel&auml; punaisella merkityt pakolliset kent&auml;t.")
      return false
    }
    return true
  })
})

