/* JQuery initialization code */
$(document).ready(function () {

    //menu logo click handler
    $("#menulogo").click(function (event) {
        document.location = '/Home.aspx';
    });

    //menu logo mouse over/out handler
//    $("#menulogo").mouseover(function (event) {
//        $("#logoImg").attr("src", "/Portals/0/top_menu_logo_bw.jpg");
//    }).mouseout(function (event) {
//        $("#logoImg").attr("src", "/Portals/0/top_menu_logo.jpg");
//    });

    //training on demand page
    //add click handlers to class section headers
    $("#ondemandWrapper .classHeader").each(function () {

        //set href to void
        $(this).find("> a").attr("href", "javascript:void(0);");

        //get section id
        var id = $(this).next().children().attr("id");

        //add click handler to show class section
        $(this).click(function () {
            showClasses("#" + id);
        });

    });

    //sets up class dates to show on reg icon click
    $("table.liveClasses .registerFacLink").each(function () {

        $(this).click(function () {
            $(this).next().slideToggle('slow');
        });

    });
    
    $("#registerDiv span").click(function(){
        $("#classDatesPopUp").slideToggle('slow');
    });

    //set up search
    $("#qcSearchTxt").keypress(function (event) {
        if (event.which == 13) {
            event.preventDefault();

            document.location = "/SearchResults.aspx?search=" + $(this).val();
        }
    });

    //add placeholders to inputs if they aren't supported
    if (!Modernizr.input.placeholder) {

        $("input[placeholder], textarea[placeholder]").each(function () {

            if ($(this).val() == "") {
                $(this).val($(this).attr("placeholder"));
                $(this).focus(function () {
                    if ($(this).val() == $(this).attr("placeholder")) {
                        $(this).val("");
                        $(this).removeClass("placeholder");
                    }
                });
                $(this).blur(function () {
                    if ($(this).val() == "") {
                        $(this).val($(this).attr("placeholder"));
                        $(this).addClass("placeholder");
                    }
                });
            }

        });
    }

});

/*
Used on the training site for showing/hiding On Demand class lists
*/
function showClasses(section) {

    //hide all classes before showing the new one
    $(".classSectionWrapper").removeClass("leftArrow");
    $(".classSectionWrapper > div > div").hide();
    
    //toggle classes
    $(section).fadeIn(500);
    $(section).parent().parent().addClass("leftArrow");

}
function hideClasses(section) {
    $(".classSectionWrapper").removeClass("leftArrow");
    $(section).fadeOut(500);
}

function showGuidelines() {

    $('#trnGruidelines').fadeIn(500);

    //$('#trnGruidelines').css("top", (($(window).height() - $('#trnGruidelines').outerHeight()) / 2) + $(window).scrollTop() + "px");
    $('#trnGruidelines').css("left", (($("#trnGruidelines").parent().width() - $('#trnGruidelines').outerWidth()) / 2) + "px");

}

function toggleTrainingHelp() {
    $("#helpContent").fadeIn(500);
}

/* simple popup window 
	 args:
	 url : web address to load
	 height: height of window
	 width: width of window
*/
var newwindow;
function popupWin(url, height, width)
{
	newwindow=window.open(url,'newWin','height='+height+',width='+width);
	if (window.focus) {newwindow.focus()}
}

/**
show/hide help info.
If help is already visible, hide it.  If not, show it.
param: useWindow - boolean. Should use window for centering.
**/
function toggleHelp(useWindow) {

    var infoDiv = document.getElementById("helpContent");

    if (!infoDiv) return;

    toggleDiv(infoDiv, useWindow);

}

/**
shows/hides div
param: infoDiv - div to use
param: useWindow - boolean. Should use window for centering.
**/
function toggleDiv(infoDiv, useWindow) {

    if (infoDiv.style.display == "block") {
        infoDiv.style.display = "none";
        return;
    } else {
        //center help
        //container width
        var winWidth = 960; //width of menu container
        if (useWindow) {
            winWidth = $(window).width();
        }
    }

    //get help div width (parseInt strips the 'px' - hip hip harrayyy)
    var helpWidth = parseInt($(infoDiv).css('width'));
    //get left point for help div 
    var divLeft = (winWidth / 2) - (helpWidth / 2);
    infoDiv.style.left = parseInt(divLeft) + "px";

    //display
    infoDiv.style.display = "block";

}

/**
show/hide help info for the Cust Admin page.
This area needs it's own function because we need to distingish between which page is being shown.  
All pages use the same help button.
param: page - which help doc to show
**/
function toggleMyAdminHelp(page) {

    var infoDiv = document.getElementById(page);

    if (!infoDiv) return;

    toggleDiv(infoDiv, true);
}

/**
updates order trac iframe window
*/
function showPage(page) {
	
	var frame = document.getElementById("ordertracIframe");
	
	if(frame) {
		
		frame.src = page + '.aspx';
		
	}
}

/**
 * Generic image updater.  Pass in image url and img id
 */
function updateImage(imgUrl, imgObjId) {
    try {
        var imgObj = document.getElementById(imgObjId);
        if (imgObj) {
            imgObj.src = imgUrl;
        }
	} catch(e) {
		//pass through.  Don't crash browser javascript engine
	}
}

/**
* Show's site info on contact page when hovering over site
* 
*/
function showSiteInfo(top, left, imageName, height, width) {

    //check for ie9 compat mode
    if (navigator.userAgent.indexOf("MSIE 7") > -1 || navigator.userAgent.indexOf("MSIE 8") > -1) {
        top -= 430;
        left -= 230;
    }
    
    var jqObjDiv = $('div#siteInfoDiv');
    
    var ht = 123;
    if (height) ht = height; 
    
    var wd = 183;
    if (width) wd = width; 

    jqObjDiv.height(ht).width(wd).css({ backgroundImage: "url(/Portals/0/" + imageName + ")", top: top + "px", left: left + "px" });

    jqObjDiv.fadeIn(700);

}

