/*
  Running MySource Matrix
  Developed by Squiz - http://www.squiz.net
  MySource, MySource Matrix and Squiz.net are registered Trademarks of Squiz Pty Ltd
  Page generated: 24 June 2011 14:01:50
*/


var sheets;
var columnsDone = 0;
function addResizeEvent(func) {
    var oldonload = window.onresize;
    if (typeof window.onresize != 'function') {
        window.onresize= func;
    }
    else {
        window.onresize= function() {
            oldonload();
            func();
        }
    }
}

addResizeEvent(refreshIFrames);
function refreshIFrames() {
    if (document.getElementById('top_nav')) {
        var getEls = document.getElementById('top_nav').getElementsByTagName("IFRAME");
        for (var i=0; i<getEls.length; i++) {
            getEls.item(i).style.width = getEls.item(i).nextSibling.offsetWidth;
            getEls.item(i).style.height = getEls.item(i).nextSibling.offsetHeight;
        }
    }
}

// Functions for the top menu
function sfHover() {
    if ($("nav")) {
        var sfEls = $("nav").childElements();
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover=function() {
                if (this.className == "current") {
                    this.className="current_sfhover";
                }
                else if (this.className == "last") {
                    return;
                }
                else {
                    this.className=" sfhover";
                }
            }
            sfEls[i].onmouseout=function() {
                if (this.className == "current_sfhover") {
                    this.className="current";
                }
                else if (this.className == "last") {
                    return;
                }
                else {
                    this.className="";
                }
            }
        }
    }
}
function highlight_top_nav() {
    if ($("nav")) {
     var ul = $("nav").childElements();
     ul.each(function(j) {
     var sfEls = $A(j.getElementsByTagName("li"));
     for (var i=0; i<sfEls.length; i++) {
        sfEls[i].onmouseover=function() {
          this.className = "hover";
        }
        sfEls[i].onmouseout=function() {
          this.className = "";
        }
    }
  });
  }
}
//Give keyboard access to the drop down menus
//todo, find out why this doesnt work properly in IE, seems like there is an addition node or something
//that causes the menu to dissapear when the first nested UL is highlighted
function top_nav_keyboard_axs() {
    var a = $$("#top_nav a");
    a.each(function(i){
      i.onfocus = function() {
        show_sub_nav(this);
        return false;
      }
      i.onblur = function() {
        hide_sub_nav(this);
        return false;
      }
    });
}
function show_sub_nav(e) {
    var element = $(e);
      while(element.up().getAttribute("id") != "nav") {
        element = element.up();
      }
      element.addClassName("sfhover");
}
function hide_sub_nav(e) {
      var element = $(e);
      while(element.up().getAttribute("id") != "nav") {
        element = element.up();
      }
      element.removeClassName("sfhover");
}

//appends a loading image to any element passed
function loadingImage(element,colour) {
    var image = document.createElement("img");
    image.setAttribute("src",ajaxLoader);
    $(element).appendChild(image);
}
//Toggle a divs visibility
function toggleDiv(id) {
    var div = $(id);
    (div.hasClassName("collapsed")) ? div.removeClassName("collapsed") : div.addClassName("collapsed");
    return false;
}
//These functions handle popups and convert standard links to popups
function processLinks(div) {
    if(document.getElementById(div)) {
        var div = document.getElementById(div);
        var as = div.getElementsByTagName("a");
        for (var i = 0; i < as.length; i++) {
            var a = as[i];
            attachLinkEvent(a);
        }
    }
}
function attachLinkEvent(a) {
    var url = a.getAttribute("href");
    a.setAttribute("target","_blank");
    a.setAttribute("title","This link will open in a new window");
    /*a.onclick = function() {
        popup(url);
        return false;
    }*/
}
function popup(url) {
    if (screen.height > 600) {
        var height = screen.height * 0.8;
    }
    else {
        var height = 580;
    }
    if (screen.width > 800) {
        var width = screen.width * 0.8;
    }
    else {
        var width = 780;
    }
    var p = window.open(url,"popup","height=" + height + ", width=" + width + ", location=yes, menubar=yes, resizable=yes, scrollbars=yes, status=yes, toolbar=yes, left=15, top=15");
    p.focus();
}
function noneAbove(element) {
    if (element.value == "NONE") {
        $("question1_additional_help").style.display = "block";
        $("question1_help").style.display = "none";
        $("STD1HELP").style.display = "block";
        element.parentNode.className = "highlight";
    }
}
function show_help(element,id) {
    if (id == "STD1HELP") {
        $("question1_additional_help").style.display = "none";
        $("question1_help").style.display = "block";
    }
    var p = element.parentNode;
    p = p.parentNode;
    if (p.nodeName.toLowerCase() != "li") {p = p.parentNode;}
    if (p.className == "highlight") {
        p.className = "";
    }
    else {
        p.className = "highlight";
    }
    var help_div = $(id);
    if (help_div.style.display == "block") {
        help_div.style.display = "none";
    }
    else {
        help_div.style.display = "block";
    }
}

