// ----------------------------------------------------------------
// these are functions to suport ajax enabled pages.  the functions
// are made to be generic but also allow customization so it can
// be reused
// 
// the first function called is xmlhttpPost with 5 arguments:
//    1) the web url to hit
//    2) the function to use to format the arguments after url?
//        you will need to create your own custom function
//    3) the input value(s) for the for the format arguments function
//    4) the function to use to display data on the form, there are 
//        2 standard functions
//          1) update_form_field - updates a form field
//          2) update_div - updates inner html of a division
//        -OR_
//          you create your own custom function
//    5) the form field or div to update with the result
//
// example: 
//    xmlhttpPost("ajax_script.php","bluetalk_post",form_el_name.value,"update_form_field",result_el_name);
// ----------------------------------------------------------------

// posts the request to the appropriate page
function xmlhttpPost(strURL,postfn,inputval,returnfn,outputval) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText,returnfn,outputval);
        }
    }
    self.xmlHttpReq.send(postquerystring(postfn,inputval));
}

// the data to send to the http page
function postquerystring(postfn,inputval) {
    var rtnVal = '';
    switch (postfn) {
        case "find_courses_post":
            rtnVal = find_courses_post(inputval);
            break;
    }
    return rtnVal;
}

// where to store the response
function updatepage(str,returnfn,outputval){
    switch (returnfn) {
        case "update_form_field":
            update_form_field(str,outputval);
            break;
        case "update_div":
            update_div(str,outputval);
            break;
        case "find_courses_populate_dd":
            find_courses_populate_dd(str,outputval);
            break;
    }
}

// generic function for form field - update with whatever is returned
function update_form_field(str,fieldname) {
    document.find_element_by_id(fieldname).value = str;
}

// generic function for div - update with whatever is returned
// warning - not W3C compliant but works in IE, Firefox
function update_div (str,divname) {
    document.find_element_by_id(divname).innerHTML = str;
}

// --------------------------------------------------------------------
// these are functions for the banner course drop down (to add courses)
// --------------------------------------------------------------------

// send request to find the courses
function find_courses (element_id,element_value,result_element_id) {
   element_value = element_value.toUpperCase();
   if (element_value.length > 0) {
       xmlhttpPost("get_course_drop_down.php","find_courses_post",element_value,"find_courses_populate_dd",result_element_id);
   }
   return;
}

// format the input parameters
function find_courses_post (inputval) {
    qstr='course=' + escape(inputval) + '&term_code=' + find_element_by_id('term').value;
    return qstr;
}

// populate the drop down
function find_courses_populate_dd (str,result_element_id) {

    var course_dd_tmp = find_element_by_id(result_element_id);
    while(course_dd_tmp.hasChildNodes()){
        course_dd_tmp.removeChild(course_dd_tmp.firstChild);
    }

    if ( str != "" ) {
        var course_list = str.split("\n");
        for ( var course_index in course_list ) {
            var course_detail = course_list[course_index].split("\|");

                var term_code = course_detail[0];
                var crn = course_detail[1];
                var course = course_detail[2];
                var section = course_detail[3];
                var instructor = course_detail[4];

            // no results returned
            if ( typeof(term_code) == "undefined" ) {
                var strVal = "None";
                var strText = "No courses match the criteria";
            } else {
                var strVal = course_list[course_index];
                var strText = course + " " + section + " - " + instructor;
            }

            // last element in list is not a course
            if ( course_index < (course_list.length-1) ) {
                var opt = document.createElement('option');
                opt.setAttribute('value',strVal);
                var text = document.createTextNode(strText);
                opt.appendChild(text);
                course_dd_tmp.appendChild(opt);
            }
        }
    } else {
            var opt = document.createElement('option');
            opt.setAttribute('value','');
            var text = document.createTextNode('No courses meet the criteria');
            opt.appendChild(text);
            course_dd_tmp.appendChild(opt);
    }
}

// ***
// *** This function locates an html object by it's id
// ***

function find_element_by_id(anId) {

  var element;

  if (document.getElementById) {
    // *** W3C Standard
    element = eval('document.getElementById(\'' + anId + '\')');
  } else if (document.all) {
    // *** old ie versions
    element = eval('document.all[\'' + anId + '\']');
  } else if (document.layers) {
    // *** nn4
    element = eval('document.layers[\'' + anId + '\']');
  }

  return element;
}

// *********************************************
// Validation Routines
// validateNumber = validate that the entry is a number
// validateDate = validate the date in the form of mm/dd/yyyy

function validateNumber ( inputNumber ) {
    var returnInd = true;
    if ( isNaN(inputNumber) ) {
        returnInd = false;
    }
    return returnInd;
}

function validateDate ( inputDate ) {
    var returnInd = true;
    var splitDateArray = inputDate.split('/');

    var strMonth = splitDateArray[0];
    var strDay = splitDateArray[1];
    var strYear = splitDateArray[2];
    if ( ( strMonth == 1 || strMonth == 3 || strMonth == 5 || strMonth == 7 || strMonth == 8 || strMonth == 10 || strMonth == 12 ) && ( strDay > 31 || strDay < 1 ) ) {
        var returnInd = false;
    }
    if ( ( strMonth == 4 || strMonth == 6 || strMonth == 9 || strMonth == 11 ) && ( strDay > 30 || strDay < 1 ) ) {
        var returnInd = false;
    }
    if (strMonth == 2) {
        if ( isLeapYear(strYear) && ( strDay > 29 || strDay < 1 ) ) {
            var returnInd = false;
        } else if ( strDay > 28 || strDay < 1 ) {
            var returnInd = false;
        }
    }
    if (!returnInd) {
        alert("The date " + inputDate + " is not valid.  Please reenter the date.");
    }
    return returnInd;
}

// check if the date passed is a leap year
function isLeapYear( inputYear ) {
    var leapYear = false;
    if ( ( inputYear % 4 ) != 0 ) {
        leapYear = false;
    } else if  ( ( inputYear % 400 ) == 0 ) {
        leapYear = true;
    } else if ( ( inputYear % 100 ) == 0 ) {
        leapYear = false;
    } else {
        leapYear = true;
    }
    return leapYear;
}

// *********************************************
// Data Filtering Routines
// stripJunk = remove junk from the input
function stripJunk (strTemp) {
    strTemp.value = strTemp.value.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-|\=/g,""); 
    return;
} 
