// get html id's
var confnumber;
var confdetails;
var addflight;
var helpdetails;
var hidebody;
var id0, id1, id2, id3;
var newuseropt;

var collapseObjects = new Array();

// some helper variables
var br = "<br />";
var endp = "</p>";

// tools to support the boarding pass application

function initAll() {
    updateClock();

    confnumber = document.getElementById("confnumber");
    confdetails = document.getElementById("confdetails");
    addflight = document.getElementById("addflight");
    helpdetails = document.getElementById("helpdetails");
    hidebody = document.getElementById("hidebody");

    id0 = document.getElementById("recordLocator");
    id1 = document.getElementById("firstName");
    id2 = document.getElementById("lastName");
    id3 = document.getElementById("emailAddress");

    confnumber.innerHTML = "";
    confdetails.innerHTML = "";
    // helpdetails.innerHTML = "";
    addflight.innerHTML = "";

    getProfile();
    // alert(document.getElementById("userhidden").value);

    newuseropt = document.getElementById("newuseropt");
    if (newuseropt) {
        newuseropt.onclick = toggleNewUser;
        toggleNewUser();
    }
}

function updateClock() {
  var now = new Date()
  var today = now.toString();
  document.getElementById("clockid").innerHTML = today;
  setTimeout("updateClock()",1000);
}

// handle the ajax callback request   
var handleSuccess = function(o){
    // YAHOO.log("XHR transaction was successful", "info", "Boarding Pass");

    var addstatus = o.responseXML.documentElement.getElementsByTagName("status");
    var addmessage = o.responseXML.documentElement.getElementsByTagName("statusmsg");
    var statusid = addstatus[0].firstChild.nodeValue;
    var statusmsg = addmessage[0].firstChild.nodeValue;
    if (statusid != "0") {
        alert(statusmsg);
        return false;
    }

    var confnums = o.responseXML.documentElement.getElementsByTagName("flight");
    confnumber.innerHTML = "";
    confdetails.innerHTML = "";
    // helpdetails.innerHTML = "";

    // limit number of reservations we can process to the last 20 for reasonable speed
    // should never happen except during testing and debugging
    var startlegs = (confnums.length > 20) ? confnums.length-20 : 0;
    
    // write the flight leg options list dynamically into the html tag
    var optinfo = "";
    var leginfo = "";
   
    // scan through the XML nodestags and grab the information 
    for (var i= startlegs; i < confnums.length; i++) {

        var id = "";
        var confnum = "";
        var firstname = "";
        var lastname = "";
        var depart_date = "";
        var depart_time = "";
        var depart_tz = "";
        var depart_city = "";
        var arrive_time = "";
        var arrive_tz = "";
        var arrive_city = "";
        var bp_result = "";
        
        var nodelength = confnums[i].childNodes.length;

        // alert ("i = "+i+" nodelength = "+nodelength);
        
        for (var n=0; n<nodelength; n++) {
            ftmNode = confnums[i].childNodes[n].nodeName;
            
            switch (ftmNode) {
                case "id":
                id= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "confnum":
                confnum= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "firstname":
                firstname= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "lastname":
                lastname= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "depart_date":
                depart_date= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "depart_time":
                depart_time= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "depart_tz":
                depart_tz= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "depart_city":
                depart_city= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "arrive_time":
                arrive_time= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "arrive_tz":
                arrive_tz= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "arrive_city":
                arrive_city= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
                
                case "bp_result":
                bp_result= confnums[i].childNodes[n].childNodes[0].nodeValue;
                break;
            }
        }
     
        // add the option item and select the first item

        if (i==0) {
            optinfo += "<div class=\"optinfo\">";
            optinfo += "<p class=\"legtext\">Confirmation: " + confnum + br;
            optinfo += "Name: " + firstname + " " + lastname + br;
            optinfo += statusmsg + endp;
            optinfo += "</div>" + br;
            // var debugopt = "Confirmation = " + confnum + "\nName: " + firstname+" "+lastname;
      	    // alert(debugopt);
        }

        leginfo += "<div class=\"leginfo\">";
        leginfo += "<p class=\"legtext\">";
        leginfo += "Leg #" + (i+1) + endp;
        leginfo += "<p class=\"tableRowOdd\">";
        leginfo += "Departing from: " + depart_city + br;
        leginfo += "On " + depart_date + " at " + depart_time + " " + depart_tz + endp;

        leginfo += "<p class=\"tableRowEven\">";
        leginfo += "Arriving at: " + arrive_city + br;
        leginfo += "On " + depart_date + " at " + arrive_time + " " + arrive_tz + endp;

        leginfo += "<div class=\"legstatus\">";
        leginfo += "<p class=\"legtext\">";
        leginfo+= "Status:" + br + bp_result + endp;
        leginfo += "</div></div>" + br;
        
        // alert(leginfo);
    }

    confnumber.innerHTML = optinfo;
    confdetails.innerHTML = leginfo;
    switchButton("Refresh Status", refreshFlights);
};