function helpLinks(id) {
    var helpLinks = $(id).getElementsByClassName("widgets");
    var helpDivs = $(id).getElementsByClassName("help_div");
    for (var i = 0; i < helpLinks.length; i++) {
        var a = helpLinks[i].getElementsByTagName("a")[0];
        var h = helpDivs[i].getAttribute("id");
        a.onclick = function(j,k){
            return function(){
                show_help(j,k);
                return false;
            }
        }(a,h)
        var closeDiv = helpDivs[i].getElementsByClassName("close_help")[0];
        var ca = closeDiv.getElementsByTagName("a").item(0);
        ca.onclick = function(j,k,l){
            return function(){
                show_help(j,k);
                l.focus();
                return false;
            }
        }(ca,h,a)

    }
}

function initClickEvents() {
    var help = $("help").getElementsByTagName("a")[0];
    help.onclick = function(){
        toggleDiv("help");
        return false;
    }
    var legal = $("legal").getElementsByTagName("a")[0];
    legal.onclick = function(){
        toggleDiv("legal");
        return false;
    }
    var start = $("intro_startbutton").getElementsByTagName("a")[0];
    start.onclick = function(){
        goToAnchor("#a_step_1");
        return false;
    }
    var logo = $("vw_logo").getElementsByTagName("a")[0];
    logo.onclick = function(){
        goToAnchor("#a_intro");
        return false;
    }
    $("findVisas").onclick = function(){
        step1();
        return false;
    }
    $("findVisas2").onclick = function(){
        step1();
        return false;
    }
    $("changeAnswers1").onclick = function(){
        goToAnchor('#a_step_1');
        return false;
    }
    $("changeAnswers2").onclick = function(){
        goToAnchor('#a_step_2');
        return false;
    }
    $("findVisas3").onclick = function(){
        step1();
        return false;
    }
    $("backtoquestions").onclick = function(){
        goToAnchor('#a_return_to_questions');
        return false;
    }
    var yourAnswers = $("answers_header").getElementsByTagName("a")[0];
    yourAnswers.onclick = function(){
        return false;
    }
    var changeAnswers = $("changeanswers").getElementsByTagName("a")[0];
    changeAnswers.onclick = function(){
        goToAnchor('#a_return_to_questions');
        return false;
    }
}

function processPopups(id){
    if (id) {
        var as = $(id).getElementsByClassName("popup");
    }
    else {
        var as = $("content").getElementsByClassName("popup");
    }
    for (var i = 0; i < as.length; i++) {
        var a = as[i];
        a.onclick = function(j){
            return function(){
                popup(j.getAttribute("href"));
                return false;
            }
        }(a)
    }
}

