/*  ==============================================================
||                                                              ||
||    Website gemaakt door / Website created by                 ||
||   _______ _____  _____ ____          _        _   _ _        ||
||  |__   __|  __ \|_   _|  _ \   /\   | |      | \ | | |       ||
||     | |  | |__) | | | | |_) | /  \  | |      |  \| | |       ||
||     | |  |  _  /  | | |  _ < / /\ \ | |      | . ` | |       ||
||     | |  | | \ \ _| |_| |_) / ____ \| |____ _| |\  | |____   ||
||     |_|  |_|  \_\_____|____/_/    \_\______(_)_| \_|______|  ||
||                                                              ||
=============================================================== */

var Website = {
  run: function() {
    this.init();
    this.placeholderInputs();
    this.courseLocations();
    this.registrationForm();
  },
  
  init: function() {
    $('body').removeClass('no-js').addClass('js');
  },
  
  // Course details' locations
  courseLocations: function() {
    if ($("#locations").length > 0) {
    
      // tabs
      var tabContainers = $('#locations .details > div');
      $('#locations .list a').click(function () {
          tabContainers
            .hide()
            .filter(this.hash)
            .fadeIn(200);
          
          $('#locations .list a').removeClass('active');
          $(this).addClass('active');
          
          return false;
      }).filter(':first').click();
      
      // add dashes in dates for ie7, rest of browsers uses :before for that
      $(".ie7 #locations .details dd.date dt").text("- " + $(".ie7 #locations .details dd.date dt").text());
      
      $('#locations .list > ul > li > a').click(function(e){
      	e.preventDefault();
      	$(this).parent().prevAll('li').find('ul').slideUp('fast');
      	$(this).parent().parent().prevAll().children().find('ul').slideUp('fast');
      	$(this).parent().nextAll('li').find('ul').slideUp('fast');
      	$(this).parent().parent().nextAll().children().find('ul').slideUp('fast');
      	$(this).next('ul').slideToggle('fast');
      });
    }
  },
  
  // placeholder text for inputs
  placeholderInputs: function() {
    
    $('input[type=text][title]')
      .live('focus', function(){ // focus for placeholder
        if($(this).val() == $(this).attr("title")) {
          $(this).val('');
        }
        $(this).removeClass("placeholder");
      })
      .live('blur', function() { // blur for placeholder
        if($(this).val().length <= 0) {
          $(this).addClass("placeholder");
          $(this).val($(this).attr("title"));
        }
      })
      .blur(); // fire blur at the begining to set everything up
	  
      $('input[type=text][title]').parents('form').submit(function(e) {
			$(this).find('.placeholder').each(function() {
				var input = $(this);
				if (input.val() == input.attr('title')) {
					input.val('');
				}
			})
		});
  },
  
  // Course registration form
  registrationForm: function() {
    if ( $("#registration-form").length > 0) {
      
      // selecting course
      /*$("#registration-course, #registration-location")
        .live("change", function() {
          var course = $("#registration-course").val();
		  var location= $("#registration-location").val();
		  var date= $("#registration-date").val();
		  var courseContainer = $("#select-course");
		  
		  var isWritten = $('#registration-course option:selected:contains("schriftelijk")');
		  if(isWritten.length > 0){
			isWritten = 'true';
		  } else {
			isWritten = 'false';
		  }
		  courseContainer.load("/registratie #select-course", {'course':course, 'location':location, 'date':date, 'written':isWritten}); // using POST!
        })
        .change();*/
      
      // adding new student to the form
      var studentData = $("#course-students > div.student").clone(true, true); // cached copy of student fields
      studentData.find("input, select").attr("rel", "optional"); // set all fields as optional
      var studentCount = 1;
      
      $("#add-new-student").click(function() { // student addition
        var newStudent = studentData.clone(true, true); // duplicate cached fields
        studentCount++;
        newStudent.find("[id]").each(function() { // correct ids
          $(this).attr("id", $(this).attr("id") + "-" + studentCount);
        });
        newStudent.find("[for]").each(function() { // correct names
          $(this).attr("for", $(this).attr("for") + "-" + studentCount);
        });
        newStudent.find("[name='student-sex-1']").each(function() { // correct names
          $(this).attr("name", "student-sex-" + studentCount);
        });
        newStudent.find("input[type=text][title]").blur(); // fire blur to add placeholders
        $(this).parent().before(newStudent); // append new student fields

        return false;
      });

      // invoice reciever
      $('input[name="invoice"]').change(function(){
        $('#contact-company, #contact-student').hide(); //hide both
        if ($('input[name="invoice"]:checked').val() == "company")
          $('#contact-company').show(); //show company fields
        else if ($('input[name="invoice"]:checked').val() == "student")
          $('#contact-student').show(); //show person fields
      }).change();
      
      //RSz this.fieldsValidation();
      
      this.studentsSelects();
      
    }
  },
  
  // validating form fields
  fieldsValidation: function() {
  
    // error message to be displayed in case of any validation issues
    var errorDiv = $('<div class="errors">De velden met <img src="images/form-error.png" alt="X" /> zijn niet of niet correct ingevoerd</div>');
    
    $("#registration-form").submit(function() {
       // reset form validation
      $("div.errors").remove();
      $("#registration-form div, #registration-form input, #registration-form select").removeClass("invalid");
      
      var errors = false;
      
      // chceck if inputs are filled (not checking students added with JS)
      $("input[type='text']:not([rel='optional']):visible").each(function(){
        if ($(this).val() == "" || $(this).val() == $(this).attr("title")) {
          errors = true;
          $(this).addClass("invalid");
          $(this).parent().addClass("invalid");
        }
      });
      
      // chceck if emails are valid
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      $("input[type='text'][id*='email']:not([rel='optional']):visible").each(function(){
        if(reg.test($(this).val()) == false) {
          errors = true;
          $(this).addClass("invalid");
          $(this).parent().addClass("invalid");
        }
      });
      
      // check if radio button are checked
      var radios = $("input:radio:not([rel='optional']):visible");
      radios.each(function(){
        if(radios.filter("[name=" + $(this).attr("name") + "]:checked").length == 0) {
          errors = true;
          $(this).parent().parent().addClass("invalid");
        }
      });
      
      // check if seletcs are selecte
      $("select:not([rel='optional']):visible").each(function(){
        if ($(this).attr("selectedIndex") == 0) {
          errors = true;
          $(this).addClass("invalid");
          $(this).parent().addClass("invalid");
        }
      });
      
      // check agreement checkbox
      if ($("#registration-acceptance:checked").length == 0) {
        errors = true;
        $("#registration-acceptance").addClass("invalid");
        $("#registration-acceptance").parent().addClass("invalid");
      }
      
      // if there were errors, show the messages
      if (errors) {
        $("#registration-form").append(errorDiv.clone()).prepend(errorDiv.clone());
        $("div.errors").hide().show();
        return false;
      }
    });
  },
  
  // managing students selects
  studentsSelects: function() {
  
    // update select lists
    $("select[id*='-choose-contact']").focus(function(){
      $(this).find("option[value!=0]").remove(); // clear selects
      var select = $(this); // cache elect
      $(".student").each(function() {
        var index = $(".student").index($(this)) + 1;
        var name = $(this).find("[id*='first-name']:eq(0)").val();
        var middlename = $(this).find("[id*='middle-name']:eq(0)").val();
		if (middlename == $(this).find("[id*='middle-name']:eq(0)").attr('title')){
			middlename = '';
		}
		if (middlename.length > 0) {
			middlename += " ";
		}
        var surname = $(this).find("[id*='last-name']:eq(0)").val();
        var nameTitle = $(this).find("[id*='first-name']:eq(0)").attr("title");
        var surnameTitle = $(this).find("[id*='last-name']:eq(0)").attr("title");
        if (name != nameTitle && surname != surnameTitle) { // check if name and surname are diffrent than placeholder
          $(select).append('<option value="' + index + '">' + name + ' ' + middlename + surname + '</option>');
        }
      });
    });
    
    // update fields on change
    $("select[id*='-choose-contact']").change(function(){
      if ($(this).attr("selectedIndex") != 0) {
        // cache elements
        var c = $($(this).parent().parent());
        var s = $($(".student").get($(this).find("option:selected").val() - 1));
        
        // assign values to fields
        if (s.find("[id*='sex']:checked").length > 0) {
          if (s.find("[id*='female']:checked").length > 0) {
            c.find("[id*='female']").attr("checked", "checked");
          } else {
            c.find("[id*='sex-male']").attr("checked", "checked");
          }
        }
        c.find("[id*='first-name']").val( s.find("[id*='first-name']").val() );
        c.find("[id*='middle-name']").val( s.find("[id*='middle-name']").val() );
        c.find("[id*='last-name']").val( s.find("[id*='last-name']").val() );
        c.find("[id*='email']").val( s.find("[id*='email']").val() );
        c.find("[id*='phone']").val( s.find("[id*='phone']").val() );
        
        c.find("input[title]").focus().blur(); // regresh placeholders
      }
    });
    
  }
};

$(function() {
  Website.run();
});
