$(document).ready(function(){
  $(".findMySchoolLink").live('click', function() {
    $.fancybox({
      'width'  : '65%',
      'height' : '85%',
      'type'   : 'iframe',
      'href'   : $(this).attr('href')
    });
    return false;
  });
});

$().ready(function()
{
  $("#cb_greetingeditor").charCounter(1000);
  $("#password").val("");
  if ($('input[name=newUsertype]:checked').val() == 'Parent') {
    parentClick('docready');
  } else if ( $('input[name=newUsertype]:checked').val() == 'Teacher' ) {
    teacherClick('docready');
  }
  $('#username').click(
    function()
    {
      $("#userNameAvailability").html('');
    });
  $('#newUsername').click(
    function()
    {
      $("#userNameAvailability").html('');
    });
});

$().ready(function()
{
  // autopopulate the form on dev
  try{
    var runon = [ 'lcl.spellingcity.com', 'dev.spellingcity.com' ];
    if( runon.indexOf( window.location.hostname ) >= 0 ) autopopulate();
  } catch(err){}

  $("#schoolSearch").keypress(
    function( e )
    {
      if (checkEnter(e))
      {
        doSearch();
      }
    }
    );

  $("#registrationForm").validate(
  {
    errorClass: "cart_error",

    submitHandler: function(form) {
      stripHTML();
      $(window).unbind('unload');
      form.submit();
    },
    rules: {
      firstname: {
        required:true,
        alphanumeric:true
      },
      lastname: {
        required:true,
        alphanumeric:true
      },
      password: {
        required:true,
        minlength:6,
        alphanumeric:true
      },
      verifyEmail: {
        required: true,
        equalTo: "#email"
      },
      newUsertype: {
        required: true
      },
      schoolName: {
        required: function (element)
        {
          return checkSchoolAddressRequired();
        },
        minlength: function (element)
        {
          return checkIfLengthRequired(2);
        }
      },
      schoolStreetAddress: {
        required: function (element)
        {
          return checkSchoolAddressRequired();
        },
        minlength:function (element)
        {
          return checkIfLengthRequired(5);
        }
      },
      schoolCity: {
        required: function (element)
        {
          return checkSchoolAddressRequired();
        },
        minlength:function (element)
        {
          return checkIfLengthRequired(2);
        }
      },
      schoolState: {
        required: function (element)
        {
          return checkSchoolAddressRequired();
        },
        minlength:function (element)
        {
          return checkIfLengthRequired(2);
        }
      },
      schoolZip: {
        required: function (element)
        {
          return checkSchoolAddressRequired();
        },
        minlength:function (element)
        {
          return checkIfLengthRequired(3);
        }
      },
      schoolCountry: {
        required: function (element)
        {
          return checkSchoolAddressRequired();
        },
        minlength:function (element)
        {
          return checkIfLengthRequired(2);
        }
      },
      homeschool_parent : {
        required: function (element)
        {
          if ($('input[name=newUsertype]:checked').val() == 'Parent') {
            return true;
          } else {
            return false;
          }
        }
      },
      parent_cb_school: {
        required: function (element)
        {
          if ($('input[name=newUsertype]:checked').val() == 'Parent') {
            if ($('input[name=homeschool_parent]:checked').val() == '0') {
              // form get passed
              return false;
            } else if ($('input[name=homeschool_parent]:checked').val() == '1') {
              // form get passed
              return false;
            } else {
              // form does not get passed alert error
              return true;
            }
          } else {
            return false;
          }
        }
      },
      teacher_cb_school: {
        required: function (element)
        {
          if ($('input[name=newUsertype]:checked').val() == 'Teacher') {
              if ($('#cantFindSchoolFlag').val() == 1)
                return false;
              else
                return true;
          } else {
            return false;
          }
        }
      },
      username: {
        required: true,
        minlength: 5,
        alphanumeric:true,
        remote: "/index.php?option=com_students&controller=students&task=checkUser"
      },
      email: {
        required: true,
        email: true,
        remote: "/index.php?option=com_students&controller=students&task=checkUser"
      },
      termsAgree: {
        required: true
      }
    },
    messages: {
      firstname: {
        required: "Please enter your first name",
        alphanumeric: "Letters, numbers or underscores only please"
      },
      lastname: {
        required: "Please enter your last name",
        alphanumeric: "Letters, numbers or underscores only please"
      },
      username: {
        required: "Please enter a username",
        minlength: "Your username must consist of at least 5 characters",
        remote: jQuery.format("{0} is already in use, please pick a different username"),
        alphanumeric: "Only letters or numbers are allowed (no spaces or punctuation)."
      },
      password: {
        required: "Please enter a password",
        minlength: "Password must consist of at least 6 characters",
        alphanumeric: "Only letters or numbers are allowed (no spaces or punctuation)."
      },
      verifyEmail: {
        equalTo: "Please enter the same email as above"
      },
      email: {
        required: "Please enter a valid email address",
        remote: jQuery.format("{0} is already in use")
      }
    },
    errorPlacement: function(error, element) {
      if (element.attr("name") == "newUsertype")
        $("#parentTeacher").css("border", "2px solid red");
      else if (element.attr("name") == "homeschool_parent")
        $("#parentDiv").css("border", "2px solid red");
      else if (element.attr("name") == "parent_cb_school")
        $("#parentDiv").css("border", "2px solid red");
      else if (element.attr("name") == "student_cb_school")
        $("#studentDiv").css("border", "2px solid red");
      else if (element.attr("name") == "teacher_cb_school")
        $("#teacherDiv").css("border", "2px solid red");
      else if (element.attr("name") == "termsAgree")
        $("#termsAgreeCell").css("border", "2px solid red");
      else
        error.appendTo( element.parent() );
    }

  }); // end of registration form validation
  
}); // end of ready function