var myModuleBookmarkedState = YAHOO.util.History.getBookmarkedState("vw");
// If there is no bookmarked state, assign the default state:
var myModuleInitialState = myModuleBookmarkedState || "#a_intro";
YAHOO.util.History.register("vw", myModuleInitialState, function (state) {
    var currentState = YAHOO.util.History.getCurrentState("vw");
    //alert(currentState);
    loadState(currentState);
});
window.onload = function() {
    sfHover();
    highlight_top_nav();
    top_nav_keyboard_axs();
    refreshIFrames();
    helpLinks("step_1_question_list");
    initClickEvents();
    processPopups("intro_container");
    processPopups("step_1");
    processPopups("notices");
    processPopups("important_info");
    try {
    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
    }  catch (e) {
    loadState("#a_intro");
    }
    var url = window.location.toString();
        if (url.indexOf("#") != -1) {
            loadState("#a_intro");
        }
};
//Define page layout based on the step the user is at
function loadState(state) {
    if (state == "#a_intro") {
        //Hide steps 2 and 3
        $("vw_container").style.display = "none";
        $("intro_container").style.display = "block";
        //goToAnchor('#a_step_1');
    }
    else if (state == "#a_step_1") {
        //Hide steps 2 and 3
        $("vw_container").style.display = "block";
        $("step_2").style.display = "none";
        $("step_3").style.display = "none";
        $("intro_container").style.display = "none";
        //Change heading
        $("step_1_heading").style.backgroundPosition = "0px 0px";
        $("step_1_heading").getElementsByTagName("h2").item(0).style.display = "block";
        $("step_1_heading").getElementsByTagName("h2").item(1).style.display = "none";
        //remove A list from step_1 div
        //remove Q & A lists from step_1 and step_2 divs
        if ($("step_1_container").firstChild.nodeName == "UL") {
            $("step_1_container").removeChild($("step_1_container").firstChild);
        }
        if ($("step_2_container").firstChild.nodeName == "UL") {
            $("step_2_container").removeChild($("step_2_container").firstChild);
        }
        //remove additional questions from step_2 and step_3 divs
        $("additionalQuestions").innerHTML = "";
        $("additionalQuestions2").innerHTML = "";
        //display step_1 div and find visas button
        $("step_1_question_container").style.display = "block";
        $("changeAnswers1").style.display = "none";
        $("findVisas").style.display = "inline";
        $("results_container").style.display = "none";
        $("step_1_container").getElementsByTagName("select").item(0).focus();
        //goToAnchor('#a_step_1');
        if (!$("help").hasClassName("collapsed")){
            toggleDiv("help");
        }
        if (!$("legal").hasClassName("collapsed")){
            toggleDiv("legal");
        }
    }
    else if (state == "#a_step_2") {
        //Show step 2 and 3
        $("step_2").style.display = "block";
        $("vw_container").style.display = "block";
        $("step_3").style.display = "none";
        //Hide buttons and divs in step_1 div
        $("findVisas").style.display = "none";
        $("step_1_question_container").style.display = "none";
        //Show buttons
        $("findVisas2").style.display = "inline";
        $("changeAnswers1").style.display = "inline";
        $("changeAnswers2").style.display = "none";
        //Change heading
        $("step_1_heading").style.backgroundPosition = "0px -117px";
        $("step_1_heading").getElementsByTagName("h2").item(0).style.display = "none";
        $("step_1_heading").getElementsByTagName("h2").item(1).style.display = "block";
        $("step_2_heading").style.backgroundPosition = "0px -60px";
        $("step_2_heading").getElementsByTagName("h2").item(0).style.display = "block";
        $("step_2_heading").getElementsByTagName("h2").item(1).style.display = "none";
        //remove Q & A lists from step_1 div
        if ($("step_2_container").firstChild.nodeName == "UL") {
            $("step_2_container").removeChild($("step_2_container").firstChild);
        }
        if ($("step_1_container").firstChild.nodeName != "UL") {
            showAnswers("step_1_question_list","step_1_container");
        }
        if ($("additionalQuestions").innerHTML == "") {
            step1();
        }
        $("ajax_loader").style.display = "none";
        $("step_2_question_container").style.display = "block";
        //remove additional questions from step_2 and step_3 divs
        $("additionalQuestions2").innerHTML = "";
        $("results_container").style.display = "none";
        $("additionalQuestions").getElementsByTagName("select").item(0).focus();
        if($("other_courses_list")) {
            $("other_course_yes").onclick = function(){showhideOtherCourses()};
            $("other_course_no").onclick = function(){showhideOtherCourses()};
            $("Q16").onchange = function(){refreshOtherCourses()};
        }
        helpLinks("step_2_question_list");
        processPopups("step_2");
        //goToAnchor('#a_step_2');
    }
    else if (state == "#a_step_3") {
        //Show step 3
        $("step_2").style.display = "block";
        $("step_3").style.display = "block";
        //Hide buttons and divs in step_2 div
        $("findVisas2").style.display = "none";
        $("step_2_question_container").style.display = "none";
        $("vw_container").style.display = "block";
        //Show buttons
        $("changeAnswers2").style.display = "block";
        //Change heading
        $("step_2_heading").style.backgroundPosition = "0px -209px";
        $("step_2_heading").getElementsByTagName("h2").item(0).style.display = "none";
        $("step_2_heading").getElementsByTagName("h2").item(1).style.display = "block";
        $("results_container").style.display = "none";
        if ($("additionalQuestions2").innerHTML == "") {
            step1();
        }
        $("ajax_loader").style.display = "none";
        showAnswers("step_2_question_list","step_2_container");
        $("additionalQuestions2").getElementsByTagName("select").item(0).focus();
        helpLinks("step_3_question_list");
        processPopups("step_3");
        //goToAnchor('#a_step_3');
    }
    else if (state == "#a_results") {
        //hide the vw and show the results div
        $("vw_container").style.display = "none";
        $("results_container").style.display = "block";
        $("resultsubheading").style.display = "block";
        $("infoMessages").style.display = "none";
        $("resultsTable").style.display = "block";
        $("ajax_loader").style.display = "none";
        $("answers_header").getElementsByTagName("a").item(0).focus();
        processPopups("results");
        goToTop();
        //goToAnchor('#a_results');
    }
    else if (state == "#a_info") {
        //hide the vw and show the results div
        $("vw_container").style.display = "none";
        $("results_container").style.display = "block";
        $("resultsubheading").style.display = "none";
        $("resultsTable").style.display = "none";
        $("previous_answers").style.display = "none";
        $("backtoquestions").style.display = "block";
        $("ajax_loader").style.display = "none";
        $("backtoquestions").getElementsByTagName("a").item(0).focus();
        goToTop();
        //goToAnchor('#a_info');
    }
    else if (state == "#a_error") {
        //hide the vw and show the results div
        $("vw_container").style.display = "none";
        $("results_container").style.display = "block";
        $("resultsubheading").style.display = "none";
        $("resultsTable").style.display = "none";
        $("previous_answers").style.display = "none";
        $("backtoquestions").style.display = "block";
        $("ajax_loader").style.display = "none";
        goToTop();
        //goToAnchor('#a_error');
    }
    else if (state == "#a_return_to_questions") {
        //hide the vw and show the results div
        $("vw_container").style.display = "block";
        $("results_container").style.display = "none";
        if ($("step_3").getElementsByTagName("select").length > 0) {
            $("step_3_container").getElementsByTagName("select")[0].focus();
        }
        else if ($("step_2").getElementsByTagName("select").length > 0) {
            $("step_2_container").getElementsByTagName("select")[0].focus();
        }
        else {
            $("step_1_container").getElementsByTagName("select")[0].focus();
        }
        //goToTop();
        //goToAnchor('#a_step_1');
    }
}
function goToAnchor(name) {
    if ($("intro_container").style.display == "none") {
        try {
        YAHOO.util.History.navigate("vw", name);
            }  catch (e) {
        loadState(name);
            }
    }
    else {
        YAHOO.util.History.navigate("vw", name);
        loadState(name);
    }
}