/**
* Hide's site info on contact page when hovering out of site hot spot
* 
*/
function hideSiteInfo() {
    $('#siteInfoDiv').fadeOut(200);
}


function showLoadingIcon() {

    var loadingFilterDiv = document.getElementById("loadingFilterDiv");

    if (loadingFilterDiv) {
        loadingFilterDiv.style.display = "block";
    }

    var loadingBox = document.getElementById("loadingIconDiv");

    
    //get browser window width
    var winWidth = $(window).width();
    //get left point for loading div (254 is div width. 254/2 = 127)
    var divLeft = (winWidth/2) - 127;

    if (loadingBox) {
        loadingBox.style.left = divLeft + "px";
        loadingBox.style.display = "block";
    }

}

function bindLoadingIcon() {

    //there has to be a better way to pull this particular input.
    //it has no id and a dynamic name so I don't know of one
    var inputs = document.getElementsByTagName("input");

    if (!inputs) return;

    for (var i = 0; i < inputs.length; i++) {

        if (inputs[i].value == "View Report" || inputs[i].value == "Search") {
            inputs[i].setAttribute('onclick', 'showLoadingIcon()'); 
        }
    }
}

//training prompt to delete a class

function promptDeleteClass(id, page) {
    var answer = confirm("Are you sure you want to delete this class?")
    if (answer) {
        window.location = page + "?d=" + id;
    }
}

function promptCancelScheduledClass(id) {
    var answer = confirm("Are you sure you want to cancel this scheduled class?")
    if (answer) {
        window.location = "LiveClassesManager.aspx?d=" + id;
    }
}


//training captivate needed functions

//xml function used to create captivate xml results
function getQuizDataAsXML(quiz) {

    var courseXML = element("Course",

       capElement("CompanyName", "QuantumClean") + "\n" +
       capElement("DepartmentName", "Training") + "\n" +
       capElement("CourseName", "NA") + "\n" +
       capElement("LearnerName", "NA") + "\n" +
       capElement("LearnerID", "NA") + "\n" +
       capElement("LessonName", "NA") + "\n" +
       capElement("QuizAttempts", "NA") + "\n" +
       capElement("TotalQuestions", "NA") + "\n" +

       element("Result",

            element("CoreData",

                capElement("Status", quiz.status) + "\n" +
                capElement("Location", quiz.location) + "\n" +
                capElement("RawScore", quiz.rawscore) + "\n" +
                capElement("MaxScore", quiz.maxscore) + "\n" +
                capElement("MinScore", quiz.minscore) + "\n" +
                capElement("SessionTime", quiz.time) + "\n"

            ) + "\n" +

            element("InteractionData",

                element("Interactions",

                    capElement("Date", "NA") + "\n" +
                    capElement("InteractionTime", "NA") + "\n" +
                    capElement("InteractionID", "NA") + "\n" +
                    capElement("ObjectiveID", "NA") + "\n" +
                    capElement("InteractionType", "NA") + "\n" +
                    capElement("CorrectResponse", "NA") + "\n" +
                    capElement("StudentResponse", "NA") + "\n" +
                    capElement("Result", "NA") + "\n" +
                    capElement("Weight", "NA") + "\n" +
                    capElement("Latency", "NA") + "\n" +
                    capElement("Attempt", "NA") + "\n"

                ) + "\n"

            ) + "\n"

       ) + "\n"
    );

    return courseXML;
}

// xml element creator specific for captivate elements (no content)
function capElement(name, value) {

    var xml = '<' + name + ' value="' + value.replace("\"", "") + '"/>' 

    return xml
}

// basic xml element
function element(name, content) {
    var xml
    if (!content) {
        xml = '<' + name + '/>'
    }
    else {
        xml = '<' + name + '>' + content + '</' + name + '>'
    }
    return xml
}

/* =================================================
convertCaptivateData properties
The object contains all of the reporting values that were sent from Captivate. 
convertCaptivateData also creates a new property named accuracy, which is a percentage created using the formula (rawscore/maxscore) * 100. Our final list of properties is:

status
location
rawscore
maxscore
minscore
time
accuracy
==================================================== */

convertCaptivateData = function (a) { if (!a) { return false } a = a.replace(/\"|Core Data\|/g, ""); var b = a.split("||")[0].split("|"); var c = b[0].split(","); var d = b[1].split(","); if (!d || !c || d.length < 1 || c.length < 1 || d.length !== c.length) { return false } var e = {}; for (var i = 0; i < c.length; i++) { var f = c[i].replace(/\s/g, "").toLowerCase(); var g = d[i]; e[f] = g } if (e.rawscore !== null && e.maxscore !== null) { e.accuracy = (e.rawscore / e.maxscore) * 100 } return e };

function appendEmailBody() { } //called by captivate, added to prevent errors
function sendMail() { }        //called by captivate, added to prevent errors

function padMail(strAddress, strSubject, strBody) {

    //Forward parameter strBody to our custom function.
    var quiz = convertCaptivateData(strBody);

    //Do something with 'quiz' object
    alert("status: " + quiz.status + "\n" +
          "location: " + quiz.location + "\n" +
          "rawscore: " + quiz.rawscore + "\n" +
          "maxscore: " + quiz.maxscore + "\n" +
          "minscore: " + quiz.minscore + "\n" +
          "time: " + quiz.time + "\n" +
          "accuracy: " + quiz.accuracy);
    alert(strBody);

}

//possible issue that sendMail is called instead of padMail
function sendMail(strAddress, strSubject, strBody) {

    padMail(strAddress, strSubject, strBody);
    
}