function checkSchoolAddressRequired()
{
  if ($('(#cantFindSchool').is(":hidden"))
  {
    $('#cantFindSchoolFlag').val(0);
    return false;
  }
  else
  {
    $('#cantFindSchoolFlag').val(1);
    return true;
  }
}

function checkIfLengthRequired(length)
{
  if ($('(#cantFindSchool').is(":hidden"))
  {
    return 0;
  }
  else
  {
    return length;
  }
}

function getCity()
{
  $('#loadingInformation').show();
  $('#schoolCityDDL').load("components/com_spellcity/findSchool.php",
  {
    city:"true",
    searchTerm:$('#schoolSearch').val(),
    zipSearchTerm:$('#zipSearch').val()
  },
  function()
  {
    $('#loadingInformation').hide();
    $('#schoolCityWrapper').show();
  }
  );
}

function getSchoolByCity(selectionList)
{
  $('#loadingInformation').show();
  $('#schoolResultsTable').load("components/com_spellcity/findSchool.php",
  {
    filterBy:$('#schoolCityList').val(),
    searchTerm:$('#schoolSearch').val()
  },
  function()
  {
    $('#loadingInformation').hide();
    $('#schoolResultsTable').show();
    $('#schoolResultsButtons').show();
  }
  );
}

function hideSearch()
{
  $('#schoolCityWrapper').hide();
  $('#schoolResultsTable').hide();
  $('#schoolResultsButtons').hide();
  $('#loadingInformation').hide();
  $('#dialog_search').hide();
  $('#selectedSchoolInformation').show();
}


function showSearch ()
{
  $('#dialog_search').show();
  $('#cantFindSchool').hide();
  $('#selectedSchoolInformation').hide();
  $('#cantFindSchoolFlag').val('');
}

function doSearch()
{
  if ($('#schoolSearch').val().length < 3 && $('#zipSearch').val().length == 0 )
  {
    alert('Please enter at least 3 characters to search for your school.');
    $('#schoolSearch').focus();
  }
  else
  {
    getCity();
  }

}

function checkEnter(e) //e is event object passed from function invocation
{
  var characterCode; // literal character code will be stored in this variable
  if (e && e.which) //if which property of event object is supported (NN4)
  {
    e = e;
    characterCode = e.which; //character code is contained in NN4 which property
  }
  else
  {
    e = event;
    characterCode = e.keyCode; //character code is contained in IE keyCode property
  }
  if (characterCode == 13) //if generated character code is equal to ascii 13 (if enter key)
  {
    return true;
  }
  else
  {
    return false;
  }

}

function getSchoolDataFromRow(refObject,schoolId)
{
  var selectedSchool = "<br>";
  $(refObject).parents('tr').find('td').each(
    function(i)
    {
      cellText = $(this).text();
      if (i == 0) // school name
      {
        selectedSchool = selectedSchool + cellText + '<br>';
      }
      if (i == 1) // school address
      {
        selectedSchool = selectedSchool + cellText + '<br>';
      }
      if (i == 2) // city
      {
        selectedSchool = selectedSchool + cellText + ', ';
      }
      if (i == 3) // state
      {
        selectedSchool = selectedSchool + cellText + '  ';
      }
      if (i == 4) // zip
      {
        selectedSchool = selectedSchool + cellText + '<br>';
      }
      if (i == 5) // country
      {
        selectedSchool = selectedSchool + cellText;
      }
    });
  $('#cb_school').val(schoolId);
  $('#cantFindSchool').hide();
  $('#selectedSchoolInformation').html(selectedSchool);
  $('#dialog_search').hide();
  $('#selectedSchoolInformation').show();
  $('#findMySchoolLink').show();
  $('#cantFindSchoolFlag').val('');
}

function checkAvailability()
{
  userNameValue = $('#username').val();
  if (userNameValue.length > 4)
  {
    $('#userNameAvailability').load("/index.php?option=com_students&controller=students&task=checkUser", {
      getoptions:userNameValue
    }, function() {
      $('#userNameAvailability').show();
    });
  }
  else
  {
    alert('Username must be at least 5 characters long.');
  }
}