function goToTop() {
    window.scrollTo(0,0);
}

//Age calculator
var one_day=1000*60*60*24;
var one_month=1000*60*60*24*30;
var one_year=1000*60*60*24*30*12;
function displayage(yr, mon, day, unit, decimal, round){
    today=new Date();
    var pastdate=new Date(yr, mon-1, day);
    var countunit=unit;
    var decimals=decimal;
    var rounding=round;
    finalunit=(countunit=="days") ? one_day : (countunit=="months")? one_month : one_year;
    decimals=(decimals<=0)? 1 : decimals*10;

    if (unit!="years"){
        if (rounding=="rounddown") {
            var age = Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals;
            return age;
        }
        else {
            var age = Math.ceil((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals;
            return age;
        }
    }
    else{
        yearspast=today.getFullYear()-yr-1;
        tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0;
        pastdate.setFullYear(today.getFullYear());
        pastdate2=new Date(today.getFullYear()-1, mon-1, day);
        tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals;
        var age = yearspast+tail;
        return age;
    }
}
//validate the form and submit the query string to Rules Burst via Ajax.request. If passed a variable will mean user is at step 2
function step1() {
    $("ajax_loader").style.display = "block";
    var proceed = true;
    errorColumns = "";
    var string;
    ($("Q1").value != "") ? string = "Q1=" + $("Q1").value : proceed = false;
    ($("Q2").value != "") ? string += "&Q2=" + $("Q2").value : proceed = false;
    //this bit calculates the users age
    if ($("Q3c").value != "" && $("Q3b").value != "" && $("Q3a").value != "") {
        var year = $("Q3c").value;
        var month = $("Q3b").value;
        var day = $("Q3a").value;
        var age = displayage(year, month, day, "years", 0, "rounddown");
        //alert(age);
        string += "&Q3=" + age;
    }
    else {
        proceed = false;
    }
    ($("Q4").value != "") ? string += "&Q4=" + $("Q4").value : proceed = false;
    ($("Q5").value != "") ? string += "&Q5=" + $("Q5").value : proceed = false;
    //if additional questions exist get their id and value and append to the query string
    if ($("additionalQuestions").getElementsByTagName("select")) {
        var s = $("additionalQuestions").getElementsByTagName("select");
        for (var i = 0; i < s.length; i++) {
            var id = s[i].getAttribute("id");
            var v = s[i].value;
            if (v != "") {
                string += "&" + id + "=" + v;
            }
            else {
                proceed = false;
            }
        }
    }
    //if second set of additional questions exist get their id and value and append to the query string
    if ($("additionalQuestions2").getElementsByTagName("select")) {
        var s = $("additionalQuestions2").getElementsByTagName("select");
        for (var i = 0; i < s.length; i++) {
            var id = s[i].getAttribute("id");
            var v = s[i].value;
            if (v != "") {
                string += "&" + id + "=" + v;
            }
            else {
                proceed = false;
            }
        }
    }

    //highlight any select boxes that have an empty value, and unhighlight them if they've been corrected
    var proceed;
    var qs = $$('#questions select');
    qs.each(function(q,index) {
            if (q.value == "") {
                q.addClassName("highlight_error");
                proceed = false;
            }
            else if (q.hasClassName("highlight_error")){
                q.removeClassName("highlight_error");
            }
        }
    );
    //Question 8 Students
    if ($("other_course_yes")){
        if ($("other_course_yes").checked == true){
            var selection = false;
            var c = $("other_courses_list").getElementsByTagName("input");
            for (var i = 0; i < c.length; i++){
                string += "&" + c[i].getAttribute("id") + "=" + c[i].checked;
                if (c[i].checked == true){
                    selection = true;
                    $("other_courses_list").removeClassName("highlight_error");
                }
            }
            if (selection == false){
                proceed = false;
                $("other_courses_list").addClassName("highlight_error");
            }
        }
        else {
            var c = $("other_courses_list").getElementsByTagName("input");
            for (var i = 0; i < c.length; i++){
                string += "&" + c[i].getAttribute("id") + "=" + c[i].checked;
            }
        }
    }
    if (proceed == false) {
        $("ajax_loader").style.display = "none";
        alert("Please answer all of the questions");
    }
    else {
        //submit the query string to ruleburst visa soap handler
        var url = domain + soapHandler + string;
        //alert("String submitted to Ruleburst: " + string);
        try {
            new Ajax.Request(url, {method:'get',onComplete:function(transport) { step2(transport.responseText); }});
        }
        catch (e) {
            alert("Sorry, the system is currently unavailable. Please contact us for more information.");
        }
    }
    return false;
}
//Process the returned string from ruleburst. the variable r is the response text from ruleburst
function step2(r) {
    var exitFunction = false;
    //alert("Response from ruleburst: " + r);
    /*if (r.indexOf("<html>") != -1) {
        alert("Could not find summary sheet");
    }*/
    var response = r.split(",");
    //if we have an error
    if (response[0] == "e") {
        var page = response[1].toUpperCase();
        var url = domain + messagePath + page;
        new Ajax.Request(url,{method:'get', on404:function() {alert(url + " could not be found"); $("ajax_loader").style.display = "none";}, onSuccess:function(transport) { loadErrorMessage(transport.responseText); goToAnchor("#a_error"); }});
    }
    //if we have additional questions
    else if (response[0] == "q") {
        state = 2;
        loadAdditionalQuestions(r);
    }
    //else if we have summary sheets
    else if (response[0] == "p") {
        var s = r.split(",");
        //splice the string to remove the p, and leave just the summary sheet id's
        s.splice(0,1);
        //Check for an INF file
        for (var i = 0; i < s.length; i++) {
            var value = s[i];
            if (value.indexOf("INF0") != -1) {
                value = value.split("INF");
                var url = domain + infoPath + value[1];
                new Ajax.Request(url,{method:'get', on404:function() {alert(url + " could not be found"); $("ajax_loader").style.display = "none";}, onSuccess:function(transport) { goToAnchor("#a_info"); loadInfoMessage(transport.responseText); }});
            exitFunction = true;
            }
        }
        if (exitFunction == true) { return; }
        var url = domain + summaryPath;
        //Lets build the table based on how many summary sheets we have been given from ruleburst. We'll also hide any extra columns
        sheets = s.length;
        if (s.length == 1) {
            new Ajax.Request(url + s[0],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 1;}, onComplete:function(transport) { loadSummaries(transport.responseText,1); goToAnchor('#a_results');}});
        }
        if (s.length == 2) {
            new Ajax.Request(url + s[0],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 1;}, onComplete:function(transport) { loadSummaries(transport.responseText,1); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[1],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 2;}, onComplete:function(transport) { loadSummaries(transport.responseText,2); goToAnchor('#a_results');}});
        }
        if (s.length == 3) {
            new Ajax.Request(url + s[0],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 1;}, onComplete:function(transport) { loadSummaries(transport.responseText,1); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[1],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 2;}, onComplete:function(transport) { loadSummaries(transport.responseText,2); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[2],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 3;}, onComplete:function(transport) { loadSummaries(transport.responseText,3); goToAnchor('#a_results');}});
        }
        if (s.length == 4) {
            new Ajax.Request(url + s[0],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 1;}, onSuccess:function(transport) { loadSummaries(transport.responseText,1); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[1],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 2;}, onSuccess:function(transport) { loadSummaries(transport.responseText,2); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[2],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 3;}, onSuccess:function(transport) { loadSummaries(transport.responseText,3); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[3],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 4;}, onSuccess:function(transport) { loadSummaries(transport.responseText,4); goToAnchor('#a_results');}});
        }
        if (s.length == 5) {
            new Ajax.Request(url + s[0],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 1;}, onSuccess:function(transport) { loadSummaries(transport.responseText,1); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[1],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 2;}, onSuccess:function(transport) { loadSummaries(transport.responseText,2); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[2],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 3;}, onSuccess:function(transport) { loadSummaries(transport.responseText,3); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[3],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 4;}, onSuccess:function(transport) { loadSummaries(transport.responseText,4); goToAnchor('#a_results');}});
            new Ajax.Request(url + s[4],{method:'get', on404:function() {loadErrorMessage(r), loadState('error'); errorColumns = 5;}, onSuccess:function(transport) { loadSummaries(transport.responseText,5); goToAnchor('#a_results');}});
        }
    }
}
// if additional questions are returned from ruleburst, load them into the additional questions div
function loadAdditionalQuestions(text) {
    var r = text.split(",");
    if (r.length > 2) {
        var page = r[2].toLowerCase();
        div = "additionalQuestions2";
        //loadingImage(div,"white");
        new Ajax.Updater(div, domain + questionPath + page, {method:'get', onComplete:function() { goToAnchor('#a_step_3');/*loadState("step_3");*/}});
    }
    else {
        var page = r[1].toLowerCase();
        div = "additionalQuestions";
        //loadingImage(div,"white");
        new Ajax.Updater(div, domain + questionPath + page, {method:'get', onComplete:function() {goToAnchor('#a_step_2');/*loadState("step_2");*/}});
    }
    return false;
}
function showAnswers(listId,divId,append) {
    var div = $(divId);
    if (div.getElementsByTagName("ul").length > 0) {
        var uls = div.getElementsByTagName("ul");
        var ulsLen = uls.length;
        for (var u = 0; u < ulsLen; u++) {
            if (uls[u].className == "answers" && !append) {
                return;
            }
        }
    }
    var ul = document.createElement("ul");
    ul.className = "answers";
    if ($(listId)) {
        var li = $(listId).childElements();
        var liLen = li.length;
        for (var i = 0; i < liLen; i++) {
            var qText = document.createTextNode(li[i].getElementsByTagName("label").item(0).firstChild.nodeValue);
            if (li[i].getElementsByTagName("select").length > 0){
                if (li[i].getElementsByTagName("select").length > 1) {
                    var s = li[i].getElementsByTagName("select");
                    var sLen = s.length;
                    var text;
                    for (var j = 0; j < sLen; j++) {
                        if (j == 0) {
                            text = " " + s[j].options[s[j].selectedIndex].text;
                        }
                        else {
                            text += " " + s[j].options[s[j].selectedIndex].text;
                        }
                    }
                    var sText = document.createTextNode(text);
                }
                else {
                    var s = li[i].getElementsByTagName("select").item(0);
                    var sText = document.createTextNode(s.options[s.selectedIndex].text);
                }
            }
            else if (li[i].getElementsByTagName("li").length > 0){
                var s = li[i].getElementsByTagName("li");
                var sLen = s.length;
                if ($("other_course_yes").checked == true){
                    var text = "";
                    for (var j = 0; j < sLen; j++) {
                        if (s[j].getElementsByTagName("input").length > 0){
                            var checkbox = s[j].getElementsByTagName("input").item(0);
                            var label = s[j].getElementsByTagName("label").item(0);
                            var t = label.innerHTML;
                            if (checkbox.checked == true){
                                (text == "") ? text = t : text += ", " + t;
                            }
                        }
                    }
                    var sText = document.createTextNode(text);
                }
                else {
                    var sText = document.createTextNode("No");
                }
            }
            var l = document.createElement("li");
            var br = document.createElement("br");
            l.appendChild(qText);
            l.appendChild(br);
            var div_a = document.createElement("div");
            div_a.appendChild(sText);
            l.appendChild(div_a);
            ul.appendChild(l);
        }
        if (append) {
            div.appendChild(ul);
        }
        else {
            div.insertBefore(ul,div.firstChild);
        }
    }
}
//loads an INFO message
function loadInfoMessage(page) {
    $("infoMessages").style.display = "block";
    $("infoMessages").innerHTML = "";
    $("infoMessages").innerHTML += "<div>" + page + "</div>";
    processLinks("infoMessages");
}
function loadErrorMessage(page) {
    $("infoMessages").style.display = "block";
    $("infoMessages").innerHTML = "";
    $("infoMessages").innerHTML += "<div>" + page + "</div>";
    processLinks("errorMessages");
}
function PHP_Unserialize(input) {
    var result = PHP_Unserialize_(input);
    return result[0];
}
function PHP_Unserialize_(input) {
    var length = 0;
    switch (input.charAt(0)) {
        case 'a':
            length = PHP_Unserialize_GetLength(input);
            input  = input.substr(String(length).length + 4);
            var arr   = new Array();
            var key   = null;
            var value = null;
            for (var i=0; i<length; ++i) {
                key   = PHP_Unserialize_(input);
                input = key[1];

                value = PHP_Unserialize_(input);
                input = value[1];

                arr[key[0]] = value[0];
            }
            input = input.substr(1);
            return [arr, input];
            break;
        case 'O':
            length = PHP_Unserialize_GetLength(input);
            var classname = String(input.substr(String(length).length + 4, length));
            input  = input.substr(String(length).length + 6 + length);
            var numProperties = Number(input.substring(0, input.indexOf(':')));
            input = input.substr(String(numProperties).length + 2);
            var obj      = new Object();
            var property = null;
            var value    = null;
            for (var i=0; i<numProperties; ++i) {
                key   = PHP_Unserialize_(input);
                input = key[1];

                // Handle private/protected
                key[0] = key[0].replace(new RegExp('^\x00' + classname + '\x00'), '');
                key[0] = key[0].replace(new RegExp('^\x00\\*\x00'), '');

                value = PHP_Unserialize_(input);
                input = value[1];

                obj[key[0]] = value[0];
            }
            input = input.substr(1);
            return [obj, input];
            break;
        case 's':
            length = PHP_Unserialize_GetLength(input);
            return [String(input.substr(String(length).length + 4, length)), input.substr(String(length).length + 6 + length)];
            break;
        case 'i':
        case 'd':
            var num = Number(input.substring(2, input.indexOf(';')));
            return [num, input.substr(String(num).length + 3)];
            break;
        case 'b':
            var bool = (input.substr(2, 1) == 1);
            return [bool, input.substr(4)];
            break;


        case 'N':
            return [null, input.substr(2)];
            break;
        case 'o':
        case 'r':
        case 'C':
        case 'R':
        case 'U':
            alert('Error: Unsupported PHP data type found!');
        default:
            return [null, null];
            break;
    }
}
function PHP_Unserialize_GetLength(input) {
    input = input.substring(2);
    var length = Number(input.substr(0, input.indexOf(':')));
    return length;
}
function loadSummaries(text,column) {
    switch (sheets) {
        case 1:
            var tdWidth = "90%";
            break;
        case 2:
            var tdWidth = "45%";
            break;
        case 3:
            var tdWidth = "30%";
            break;
        case 4:
            var tdWidth = "22.5%";
            break;
        case 5:
            var tdWidth = "18%";
            break;
    }
    //unserialize the array return by petes php script
    //(PHP_Unserialize(text)) ? alert("PHP unserialize successful") : alert("PHP unserialize failed");
    var content = PHP_Unserialize(text);
    //alert(content[0]);
    contentLen = content.length;
    //process table header
    var th = $("resultsTable").getElementsByTagName("th");
    var thLen = th.length;
    var d = th[column].getElementsByTagName("div");
    var dLen = d.length;
    for (var j = 0; j < dLen; j++) {
        if (d[j].className == "col_name") {
            d[j].innerHTML = content[0];
            th[column].style.display = "";
        }
    }
    var tr = $("resultsTable").getElementsByTagName("tr");
    var even = false;
    //loop through all the td's and append the new html from the summary sheet and also set the zebra stipes
    for (var i = 1; i < contentLen; i++) {
        if (tr[i]) {
            var td = tr[i].getElementsByTagName("td");
            var tdLen = td.length;
            for (var t = 1; t < tdLen; t++) {
                td[t].style.width = tdWidth;
            }
            var cell = column-1;
            td.item(cell).innerHTML = content[i];
            td.item(cell).style.display = "";
        }
    }
    columnsDone ++;
    if (columnsDone == sheets) {
        hideCells(columnsDone,"th");
        hideCells(columnsDone,"td");
        processLinks("resultsTable");
        /* This part is to display the users andswers on the results screen */
        $("answers_header").style.display = "block";
        $("answers_content").style.display = "block";
        $("answers_left").innerHTML = "";
        $("answers_right").innerHTML = "";
        $("backtoquestions").style.display = "none";
        $("previous_answers").style.display = "block";
        showAnswers("step_1_question_list","answers_left",true);
        showAnswers("step_2_question_list","answers_right",true);
        showAnswers("step_3_question_list","answers_right",true);
        /*if (location.href.indexOf("?hide_results") != -1) {
            $("answers_header").style.display = "block";
            $("answers_content").style.display = "";
        }
        if (location.href.indexOf("?no_results") != -1) {
            $("previous_answers").style.display = "none";
        }*/
        columnsDone = "";
    }

}
function hideCells(c,tag) {
    var rows = $("resultsTable").getElementsByTagName("tr");
    var rowsLen = rows.length;
    for (var j = 0; j < rowsLen; j++) {
        var cells = rows[j].getElementsByTagName(tag);
        var cellsLen = cells.length;
        var i;
        (tag == "td") ? i = c : i = c + 1;
        for (i; i < cellsLen; i++) {
            cells[i].style.display = "none";
        }
    }
}