// handle the ajax callback request   
var handleAddSuccess = function(o){
    // YAHOO.log("XHR transaction was successful", "info", "Boarding Pass");

    confnumber.innerHTML = "";
    confdetails.innerHTML = "";
    addflight.innerHTML = "";
    // helpdetails.innerHTML = "";

    var addstatus = o.responseXML.documentElement.getElementsByTagName("status");
    var addmessage = o.responseXML.documentElement.getElementsByTagName("statusmsg");

    // alert(addmessage[0].childNodes[0].nodeValue);
   
    statusid = addstatus[0].childNodes[0].nodeValue;
    // alert(statusid);

    var displayclass = "errinfo";
    if (statusid == "0") {
        displayclass = "optinfo";
    }

    statusmsg = "<div class=\"" + displayclass + "\"><p class=\"legstatus\">";
    statusmsg += addmessage[0].childNodes[0].nodeValue;
    statusmsg += "</p></div>";
    addflight.innerHTML = statusmsg;

    if (statusid == "0") {
        viewFlights();
        switchButton("Refresh Status", refreshFlights);
    }
    else if (statusid == "1") {
        viewFlights();
        switchButton("View Existing Status", viewFlights);
    }

};

// handle the ajax callback request   
var handleUserSuccess = function(o){
    // YAHOO.log("XHR transaction was successful", "info", "Boarding Pass");

    // alert("success");

    var n1 = o.responseXML.documentElement.getElementsByTagName("numrows");
    var n2 = o.responseXML.documentElement.getElementsByTagName("username");
    var n3 = o.responseXML.documentElement.getElementsByTagName("firstname");
    var n4 = o.responseXML.documentElement.getElementsByTagName("lastname");
    var n5 = o.responseXML.documentElement.getElementsByTagName("emailaddress");
    
    // alert(n3[0].childNodes[0].nodeValue);

    // alert(addmessage[0].childNodes[0].nodeValue);
   
    var numrows = n1[0].childNodes[0].nodeValue;
    // alert(numrows);
    
    var username = n2[0].childNodes[0].nodeValue;
    // alert(username);
    
    var firstname = n3[0].childNodes[0].nodeValue;
    // alert(firstname);
    
    var lastname = n4[0].childNodes[0].nodeValue;
    // alert(lastname);
    
    var emailaddress = n5[0].childNodes[0].nodeValue;
    // alert(emailaddress);
    
    // alert(" username="+username+"\n firstname="+firstname+"\n lastname="+lastname+"\n email="+emailaddress);

    if (numrows > 0) {
        id1.value = firstname;
        id2.value = lastname;
        id3.value = emailaddress;
    }
};


var fnUserCallback =
{
    success:handleUserSuccess,
    failure:handleFailure,
    argument: 0,
    timeout: 5000
};


function showValue() {
    alert("This is a test");
}

var handleFailure = function(o){
    alert("request failed");
	if(o.responseText !== undefined){
		errmsg = "<div class=\"errinfo\"><p>Transaction id: " + o.tId + "<br />";
		errmsg += "HTTP status: " + o.status + "<br />";
		errmsg += "Status code message: " + o.statusText + "</p></div>";
		confnumber.innerHTML = errmsg;
	}
};

var fnViewFlightCallback =
{
    success:handleSuccess,
    failure:handleFailure,
    argument: 0,
    timeout: 10000
};

function checkInputs(inpnames, checkemail) {
    var confnum = inpnames[0].value;

    if ( confnum.length == 0 ) {
        alert("You must enter a Confirmation Number");
        return false;
    }

    var cre = /^\s*(\w*)\s*$/;
    if ( !cre.test(confnum) ) {
        alert("Invalid Confirmation Number entered: "+confnum);
        return false;
    }
    cre.exec(confnum);
    inpnames[0].value = RegExp.$1.toUpperCase();

    var firstname = inpnames[1].value;
    if ( firstname.length == 0 ) {
        alert("You must enter a First Name");
        return false;
    }

    var re = /^\s*([a-zA-Z'-])([a-zA-Z'-]\S+)\s*$/;
    if ( !re.test(firstname) ) {
        alert("Invalid First Name entered: "+firstname);
        return false;
    }

    var lastname = inpnames[2].value;
    if ( lastname.length == 0 ) {
        alert("You must enter a Last Name");
        return false;
    }

    if ( !re.test(lastname) ) {
        alert("Invalid Last Name entered: "+lastname);
        return false;
    }

    if ( checkemail && (inpnames[3].name == "emailAddress" ) ) {
        var emailaddr = inpnames[3].value.toLowerCase();
        if (emailaddr.length > 0) {
            emailre = /^\s*\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+\s*$/;
            if ( !emailre.test(emailaddr) ) {
                alert("Invalid Email Address entered: "+emailaddr);
                return false;
            }
        }
    }
    else {
        inpnames[3].value = "";
    }

    re.exec(firstname);
    firstname = RegExp.$1.toUpperCase()+RegExp.$2.toLowerCase();
    inpnames[1].value = firstname;

    re.exec(lastname);
    lastname = RegExp.$1.toUpperCase()+RegExp.$2.toLowerCase();
    inpnames[2].value = lastname;
    
    return true;
}

