/*global $, $F, $$, Ajax, Form, window, Effect, alert, prompt, confirm */

function create_new_course_type(auth_token) {
   var name = prompt("New course type name: ");
   //spinner
   var req = new Ajax.Request("/course_types/create/", {
      method: "POST", 
      parameters: {"course_type[name]": name, authenticity_token: auth_token},
      evalScripts: true,
      onSuccess: function(res) {
         var course_type = eval('(' + res.responseText + ')');
         var select_box = $('course_course_type_id');
         select_box.insert("<option value=\"" + course_type.id + "\">" + course_type.name + "</option>");
         select_box.value = course_type.id;
      },
      onFailure: function() {
         alert("Failed to create course.");
      }
   });
}


function create_new_certification_type(select_item) {
   var cert_type = prompt("New certification name: ");
   select_item.insert("<option value=\"" + cert_type + "\">" + cert_type + "</option>");
   select_item.value = cert_type;
}

function choose_cert(select_item){
   if(select_item.value === "Other"){
      create_new_certification_type(select_item);
   }
}

function click_optional(checkbox) {
   if (checkbox.checked) {
      checkbox.up().down('.optional_info').show();
      checkbox.up().down('.optional_data').value = 1;
   } else {
      checkbox.up().down('.optional_info').hide();
      checkbox.up().down('.optional_data').value = 0;
   }
}

function display_other(select_tag, other_id) {
   if (select_tag.value === "Other") {
      $(other_id).show();
   } else {
      $(other_id).hide();
   }
}


function check_hidden(checkbox, check_value_class) {
   if (checkbox.checked) {
      checkbox.up().down(check_value_class).value = 1;
   } else {
      checkbox.up().down(check_value_class).value = 0;
   }
}

function check_training_site(checkbox) {
   if (checkbox.checked) {
      $('course_type').show();
   } else {
      $('course_type').hide();
   }
}

function clear_payment_contact() {
   $("facility").options.length = 0;
   $("facility").value = "";
   $("department").options.length = 0;
   $("department").value = "";
   $("payment_contact_display").innerHTML = "";
   $("payment_contact_id").value = "";
}

function set_payment_contact(payment_contact) {
   $("payment_contact_display").innerHTML = "Contact: " + payment_contact.name;
   $("payment_contact_id").value = payment_contact.id;
}

function select_department(select) {
   var request = new Ajax.Request("/public/course/determine_payment_contact", {
      parameters: {
         department: select.value,
         facility: $('facility').value,
         organization: $("organization").value
      },
      onFailure: function() {
         alert("something went wrong");
      },
      onSuccess: function (transport) {
         var result = transport.responseJSON;
         set_payment_contact(result.payment_contact);         
      }
   });
}

function select_facility(select) {
   var request = new Ajax.Request("/public/course/departments_for_facility", {
      parameters: {
         facility: select.value,
         organization: $("organization").value
      },
      onFailure: function() {
         alert("something went wrong");
      },
      onSuccess: function (transport) {
         var result = transport.responseJSON;
         var department_select = $("department");
         if (result.departments) {
            department_select.enable();
            department_select = $("department");
            department_select.options.length = 0;
            
            result.departments.each(function(department){
               department_select.options[department_select.length] = new Option(department, department);
            });
            set_payment_contact(result.payment_contact);
         } else {
            var pc = result.payment_contact;

            department_select.options.length = 0;
            var department = pc.department === null ? "" : pc.department;
            department_select.options[0] = new Option(department, department);
            department_select.disable();
            set_payment_contact(pc);         
         }
      }
   });
}

function select_organization(select) {
   if (select.value === "-1" ) { //Not listed
      $('unlisted_payer').show();
      $('listed_payer').hide();
      clear_payment_contact();
      $('payment_contact_id').value = "-1";
   } else if(select.value === "cc" || select.value === "") {
      $('unlisted_payer').hide();
      $('listed_payer').hide();
      clear_payment_contact();
      if(select.value === "cc") {
         $('payment_contact_id').value = "cc";
      }
   } else {
      $('unlisted_payer').hide();
      $('listed_payer').show();
      var request = new Ajax.Request("/public/course/facilities_for_organization", {
         parameters: {
            organization: select.value
         },
         onFailure: function() {
            alert("something went wrong");
         },
         onSuccess: function (transport) {
            var result = transport.responseJSON;
            var facility_select = $("facility");
            var facility = "";

            if (result.payment_contact) {
               var pc = result.payment_contact;
               facility_select.options.length = 0;
               facility = pc.facility === null ? "" : pc.facility;
               facility_select.options[0] = new Option(facility, facility);
               facility_select.disable();

               var department_select = $("department");
               department_select.options.length = 0;
               var department = pc.department === null ? "" : pc.department;
               department_select.options[0] = new Option(department, department);
               department_select.disable();

               set_payment_contact(pc);
            }
            else {
               facility_select.enable();
               var facilities = result.facilities;
               facility_select.options.length = 0;

               facilities.each(function(facility) {
                  facility_select.options[facility_select.length] = new Option(facility, facility);
               });
               
               select_facility(facility_select);
            }
         }
      });
   }
}