function showhideOtherCourses() {
    //check if main course is selected
    if ($("Q16").selectedIndex == 0) {
        displayMessage("Q16");
    }
    else {
        //display other courses list
        displayOtherCourses();
    }
}

//used when yes has already been selected but the user changes the course
function refreshOtherCourses() {
    if ($("other_courses_list").style.display != "none") {
        displayOtherCourses();
    }
}

function displayOtherCourses() {
    var mCourse = $("Q16").value;
    var cList = $("other_courses_list").getElementsBySelector("input");

    //show or hide the other courses depending on what is selected in Q16
    for (var i=0; i<cList.length; i++) {
            if (cList[i].value != mCourse) {
                cList[i].parentNode.style.display = "block";
            }
            else {
                cList[i].checked = "";
                cList[i].parentNode.style.display = "none";
            }
    }

    //if yes is selected then put the focus to other courses
    if ($("other_course_yes").checked) {
        $("other_courses_list").style.display = "block";
        focusOtherCourses();
    }
    else {
        $("other_courses_list").style.display = "none";
        for (var i = 0; i < cList.length; i++){
            cList[i].checked = false;
        }
    }
}

function assessmentLevelCheck() {
    var proceed = validateInputs();
    if (proceed) {
        if (!excemptfromRB()) {
            callSoapHandler();
        }
    }
}

