// jde Feb 99
var debugging = false;
var xhr = false;		// XMLHttpRequest object variable

function handleTopicChanged() {
    debug('handleTopicChanged:');
    var topic = document.getElementById("topic")
    if (( topic != null) && ( topic.selectedIndex > 0 )) {
        var uri = topic.value;
        debug("uri is!" + uri + "!");
        loadSnippet(uri, 'header', false);  // false => don't append the data
        window.location.hash = '#topic';
    }
}

function handleCategoryChanged() {
    debug('handleCategoryChanged:');
    var category = document.getElementById("category");
    if (( category != null) && ( category.selectedIndex > 0 )) {
        var uri = category.value;
        debug("uri is!" + uri + "!");
        loadSnippet(uri, 'header', false);  // false => don't append the data
        window.location.hash = '#category';
    }
}

// Dev 19th Aug 2009 changed name from searchGlossary to doSearch
// now passes a parameter to say which DB to search
function doSearch(what) {
    var searchTerm = '';   // assume looking for nowt
    var term = document.getElementById('term1');
    if (term != null) searchTerm = term.value;
    alert('doSearch: (Searching ' + what +' for "' + searchTerm + '")');
    var cboxValue = 'N';   // assume not looking for exact value
    var checkboxValue = document.getElementById('checkboxValue');
    if (checkboxValue != null) {
        if (checkboxValue.checked) cboxValue = 'Y';
    }
    if (searchTerm.length > 0) {
        if (what == 'glossary')
            var url = '.\\src\\php\\glossarySearch.php?term1=' + searchTerm + '&checkboxValue=' + cboxValue;
        else // assume slides search
            var url = '.\\src\\php\\slidesSearch.php?term1=' + searchTerm + '&checkboxValue=' + cboxValue;
//alert( 'calling loadSnippet:'+ url+ 'SideNavigationLong:false ');
        loadSnippet(url, 'SideNavigationLong', false);
    } else {
        showMessage('<p>No search term given!</p>', 'SideNavigationLong', true); // append data message
    }
}

// Dev 19th Aug 2009 changed name from searchGlossary to doSearch
// now passes a parameter to say which DB to search
function getSlideCount(lecturename) {
    alert('getSlideCount: ' + lecturename);
    var url = 'slideCount.php?lecture=' + lecturename;
    loadSnippet(url, 'footer', false);
}


function enterKeyTrap(e) {
    alert('enterKeyTrap');
    if (e) {
        if (e.which == 13) document.glossarySearch.submit();
    }
    else {
        if (window.event.keyCode == 13) document.glossarySearch.submit();
    }
    return true;
}

function setupKeyTrap() {
//alert( 'setting up key trap for term1' );
    if (document.getElementById("term1") != null) {
        document.getElementById("term1").onkeydown = enterKeyTrapInput;
    }
}

function enterKeyTrapInput(e) {
//alert( 'enterKeyTrapInput' );
    if (e) {
        if (e.which == 13) {
            alert('1 Looking for:' + document.getElementById("term1").value);
            doSearch('glossary');
        }
    }
    else {
        if (window.event.keyCode == 13) {
            alert('2 Looking for:' + document.getElementById("term1").value);
            doSearch('glossary');
        }
    }
    return true;
}


// If you just want to log a message to the server:
function log(message) {
    var client = new XMLHttpRequest();
    client.open("POST", "/log");
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(message);
}

// Or if you want to check the status of a document on the server:
function fetchStatus(address) {
    var client = new XMLHttpRequest();
    client.onreadystatechange = function () {
        // in case of network errors this might not give reliable results
        if (this.readyState == 4)
//   returnStatus(this.status);
            alert(address + ':' + this.status);
    }
    client.open("HEAD", address);
    client.send();
}

function warnUser() {
    alert("An error has occurred while processing this page." +
        "Our engineers have been alerted!");
// drastic action
//	location.href = './error.html';
}

function trapError(msg, URI, ln) {
    debug('trapError:' + msg);
    // wrap our error condition in an object
    var error = new Error(msg);
    error.location = URI + ', line: ' + ln; // add custom property
    if (debugging) {
        showMessage('trapError Error found:' + msg, 'debugArea', false);   // don't append
        return false;
    } else {
        logger.log(error);
        warnUser();
        return true;  // stop the yellow triangle
    }
}