// this function fills the list of flight records
var viewFlights = function() {

    // get the boxes entered by user
    // var inpnames = document.getElementsByTagName("input");
    var inpnames = new Array(id0, id1, id2, id3);


    if ( !checkInputs(inpnames, false) ) {
        return false;
    }

    confnum = inpnames[0].value;
    firstname = inpnames[1].value;
    lastname = inpnames[2].value;
    
    // alert(confnum+" "+firstname+" "+lastname);

    // convert this to post in the future
    var fnUrl = "bpinput.py?getFlightXML=yes&recordLocator="+confnum;
    fnUrl += "&firstName="+firstname+"&lastName="+lastname;

    // alert(fnUrl);
    var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, fnViewFlightCallback);
}


var fnAddFlightCallback =
{
    success:handleAddSuccess,
    failure:handleFailure,
    argument: 0,
    timeout: 5000
};

// this function fills the list of flight records
var addFlights = function() {

    // get the boxes entered by user
    // var inpnames = document.getElementsByTagName("input");
    var inpnames = new Array(id0, id1, id2, id3);

    if ( !checkInputs(inpnames, true) ) {
        return false;
    }

    confnum = inpnames[0].value;
    firstname = inpnames[1].value;
    lastname = inpnames[2].value;
    emailaddress = inpnames[3].value;
    
    // alert(confnum+" "+firstname+" "+lastname);

    // convert this to post in the future
    var fnUrl = "bpinput.py?addFlightXML=yes&recordLocator="+confnum;
    fnUrl += "&firstName="+firstname+"&lastName="+lastname+"&emailAddress="+emailaddress;

    // alert(fnUrl);
    var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, fnAddFlightCallback);
}

function refreshFlights() {
    // helpdetails.innerHTML = "";
    if (addflight) {
        addflight.innerHTML = "";
    }
    viewFlights();
}

// function to switch button from View, to Enter, to Update
function switchButton(thetext, thefunction) {
    var inpbutton = document.getElementById("doflight");
    if (inpbutton) {
        inpbutton.onclick = thefunction;
        inpbutton.value = thetext;
    }
}

function resetFlights() {
    // var inpnames = document.getElementsByTagName("input");
    var inpnames = new Array(id0, id1, id2, id3);
    
    inpnames[0].value = "";
    inpnames[1].value = "";
    inpnames[2].value = "";
    inpnames[3].value = "";
    switchButton("View Existing Status", viewFlights);

    confnumber.innerHTML = "";
    confdetails.innerHTML = "";
    // helpdetails.innerHTML = "";
    if (addflight) {
        addflight.innerHTML = "";
    }

    var logerr = document.getElementById("loginerror");
    if (logerr) logerr.innerHTML = '<div id="loginerror"></div>';

    var opt1 = document.getElementById("opt1");
    if (opt1) opt1.checked = false;
}


var show_hide = function () {
    var obj = this;
    var myHidden = !obj.cfg.visible;
    if (myHidden) {
        // for (var i=0; i<collapseObjects.length; i++) {
        //     collapseObjects[i].hide();
        //     collapseObjects[i].cfg.visible = false;
        // }
        obj.show();
    } else {
        obj.hide();
    }
    obj.cfg.visible = myHidden;
}