function excemptfromRB() {
    if ($("Q16").value == "AUS") {
        window.location = "/students/students/576-2/";    return true;
    }
    return false;
}

function callRedirect(redirectCode) {
    alert(pageRedirector + "?code=" + redirectCode);
}

function validateInputs() {
    if ($("Q2").selectedIndex == 0) { displayMessage("Q2"); return false; }
    if ($("Q16").selectedIndex == 0) { displayMessage("Q16"); return false; }
    //check if other courses are selected
    if ($("other_course_yes").checked) {
        var cList = $("other_courses_list").getElementsBySelector("input");
        var isSelected = false;
        for (var i=0; i<cList.length; i++) {
            if (cList[i].checked)     isSelected = true;
        }
        if (!isSelected) { displayMessage("OTHER_COURSE"); return false; }
    }

    return true;
}

function displayMessage(code) {
    switch (code) {
        case "Q2":
            alert("Please select your passport country.");
            $("Q2").focus();
            break;
        case "Q16":
            alert("Please select your main course of study.");
            $("Q16").focus();
            break;
        case "OTHER_COURSE":
            alert("Please select any courses in an education sector other than your main course of study.");
            focusOtherCourses();
            break;
    }
}

function focusOtherCourses() {
    if ($("Q19").parentNode.style.display != "none")
        $("Q19").focus();
    else
        $("Q20").focus();
}