function deny_instructor_request(form) {
   var message = prompt("Please provide an explanation for denial.", "An instructor has already been assigned to this station.");
   if (message === null ) {
     return false;
   } else {
     form.explanation.value = message;
     return true;
   }
}

function reload_roster_list(offering_id, token){
   var upd = new Ajax.Updater("roster_list", "/offerings/roster/" + offering_id, {
      parameters: {partial: true, authenticity_token: token}
   });
}

function choose_number_of_days_for_course(select, url, form_authenticity_token) {
   if (select.options[select.selectedIndex].value === "")
   {
      return;
   }
   else if (select.options[select.selectedIndex].value === 'Other...') 
   {
      var count = prompt('How Many?');
      if (count === null) {
         return;
      }
      if (count > 100) {
         count = 100;
      }
      select.options[select.options.length - 2] = new Option(count, count);
      select.selectedIndex = select.options.length - 2;
   }
   var upd = new Ajax.Updater('courseSkills', url, {
      parameters: Form.serialize(select.form) + '&authenticity_token=' + form_authenticity_token
   });
}

function populate_instructor_opportunity_courses() {
   var course_popup = $('instructorCourseFilterPopup');
   course_popup.disabled = true;

   var submit = $('opportunity_submit_button');
   submit.disable = true;
   
   if ($F('year') !== "" && $F('month') !== "") {
      var values = $('opportunity_filter_form').serialize();
      var req = new Ajax.Request("/instructor/course_filter_options", {
         parameters: values,
         onSuccess: function (transport) {
            var options = eval('(' + transport.responseText + ')');
            course_popup.options.length = 0;
            options.each(function (x) {
               course_popup.options[course_popup.options.length] = new Option(x[0], x[1]);
            });
            course_popup.disabled = false;
            submit.disabled = false;
         }
      });
   }

}

function edit_qualification_date(id, date, authenticity_token) {
   var response = prompt("Please enter a new date for this qualification.", date);
   if (response !== null && response.length > 0)
   {
      var upd = new Ajax.Updater("staffQualifications", "/staff/update_qual", {
         parameters: {
            id: id,
            date: response,
            authenticity_token: authenticity_token
         }
      });
   }
}

function populate_day_popup() {
    var days = 0;
    var year = parseInt($F("year"), 10);
    var leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    var month = 0;
    var i;
    
    switch($F("month")) {
        case "All": 
            days = 0;
            break;
            
        case "January":
            month = 0;
            days = 31;
            break;
            
        case "February": 
            month = 1;
            days = (leap ? 29 : 28); 
            break;
            
        case "March":
            month = 2;
            days = 31;
            break;
            
        case "April":
            month = 3;
            days = 30;
            break;
            
        case "May":
            month = 4;
            days = 31;
            break;
            
        case "June":
            month = 5;
            days = 30;
            break;
            
        case "July":
            month = 6;
            days = 31;
            break;
            
        case "August":
            month = 7;
            days = 31;
            break;
            
        case "September":
            month = 8;
            days = 30;
            break;
            
        case "October":
            month = 9;
            days = 31;
            break;

        case "November":
            month = 10;
            days = 30;
            break;

        case "December":
            month = 11;
            days = 31;
            break;
    }
    
    if (days > 0) {
        // find the sundays
        var first_date = new Date(year, month, 1);
        
        var day_of_week = first_date.getDay();
        var first_sunday = 1;
        if (day_of_week >= 1) {
           first_sunday = 8 - day_of_week; 
        }
        first_date.setDate(first_sunday);
        
        // build the week pop-up
        var old = $F("week");
        $("week").options.length = 0;
        $("week").options[0] = new Option("All");
        while (first_date.getMonth() === month) {
            $("week").options[$("week").options.length] = new Option("Week of " + $F("month") + " " + first_date.getDate(), first_date.getDate());
            if (old === first_date.getDate().toString()) {
               $("week").selectedIndex = $("week").options.length - 1;
            }
            first_date.setDate(first_date.getDate() + 7);
        }
    } else {
       $("week").options.length = 0;
       $("week").options[0] = new Option("All");
    }
    
    // build the day pop-up
    var selected_day = parseInt($F("day"), 10);
    $("day").options.length = 0;
    $("day").options[0] = new Option("All");
    
    if ($F("week") !== "All") {
        var start = parseInt($F("week"), 10);
        var end = start + 6;
        if (end > days) {
           end = days;
        }
        
        for (i = start; i <= end; i++) {
            $("day").options[$("day").options.length] = new Option(i.toString());
            if (i === selected_day) {
               $("day").options.selectedIndex = $("day").options.length - 1;
            }
        }
    }
    else {
        for (i = 1; i <= days; i++) {
            $("day").options[i] = new Option(i.toString());
            if (i.toString() === selected_day) {
               $("day").options.selectedIndex = i;
            }
        }
    }
}