var setup_collapse = function() {
    var clickElements = YAHOO.util.Dom.getElementsByClassName("anime");
    for (var i=0; i<clickElements.length; i++) {
      var clickelem = clickElements[i];
      var clickid = clickelem.getAttribute("id");
      // alert(clickelem.firstChild.nodeValue.length);
      // var dotwidth = clickelem.firstChild.nodeValue.length * 12;
      if (clickid == null || clickid=="") {
        clickid = "id_click_" + (i+1);
        clickelem.setAttribute("id",clickid);
        // clickelem.setAttribute("width", dotwidth);
      }
      // alert(clickid);
      
      // get the node element and id of the next div or p
      var hidenode = clickelem.nextSibling;
      while ( hidenode.nodeType != 1 ) { // && hidenode.nodeName.toUpperCase() != "DIV" ) {
         hidenode = hidenode.nextSibling;
      }

      // alert("node name = " + hidenode.nodeName);

      if (hidenode) {
          hideid = hidenode.getAttribute("id"); 

          // set the id for the hideable portion if it is blank
          if (hideid == null || hideid=="") {
            hideid = "p_"+clickid;
            hidenode.setAttribute("id",hideid);
          }
          // alert(hideid);
          // create a module and a listener to toggle its display
          // initially hidden
          var hidemodule = new YAHOO.widget.Module(hideid, { visible: false });
          n = collapseObjects.length;
          collapseObjects[n] = hidemodule;
          hidemodule.hide();
          hidemodule.cfg.visible = false;
          YAHOO.util.Event.addListener(clickid, "click", show_hide, hidemodule, true);
      }
    }
}

var registerUser = function() {

    var userName = document.getElementById("userName").value;
    var userPass = document.getElementById("userPass").value;

    if ( userName.length < 3 ) {
        alert("You must enter at least a 3 character username");
        return false;
    }

    if ( userPass.length < 6 ) {
        alert("You must enter at least a 6 character password");
        return false;
    }

    var isnew = document.getElementById("passCheck");
    if ( isnew ) {
        var passCheck = isnew.value;
        if (passCheck != userPass ) {
            alert("Verification failed\nYou must enter exactly the same password twice\nPasswords are case sensitive");
            isnew.value = "";
            return false;
        }
    }

    var re = /^(\w+)$/;
    if ( !re.test(userName) ) {
        alert("Invalid username entered: "+userName);
        return false;
    }
    // alert("User = "+userName);

    // convert this to post in the future
    // var fnUrl = "checkuser.php?htXML=yes&recordLocator="+confnum;
    // fnUrl += "&firstName="+firstname+"&lastName="+lastname+"&emailAddress="+emailaddress;
    // var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, fnRegisterUserCallback);

    // put the username in a hidden field for those who don't use cookies
    userhidden = document.getElementById("userhidden");
    if (userhidden) userhidden.value = userName;

    // signal okay to submit the form
    myform = document.getElementById("loginform");
    myform.submit();
    
    return false;
}

var toggleNewUser = function () {
    var newusercontent = document.getElementById("newusercontent");
    var oldusercontent = document.getElementById("oldusercontent");

    if (newuseropt.checked) {
        var oldhtml = '<p class="tableText">Password:';
        oldhtml += '<input type="password" id="userPass" name="userPass" size="20" maxlength="20">';
        oldhtml += '</p>';
        
        var newhtml = '<p class="tableText">Verify PW:';
        newhtml += '<input type="password" id="passCheck" name="passCheck" size="20" maxlength="20">';
        newhtml += '&nbsp; <input class="tinybutton" value="Register" type="button" onclick=registerUser() /></p>';
    } else {
        var newhtml = '&nbsp;';

        var oldhtml = '<p class="tableText">Password:';
        oldhtml += '<input type="password" id="userPass" name="userPass" size="20" maxlength="20">';
        oldhtml += '&nbsp; <input class="tinybutton" value="Login" type="button" onclick=registerUser() /></p>';
    }

    oldusercontent.innerHTML = oldhtml;    
    newusercontent.innerHTML = newhtml;    
}

var putProfile = function() {

    var userhidden = document.getElementById("userhidden");
    if (userhidden) {
        var username = userhidden.value;
        if ( username.length > 0 ) {
            var inpnames = new Array(id0, id1, id2, id3);
            username = encodeURIComponent(username);
            var firstname = encodeURIComponent(inpnames[1].value);
            var lastname = encodeURIComponent(inpnames[2].value);
            var emailaddress = encodeURIComponent(inpnames[3].value);
        
            // alert(" username="+username+"\n firstname="+firstname+"\n lastname="+lastname+"\n email=["+emailaddress+"]");
            var fnUrl = "bpinput.py?putUserXML=yes&username="+username;
            fnUrl += "&firstName="+firstname+"&lastName="+lastname+"&emailAddress="+emailaddress;
        
            // alert(fnUrl);
            var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, fnUserCallback);
        }
    }    
}

var getProfile = function() {

    var userhidden = document.getElementById("userhidden");
    if (userhidden) {
        var username = userhidden.value;
        if ( username.length > 0 ) {
            var fnUrl = "bpinput.py?getUserXML=yes&username="+username;
            // alert(fnUrl);
            var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, fnUserCallback);
        }
    }

}

YAHOO.util.Event.addListener(window, "load", initAll);
YAHOO.util.Event.addListener(window, "load", setup_collapse);