function init() {
    if (xhr === false) xhr = createXMLHttpRequestObject();
    //loadSnippet( 'welcome.hdr', 'header', true );  // false => don't append the data
}

logger = new Logger();
window.onerror = trapError;
window.onload = init;

$(document).ready(function () {

    var $newList = $('#MainMiddleWrap');
    $newList.on('click', 'li', function () {
        alert('li value:' + $(this)[0].innerText);
    });
    $newList.on('click', 'input[type="radio"]', function () {
        alert('radio value:' + $(this).val());
    });
    $newList.on('click', 'input[type="checkbox"]', function () {
        alert('checkbox value:' + $(this).val());
    });
    $newList.on('click', 'input[type="button"]', function () {
        var $name = $('input[type="button"]').attr('name');
        if ( $name == 'submit' ) {
            var $id = $('input[type="button"]').attr('id');
            var qId = $id.substr(6);
            showValue($name + '!' + qId + '!');
            btnClick(qId);
        }
    });
    $newList.on('click', 'input[type="image"]', function () {
        showValue($(this).val());
    });

    <!-- $( "#newList" ).load( "loadLis.phtml #projects li" ); -->
    <!--    $( "#MainMiddle" ).load( "loadLis.phtml #projects input" ); -->

    $("#answer").hide();   // hide the answer

    //alert('All loaded up');

});

// jde, 17/04/2017, code to show/hide a section of the page
$(document).on("click", 'div.toggle', function(event) {
    //alert('new $toggleDiv clicked');
    $(this).children(".collapsible").toggle("blind", {direction:"up", easing:"easeOutBounce"}, 2000);
});

function showValue(value) {
    alert('Value is:' + value);
};

function btnClick(qId) {
    var optionsListing = '#options-listing' + qId;
    var dataForm = '#mcqForm' + qId;
    var formData = $(dataForm).serialize();
    var pos = formData.indexOf("response=");
    if ( pos == -1 ) {
        alert( ' Please ensure that you have chosen one of the options' );
    } else {
        //alert('btnClick(' + qId + ') form data:' + formData + ' pos:' + pos);

        $.ajax({
            type: 'POST',
            url: 'http://localhost/qubed3new/helper/backend/saveChosenOptionInData.php',
            data: formData,
            success: function (response) {
                alert('response:!' + response + '!');
                var data = eval('(' + response + ')'); // turn it into an object
                alert('out data:' + data.message);
                // clear out the form so users can't click it again
                $(optionsListing).hide();
                $(optionsListing).html('<h2>' + data.message + '</h2><br/>');
                $(optionsListing).show();
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Status: " + textStatus);
                alert("Error: " + errorThrown);
            }

        });
    }

}

function btnFreeTextClick(qId) {
    var optionsListing = '#options-listing' + qId;
    var dataForm = '#mcqForm' + qId;
    var formData = $(dataForm).serialize();

    var pos = formData.indexOf("ft=");
    if ( pos == -1 ) {
        alert( ' Please ensure that you have answered the question' );
    } else {
        alert('btnClick(' + qId + ') form data:' + formData + ' pos:' + pos);

        $.ajax({
            type: 'POST',
            url: 'http://localhost/qubed3New/helper/backend/saveFreeTextInData.php',
            data: formData,
            success: function (response) {
                alert('response:!' + response + '!');
                var data = eval('(' + response + ')'); // turn it into an object
                alert('out data:' + data.message);
                // clear out the form so users can't click it again
                $(optionsListing).hide();
                $(optionsListing).html('<h2>' + data.message + '</h2><br/>');
                $(optionsListing).show();
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Status: " + textStatus);
                alert("Error: " + errorThrown);
            }

        });
    }

}

/*
$(document).on('pagebeforecreate', function () {
    console.log('pagebeforecreate');
});
$(document).on('pagecreate', function () {
    console.log('pagecreate');
});
$(document).on('pageinit', function () {
    console.log('pageinit');
});
$(document).on('pagebeforehide', function () {
    console.log('pagebeforehide');
});
$(document).on('pagebeforeshow', function () {
    console.log('pagebeforeshow');
});
$(document).on('pageremove', function () {
    console.log('pageremove');
});
$(document).on('pageshow', function () {
    console.log('pageshow');
});
$(document).on('pagehide', function () {
    console.log('pagehide');
});
$(window).load(function () {
 console.log("window loaded");
});
$(window).unload(function () {
    console.log("window unloaded");
});
$(function () {
    console.log('document ready');
});

*/