function delete_offering(id, dbl) {
   var yes = confirm("Are you sure you want to delete this offering? Once its gone, its gone for good.");
   if (yes) {
      if (dbl) {
         yes = confirm("This offering has enrolled students and/or assigned instructors. They WILL NOT BE NOTIFIED. Are you sure?");
      }
   }
   if (yes) {
      location.href = "/offerings/delete?id=" + id;
   }
}


function file_upload_button(id, js) {
   $(id).innerHTML = js;
}

function submit_offering_role(form) {
   form.up('TD').removeClassName('dirty');
   if($$('.dirty').length === 0) {
      window.onbeforeunload = null;
   }
}

function mark_offering_role_dirty(role_id) {
   $('form_' + role_id).up('TD').addClassName('dirty');
   window.onbeforeunload = function(){
     return "You have made changes on this page.";  
   };
}

function submit_offering_form(form) {
   var iframe = document.createElement('iframe');
   iframe.setAttribute("id", form.id + '_iframe');
   iframe.setAttribute("name", iframe.id);
   document.body.appendChild(iframe);
   form.target = iframe.id;
   
   $(iframe).observe("load",function(){
      document.body.removeChild(iframe);
   });
   return true;
}

// Either course_id or offering_id can be used for value list.
// id is the 
function load_value_list(value_list, dependent_id, auth_token) {
   var popup = $(value_list);

   Form.Element.disable(popup);
   var req = new Ajax.Request("/offerings/load_value_list", {
      method: 'post',
      parameters: {
         value_list: value_list,
         dependent_id: dependent_id,
         authenticity_token: auth_token
      },
      onSuccess: function(transport) {
         var result = transport.responseJSON;
         while (popup.options.length) {
            popup.remove(0);
         }
         result.each(function(item){
            popup.options.add(new Option(item.name, item.id));
         });
         Form.Element.enable(popup);
         if(value_list === 'courses'){
            load_value_list('offerings', popup.value, auth_token);
         }
      }
   });
}

function load_courses_value_list(id, auth_token) {
   load_value_list('courses', id, auth_token);
   Form.Element.disable($('offerings'));
}

function duplicate_offering(offering_id, auth_token) {
   var initial_date = prompt("Please enter the start date of your new offering.\n eg. (MM/DD/YYYY)", "");
   if(initial_date !== null && initial_date !== '') {
      window.location.href = "/offerings/duplicate/" + offering_id + "?initial_date=" + initial_date + "&authenticity_token=" + auth_token;
   }
}

function edit_offering_details(offering_id, auth_token) {
   var req = new Ajax.Request("/offerings/edit/" + offering_id, {
      method: 'post',
      parameters: {
         authenticity_token: auth_token
      },
      onSuccess: function(transport) {
         $('offering_row_' + offering_id).innerHTML = transport.responseText;
         $('offering_row_' + offering_id).scrollTo();
      }
   });
}

function new_category_oncomplete(response) {
   if (response.status === 200) {
      var table = $('category_table');
      //the last real row is the row with the new form, so we want to insert this new category at n-2
      var create_row = $(table.rows[table.rows.length-1]);
      var row = table.insertRow(table.rows.length-1);
      if (create_row.hasClassName("evenRow")){
         row.addClassName("evenRow");
         create_row.removeClassName("evenRow");
         create_row.addClassName("oddRow");
      } else {
         row.addClassName("oddRow");
         create_row.removeClassName("oddRow");
         create_row.addClassName("evenRow");
      }
      row.innerHTML = response.responseText;
      create_row.hide();
      $('category_form_new').reset();
   } else {
      alert("Error!");
   }
}