;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
  alert('schools requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
  return;
}

})(jQuery);

$(function(){

// Prevent ajax caching. (Bug in IE caching)
$.ajaxSetup({
  cache: false
});

// Add time pickers
$(".datetime").datepicker({
	  duration: '',
	  showTime: true,
	  constrainInput: false,
	  stepMinutes: 1,
	  stepHours: 1,
	  altTimeField: '',
	  time24h: false,
    onClose: function() {
      $(this).change();
    }
});
$(".date").datepicker({duration: ''}); 
$(".time").timepickr({convention: 12}); 

// Busy dialog
$('#container')
    .ajaxStart(function() {$(this).block({ message: '<p><img src="/img/spinner.gif" />Busy, please wait...</p>' });})
    .ajaxStop(function() {$(this).unblock();});

// Submit button action
$('#mainbutton').bind('click', function() {saveSchools();});

// Bulk action check all box
$("#bulkCheckbox").click(function() {
  $('input:checkbox.school')
      .attr('checked', $(this).attr('checked'))
      .change();
});

$("#bulkAction").change(function() {
   var bulkAction = $(this).val();
  // Bulk action button
  $.each(config.schools, function(id, school) {
    if (school.bulk) {
      var option = $("#g" + id + "_School_Status :options[text='" + bulkAction + "']");
      $("#g" + id + "_School_Status")
          .val(option.val())
          .change();
    }
  });

  $(this).val("");
});

$("#bulkActionTxt").keyup(function() {
   var bulkActionTxt = $(this).val();
  // Bulk action button
  $.each(config.schools, function(id, school) {
    if (school.bulk) {
       var txt = $("#g" + id + "_Details").val(bulkActionTxt);
      $("#g" + id + "_Details").val(txt.val()).change();
    }
  });

//  $(this).val("");
});

// Load all schools.
loadSchools();

});

// Get survey by id.
function getForm(id) {
  if (!config.forms[id]) {

    $.ajax({
      async: false,
      dataType: "json",
      url: "/go/survey/" + config.site + "/" + id + "/?contenttype=application/json",
      success: function(data) {
        var survey = data.page.survey;
        config.forms[survey.id] = survey;
      }
    });
  }

  return config.forms[id];
}

// Loads all schools.
function loadSchools() {
  $.each(config.schools, function(id) {
    loadSchool(id);
  });
}

// Loads one school by document id.
function loadSchool(id) {
  $.getJSON("/go/doc/" + config.site + "/" + id + "/?contentType=application/json", 
    function(data) {
      var doc = data.page.document.id;
      var x = $("<div/>").html(data.page.document.content);

      var school = eval('(' + x.find('#json').text() + ')');
      config.schools[id] = school;

      var survey = getForm(school.id);
      $.each(survey.question_list, function(key, question) {
        var n = "#g" + doc + "_" + question.text.replace(/ /g, "_");

        switch (question.text) {
        case 'School Status' :
          $(n).empty();
          $.each(question.answers, function(key, answer) {
            $(n).append('<option value="' + answer.id + '">' + answer.text + '</option>');
          });
          break;
        }
      });

      var row = $("#g" + doc + "_row");

      $.each(school.fields, function(key, field) {
        var n = "#g" + doc + "_" + this.name.replace(/ /g, "_");

        switch (field.name) {
        case 'Region' :
        case 'School Name' :
          $(n).text(field.value[0].value);
          $(n + '_id').val(field.value[0].id);
          break;
        case 'Staff' :
        case 'Student' :
        case 'Details' :
        case 'Chyron' :
          $(n).val(field.value);
          $(n). change(function() {
            if (field.value != $(this).val()) {
              field.value = $(this).val();
              school.changed = true;
              row.addClass("changed");
            }
          }).change();
          break;
        case 'School Status' :
          $(n).val(field.value[0].id);
          $(n).change(function() {
            row.removeClass("Status_" + field.value[0].value.replace(/ /g, "_"));
            if (field.value[0].id != $(this).val()) {
              field.value[0].id = $(this).val();
              field.value[0].value = $(this).children(':selected').text();
              school.changed = true;
              row.addClass("changed");
            }
            row.addClass("Status_" + field.value[0].value.replace(/ /g, "_"));
          }).change();
          break;
        }

      });

      $("#g" + doc + "_updated").text(data.page.document.formatted_post_date);
      $("#g" + doc + "_bulk").change(function() {
        school.bulk = $(this).is(':checked');
      }).change();   

      school.changed = false;
      row.removeClass("changed");

  });
}

// Submit all changed schools
function saveSchools() {
  $.each(config.schools, function(id, school) {
    if (school.changed) {
      saveSchool(id);
    }
  });
}

// Submit single school by id.
function saveSchool(id) {
  var school = config.schools[id];
  var data = {surveyID: school.id, isValidSubmission: 1};
  var chyronText = "";


  $.each(school.fields, function(k, field) {
    switch(field.type) {
    case 'radio':
    case 'checkbox':
    case 'select':
       data["q" + field.id] = field.value[0].id;
       break;
    default:
       data["x" + field.id] = field.value;
    }
  });

  $.post("/go/insertsurvey/" + config.site + "/", data, function() {
    loadSchool(id);
  });
}

