/**
 * jde, 24/08/17, loadNavigationDetails now checks for an empty filename
 * jde, 27/07/17, added routine loadNavigationDetails to use new json structure
 * jde, ContentLoader.js, Converted from original coding 26/07/2017.
 *      Original coding used in helpSys August 09
 */

'use strict';

var ContentLoader = ContentLoader || {};

ContentLoader = function () {

    var xhr = null, localDebugging = false; // just change to true and put in appropriate place throughout code

    var contentFolder = '', whereAbouts = '';

    function debug(msg) {
        if ( ( localDebugging ) && ( GlobalData.debugging ) )
            MainApp.LoggingHandler.logMessage(1, msg);
    }

    function showMessage(msg, whereAbouts, appendMode) {
// switch off debugging for everything except output to the 'debugArea'
        if (whereAbouts != 'debugArea') {
            var tmpDebugging = localDebugging;
            localDebugging = false;
        }
        debug('showMessage:' + msg + whereAbouts + appendMode);

        var where = document.getElementById(whereAbouts);
        if ( (where == null) || (where == 'undefined' ) ) { // can't find where in page
            alert('showMessage:' + msg)
        } else {
            if (appendMode == 'add') {
                MainApp.PageUpdater.updateElement( whereAbouts, msg, 'add');
            } else {
                (appendMode == 'append') ? MainApp.PageUpdater.updateElement( whereAbouts, msg, 'append') : MainApp.PageUpdater.updateElement( whereAbouts, msg, 'prepend');
            }
        }

// now put debugging back to previous state
        if (whereAbouts != 'debugArea') {
            localDebugging = tmpDebugging;
        }
    }

// filename => path/filenameprefix.extension?parameters
    function filenameSplit( inputFilename ) {
        //localDebugging = true;
        debug('filenameSplit:'+ inputFilename +': ' +inputFilename.length + ':');
        var parts = new Array();
        var path = '';
        var fileExtension = '';
        var filename = '';
        var parameters = '';
        for ( var i=0; i<4; i++ ) parts[i] = '';  // initialise the return array to empty strings

        if ( inputFilename.length == 0 ) { // we dont have a inputFilename to split
            debug( 'inputFilename length is zero' );
        } else {
            var tmpString = inputFilename;
            var firstQMark = tmpString.indexOf( '?' );
            if ( firstQMark > 0 ) {
                parameters = tmpString.substr( firstQMark + 1, 255 );  // leave the QMark in the return string
                tmpString = tmpString.substr( 0, firstQMark );
            }

            var lastDot = tmpString.lastIndexOf( '.' );
            if ( lastDot > 0 ) {
                fileExtension = tmpString.substr( lastDot, 255 );  // do want the dot
                tmpString = tmpString.substr( 0, lastDot );
            }

            var lastSlash = tmpString.lastIndexOf( '/' );
            if ( lastSlash == 0 ) {
                path = '';  // no path
            } else {
                path = tmpString.substr( 0, lastSlash + 1 );  // put the slash at end back on
            }

            filename = tmpString.substr( lastSlash + 1, 255 );
        } // end of if
        parts[ 0 ] = path;
        parts[ 1 ] = filename;
        parts[ 2 ] = fileExtension;
        parts[ 3 ] = parameters;
        var bits = parts[ 1 ].split( '_' );
        parts[ 4 ] = bits[ 1 ];  // this is the file number part eg sl_23 => returns 23
//  for ( var i=0; i < 4; i++ ) debug( 'Parts[' + i + ']: ' + parts[ i ] + ':' );   // show the returned parts
        //localDebugging = false;
        return parts;
    }

    // where does data come from and where is it to be displayed
    function startUp( folderName, where ) {
        contentFolder = folderName;
        whereAbouts = where;
    }

// function executed when the state of the request changes
    function handleStateChangeText(whereAbouts, preText, postText, appendMode) {
        debug('handleStateChangeText:' + whereAbouts + preText + postText + appendMode);
        // continue if the process is completed

        if (xhr.readyState == 4) {
            // continue only if HTTP status is "OK"
            if ((xhr.status >= 200 && xhr.status < 300) || (xhr.status == 304)) {
                try { // now place response in the chosen area of the page if found
                    var where = document.getElementById(whereAbouts);
                    if (where != null) {
                        // build the response
                        var responsTxt = preText + xhr.responseText + postText;
//alert( 'handleStateChangeText responseText:'+ responsTxt + ':' );
                        showMessage(responsTxt, whereAbouts, appendMode);
                    } else {
                        throw new Error('Error :' + whereAbouts + ' not found on page!');
                    }
                } catch (e) {
                    // display error message
                    showMessage(e.name + "(handleStateChangeText)Error reading the response:" + e.toString(), 'debugArea', true);
                }
            }
            else {
                // display status message
                showMessage("(handleStateChangeText)There was a problem retrieving the data:\n" + xhr.statusText + " (" + xhr.status + ") ", 'debugArea', true);
            }
        }
    }

// jde, added to new system, 02/08/17
// jde, added 01/12/2016, send a post request
// performs a server request and assigns a callback function
    function loadPHPPostPage(url, parameters, whereAbouts, preText, postText, appendMode) {
//        showMessage( 'loadPHPPostPage:' + url, whereAbouts, appendMode );
        localDebugging = true;
        debug('loadPHPPostPage:' + url + ' parameters:' + parameters + ' :' + whereAbouts + ':' + preText + ':' + postText + ':' + appendMode + ':');
        // continue only if xhr isn't void
        if (xhr) {
            // try to connect to the server
            try {
                // initiate server request
                xhr.open("POST", url, true); // true => asynchronous call
                var txtMode = true;  // xxx for the time being assume that we always want straight text back from php call
                if (txtMode) {
//        xhr.setRequestHeader( "Cache-Control", "no-cache" );
//        xhr.setRequestHeader( "Pragma", "no-cache" );
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    //xhr.setRequestHeader("Content-length", parameters.length);
                    xhr.onreadystatechange = function () {
                        //alert('Looking for: '+url);
                        handleStateChangeText( whereAbouts, preText, postText, appendMode);
                        // handleStateChangeJSON(whereAbouts, preText, postText, appendMode);
                        localDebugging = false;
                    }
                } else {
                    xhr.onreadystatechange = function () {
                        handleStateChangeXML(whereAbouts);
                        localDebugging = false;
                    }
                }
                xhr.send(parameters);
            }
            // display an error in case of failure
            catch (e) {
                showMessage("Can't connect to server:\n" + e.toString(), 'debugArea', true);
                localDebugging = false;
            }
        }
    }

// Added Dev 21/02/17
    function loadPDF(pathname, whereAbouts, preText, postText, appendMode) {
        debug('loadPDF:' + pathname + ':' + whereAbouts + ':' + appendMode + ':');
        var ok = false;
        var div = document.getElementById(whereAbouts);
        if (div != null) {
            var pdfHTML = '<embed width = "600" height = "450" src = "' + pathname + '" type = "application/pdf" ></embed>';
            showMessage(pdfHTML, whereAbouts, appendMode);
            ok = true;
        }
        return ok;
    }

// performs a server request and assigns a callback function
    function loadPage(pathname, whereAbouts, preText, postText, appendMode) {
        debug('loadPage:' + pathname + whereAbouts + preText + postText + appendMode);
        // continue only if xhr isn't void
        if (xhr) {
            // try to connect to the server
            try {
                // initiate server request
                xhr.open("GET", pathname + '?junk=' + Math.random(), true); // true => asynchronous call
                var txtMode = true;   // assume that we have text being returned
                if (txtMode)
//        xhr.setRequestHeader( "Cache-Control", "no-cache" );
//        xhr.setRequestHeader( "Pragma", "no-cache" );
                    xhr.onreadystatechange = function () {
                        handleStateChangeText(whereAbouts, preText, postText, appendMode);
                    };
                else
                    xhr.onreadystatechange = function () {
                        handleStateChangeXML(whereAbouts);
                    };
                xhr.send(null);
            }
            // display an error in case of failure
            catch (e) {
                showMessage("Can't connect to server:\n" + e.toString(), 'debugArea', true);
            }
        }
    }

// Added Dev 13/08/09
    function loadImage(pathname, whereAbouts, preText, postText, appendMode) {
        debug('loadImage:' + pathname + ':' + whereAbouts);
        var ok = false;
        var div = document.getElementById(whereAbouts);
        if (div != null) {
            var imgHTML = preText + '<img src="' + pathname + '" width="100%" height="100%" alt="slide:' + pathname + '" border="0" />' + postText;
            showMessage(imgHTML, whereAbouts, appendMode);
            ok = true;
        }
        return ok;
    }

    // jde, 24/08/17, copied from original
    // Added Dev 13/08/09
function loadTXTSnippet(pathname, whereAbouts, preText, postText, appendMode) {
//alert( 'loadTXTSnippet:' + pathname +':' +whereAbouts + ':');
    try {
	// initiate server request
	var url = pathname;
	xhr.open("GET", url, true); 				// true => asynchronous call
	xhr.onreadystatechange = function () {
	    handleStateChangeText(whereAbouts, preText, postText, appendMode);
	};
	xhr.send(null);
    }
	// display an error in case of failure
    catch (e) {
	showMessage("Can't connect to server:\n" + e.toString(), 'debugArea', true);
    }
}

// jde, 24/5/17, added support for java files
// gets the file extension from the given file and then tries to load that page
// into a specific area of the current page.
    var loadSnippet = function ( pathname, whereAbouts, appendMode ) {
        //alert( 'loadSnippet:' + pathname +':' + whereAbouts+':'+appendMode+':' );
        debug('loadSnippet:' + pathname + ':' + whereAbouts + ':' + appendMode + ':');
        var preText, postText;
        // continue only if xhr isn't void
        if (xhr) {
            var parts = filenameSplit(pathname);
            var ext = parts[2];
            var url = parts[0] + parts[1] + parts[2];
            if (ext == '') {
                showMessage('No file extension found', 'debugArea', true);
                MainApp.PageUpdater.updateElement('mainMiddleContent', 'Cleared ok ...', 'add');
            } else {
//alert( 'FilenameExtension is:' + ext );
                switch (ext) {
                    case '.txt' : {
                        var id = 'makeOneUp' + Math.random();
                        preText = '<div class="open" id="' + id + '">';
                        preText += '<img src="./src/images/minus.gif" alt="expand" onclick="SlideManager.toggle(\'' + id + '\');"/>' + parts[1];
                        preText += '<div class="item-body" id="item-body"><pre>';
                        postText = '</pre></div></div>';
                        loadTXTSnippet(pathname, whereAbouts, preText, postText, appendMode);
                        break;
                    }
                    case '.js' :
                    case '.pas' :
                    case '.java' : {
                        preText = '<pre class="code">';
                        postText = '</pre>';
                        loadTXTSnippet(pathname, whereAbouts, preText, postText, appendMode);
                        break;
                    }
                    case '.php' :  {
                        var parameters = parts[3];
                        preText = '';
                        postText = '';
                        debug('loadPHPPage:'+ pathname + ':'+whereAbouts + ':'+appendMode +':');
                        showMessage( '', 'mainMiddleContent', 'add');
                        loadPHPPostPage(url, parameters, whereAbouts, preText, postText, appendMode);
                        break;
                    }
                    case '.jpg' :
                    case '.gif' :
                    case '.PNG' :
                    case '.png' : {
                        preText = '';
                        postText = '';
                        var ok = loadImage(pathname, whereAbouts, preText, postText, appendMode);
                        //if (ok) updateHiddenPathname(pathname);
                        showMessage( 'Check out the slides', 'contentFooter', 'add');
                        break;
                    }
                    case '.sbr' :
                    case '.hdr' :
                    case '.ftr' :  {
                        preText = '';
                        postText = '';
//			     loadTXTSnippet( pathname, whereAbouts, preText, postText, appendMode );
                        loadPage(pathname, whereAbouts, preText, postText, appendMode);
                        //setupKeyTrap();
                        break;
                    }
                    case '.pdf' : {
                        preText = '';
                        postText = '';
                        loadPDF(pathname, whereAbouts, preText, postText, appendMode);
                        break;
                    }
                    default :
                        //console.log("default" + pathname + whereAbouts + preText + postText +appendMode);
                        preText = '';
                        postText = '';
                        loadPage(pathname, whereAbouts, preText, postText, appendMode);  //html files end up here
                }
            }
        }
    };

    var loadLectureDetails = function ( filename, whereAbouts, appendMode ) {
        xhr.onreadystatechange = function ( ) {
            if (xhr.readyState==4 && xhr.status==200) {
                // Added Dev 11/07/17
                var slideDetails = {};
                var slides = JSON.parse( xhr.responseText );
                var foldername = slides.contentFolder;   // as we're dealing with lectures they live in the lectures folder ;)
                SlideManager.startup(foldername);
                var slideCount = slides.slides.length;
                slideDetails.slideCount = slideCount;
                SlideManager.load( slideCount );   // get the slide manager ready with the number of slides in set and display first slide in set
                slideDetails.titles = [];
                var tmpString = "";
                var html = "<p>No: of slides:" + slideCount + "</p>";
                for (var index = 0; index < slideCount; index ++){
                    var slideNumber = index + 1;
                    tmpString = slides.slides[index].title;
                    html += '<button id="but' + slideNumber +'" type="button" onclick="SlideManager.display(' + slideNumber + ');">' + tmpString + '</button>';
                    //console.log( index + '. ' + tmpString );
                }
                showMessage( html, whereAbouts, appendMode );
                loadSnippet( './dsa/lectures/slideMenu.phtml', 'contentFooter', 'add' );   // put menu buttons on screen
            }
        };
        xhr.open("GET", filename, true);
        xhr.send();
    };

    function clearContentArea( ) {
        showMessage( 'Datastructures and Algorithms', 'contentHeader', 'add' );
        showMessage( 'Contacts: Jim Devon & Len Scott', 'mainMiddleContent', 'add' );
        showMessage( '', 'contentFooter', 'add' );
    }

    // jde, addded, 27/07/17
    // loads a json navigation file
    var loadNavigationDetails = function ( filename ) {
        xhr.onreadystatechange = function ( ) {
            if (xhr.readyState==4 && xhr.status==200) {
                localDebugging = true;
                clearContentArea();
                var data = JSON.parse( xhr.responseText );
                var navigationData = data.navigation;
                var contentData = data.content;

                var navClick = navigationData.navigationClick;
                var navLinks = navigationData.navigationLinks;
                var navLinksCount = navLinks.length;
                var navType = 'default'; // assume context is default
                if ( navClick == "SlideManager" ) {
                    navType = 'slide';  // set context to slide
                    SlideManager.initialise(contentData.contentFolder, contentData.contentContainerId, navLinksCount );
                    showMessage( contentData.header, 'contentHeader', 'add' );
                    loadSnippet( './dsa/lectures/slideMenu.phtml', 'contentFooter', 'add' );   // setup footer with nav buttons
                } else {
                    startUp(contentData.contentFolder, contentData.contentContainerId );
                    showMessage( '', 'contentFooter', 'add' );   // clear out content footer
                }

                // now build the link info
                var html = "<p>Link Count: " + navLinksCount + "</p>";
                var tmpString = "";
                var slideNumber = 0;
                var tmpLoadSnippetParametersString = "";
                var singleQuote = "'";
                var comma = ", ";
                for (var index = 0; index < navLinksCount; index ++) {
                    slideNumber ++;
                    tmpString = navLinks[index].title;
                    if ( navLinks[index].filename != "" ) { // only set up the file link info if filename is not empty
                        tmpLoadSnippetParametersString = singleQuote + contentData.contentFolder + navLinks[index].filename + singleQuote; // first parameter
                        tmpLoadSnippetParametersString += comma + singleQuote + contentData.contentContainerId + singleQuote; // second parameter
                        tmpLoadSnippetParametersString += comma + singleQuote + "add" + singleQuote;

                        // now get the click handler code setup
                        switch (navType) {
                            case 'slide' :
                                html += '<button id="but' + slideNumber + '" type="button" onclick="SlideManager.display(' + slideNumber + ');">' + tmpString + '</button>';
                                break;
                            case 'default' :
                                html += '<button id="but' + slideNumber + '" type="button" onclick="ContentLoader.loadSnippet(' + tmpLoadSnippetParametersString + ');">' + tmpString + '</button>';
                                break;
                        }
                    }
                }
                showMessage( html, navigationData.navigationContainerId, 'add' );   // put nav stuff onto page
                localDebugging = false;
            }
        };
        xhr.open("GET", filename, true);
        xhr.send();
    };

    var initialisations = function (XMLHttpRequestObject) {
        MainApp.LoggingHandler.initialise(GlobalData.debugging);
        if ( ( XMLHttpRequestObject == 'undefined' ) || ( XMLHttpRequestObject == null ) ) {
            XMLHttpRequestObject = XHRManager.getInstance();
            MainApp.LoggingHandler.logMessage(1, "ContentLoader initialised ... created new xhr:" + XMLHttpRequestObject);
        }
         // should have an XMLHttpRequestObject by now, so save it for use locally
         xhr = XMLHttpRequestObject;
         MainApp.LoggingHandler.logMessage(1, "ContentLoader initialised ... (xhr:" + XMLHttpRequestObject + ')' );
         return xhr;
     };

     return {
         initialise: initialisations,
         loadLectureDetails: loadLectureDetails,
         loadNavigationDetails: loadNavigationDetails,
         loadSnippet: loadSnippet
     }

 } ();