function selectUserNametoForm(selectedUserName)
{
  // username exists on both registration page and edit profile page
  $('#username').val(selectedUserName);
  $('#newUsername').val(selectedUserName); // new user name only exists on the edit profile page
  $('#userNameAvailability').hide();
  $("label[for='username']").hide(); // registration page
  $("label[for='newUsername']").hide(); // edit page
  $('#username').removeClass('cart_error'); // registration page
  $('#newUsername').removeClass('cart_error'); // edit page
}

function stripHTML()
{
  var greetings = $('#cb_greetingeditor').val();
  var noHtml = greetings.replace(/(<([^>]+)>)/ig,"");
  $('#cb_greetingeditor').val(noHtml);
}

function hideSearch () {
  $('#dialog_search').hide();
}

function parentTeacherClick() {
  $("#parentTeacher").css("border", "2px solid white");
}

function parentHomeSchoolClick() {
  if ($('input[name=homeschool_parent]:checked').val() == '0') {
    $('#parentSelected').show();
  } else {
    $('#parentSelected').hide();
    hideCantFindSchool();
  }
  $("#parentDiv").css("border", "2px solid white");
}

function parentFindSchoolClick() {
  if ($('input[name=homeschool_parent_find]:checked').val() == '0') {
    $('#parentSelectedSchoolInformation').hide();
  } else if ($('input[name=homeschool_parent_find]:checked').val() == '1') {
    $('#parentSelectedSchoolInformation').show();
  }
}

function teacherSchoolClick() {
  if ($('input[name=teacher_school]:checked').val() == '1') {
    $('#teacherSelectedSchoolInformation').show();
  } else {
    $('#teacherSelectedSchoolInformation').hide();
    hideCantFindSchool();
  }
  $("#teacherDiv").css("border", "2px solid white");
}

function studentHomeSchoolClick() {
  if ($('input[name=homeschool_student]:checked').val() == '0') {
    $('#studentSelectedSchoolInformation').show();
  } else {
    $('#studentSelectedSchoolInformation').hide();
    hideCantFindSchool();
  }
  $("#studentDiv").css("border", "2px solid white");
}

function parentClick(state) {
  var school_id;
  
  if (state != 'docready') {
    hideCantFindSchool();
  }
  $('#teacherDiv').hide();
  $('#cb_usertype').val("Parent");
  $('#studentDiv').hide();
  $('#parentDiv').show();
  $('#parentSelected').hide();
  parentHomeSchoolClick();
  parentTeacherClick();
  parentFindSchoolClick();
  if ($('#teacher_cb_school').val()) {
    school_id = $('#teacher_cb_school').val();
    $('#parent_cb_school').val(school_id);
    $('#teacher_cb_school').val('');
  }
}

function teacherClick(state) {
  
  var school_id;
  
  if (state != 'docready') {
    hideCantFindSchool();
  }
  $('#teacherDiv').show();
  $('#cb_usertype').val("Teacher");
  $('#parentDiv').hide();
  $('#studentDiv').hide();
  parentTeacherClick();
  if ($('#parent_cb_school').val()) {
    school_id = $('#parent_cb_school').val();
    $('#teacher_cb_school').val(school_id);
    $('#parent_cb_school').val('');
  }
}

function cantFindSchool()
{
  $('#cantFindSchoolFlag').val('1');
  $('#cantFindSchool').show();
  $('#dialog_search').hide();
}

function hideCantFindSchool() {
  $('#cantFindSchool').hide();
  $('#cantFindSchoolFlag').val('0');
}

function parentSchoolClick() {
  $('#parentDiv').show();
  $("#parent_home_schooler_no").attr("checked", true);
}

function studentSchoolClick() {
  $('#studentDiv').show();
  $("#student_home_schooler_no").attr("checked", true);
}

function randstr()
{
  var text = '';
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for( var i=0; i<5; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length));
  return text;
}
function autopopulate()
{
  //bust
  // auto populate the form for dev purposes
  $("#registrationForm").find('input:text[name="firstname"]').val('test123');
  $("#registrationForm").find('input:text[name="lastname"]').val('test123');
  $("#registrationForm").find('input:hidden[name="password__verify"]').val('test123');
  $("#registrationForm").find('input:password[name="password"]').val('test123');
  $("#registrationForm").find('input:text[name="password__verify"]').val('test123');
  $("#registrationForm").find('input:text[name="username"]').val('test'+randstr());
  $("#registrationForm").find('input:text[name="email"],input:text[name="verifyEmail"]').val( 'test'+randstr()+'@test.com' );
//$("#parentUserType").click();
}

function saveBeforeFindSchool ()
{
  $.post("index.php?option=com_comprofiler&task=saveLoginInfo",
  {
    First_Name:$('#firstname').val(),
    Last_Name:$('#lastname').val(),
    Username:$('#username').val(),
    Email:$('#email').val(),
    Verify_Email:$('#verifyEmail').val(),
    Password:$('#password').val()
  }
  );
}

function clearTerms()
{
  $('#termsAgreeCell').css("border", "#FFFFFF");
}

