﻿//timer
var _timer = null;

jQuery(document).ready(function () {
	//lms activity report comments section
	jQuery(".evaluationDataCommentsLink").fancybox({
		'frameHeight': 415,
		'frameWidth': 550,
		'centerOnScroll': false,
		'overlayShow': true,
		'hideOnContentClick': false
	});

	jQuery(".leaving-popup").fancybox({
		'frameHeight': 275,
		'frameWidth': 605,
		'centerOnScroll': false,
		'overlayShow': true,
		'hideOnContentClick': false
	});

	//activity and credit information modal
	//activity start modal
	jQuery("a.popup").fancybox({
		'frameHeight': 640,
		'frameWidth': 610,
		'centerOnScroll': false,
		'overlayShow': true,
		'hideOnContentClick': false
	});

	//state requirements modal
	//external activitues
	jQuery("a.manageStateLink,a.externalActivityLink,a.externalActivityEditLink").fancybox({
		'frameHeight': 400,
		'frameWidth': 550,
		'overlayShow': true,
		'hideOnContentClick': false,
		'callbackOnClose': function () {
			parent.location.reload(true);
		}
	});

	//claim moc credit link on activity summary page
	//various my moc modal calls
	jQuery("a.mocClaimLink,a.myMocModal").fancybox({
		'frameHeight': 350,
		'frameWidth': 550,
		'overlayShow': true,
		'hideOnContentClick': false,
		'centerOnScroll': false,
		'callbackOnClose': function () {
			parent.location.reload(true);
		}
	});


	//my moc page delete modal
	//my transcript delete link for external activities
	jQuery("a.delete_popup,a.popup_delete").fancybox({
		'frameHeight': 190,
		'frameWidth': 550,
		'overlayShow': true,
		'hideOnContentClick': false,
		'callbackOnClose': function () {
			parent.location.reload(true);
		}
	});

	//footer links
	jQuery("a.fancybox").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 550,
		'frameWidth': 550
	});

	//lms activity eula
	jQuery("div.eula-container").scroll(function () {
		var elem = jQuery("div.eula-container");
		//alert("Scroll Height: " + elem[0].scrollHeight + " Scroll Top: " + elem.scrollTop() + " Outer Height: " + elem.outerHeight());
		if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
			var button = jQuery("input.accept");
			button.removeClass("cancel-button");
			button.addClass("general-button");
			button.removeAttr('disabled');
		}
	});

	//expand and collapse functionality on the activity summary page
	jQuery('.table-style .expandCollapseImage').each(function (index, item) {
		//wire up click event for the li element
		jQuery(item).click(function (event) {
			var chaptersection = jQuery(item).attr('chaptersection');
			if (chaptersection != "") {
				if (jQuery('#chapterSection' + chaptersection).css('display') == 'table-row') {
					//hide
					jQuery(item).attr('src', '/images/lms/plus.png');
					jQuery('#chapterSection' + chaptersection).hide();
				}
				else {
					//show
					jQuery(item).attr('src', '/images/lms/minus.png');
					jQuery('#chapterSection' + chaptersection).show();
				}
			}
		});
	});

	//wire up click event for trial groups to change class
	jQuery('a.trialExpandBar').each(function (index, item) {
		//wire up click event
		jQuery(item).click(function (event) {
			//if the item is not required, lets make it completed
			if (jQuery(item).find('span.trial-title').length > 0) {
				jQuery(item).find('span.trial-title').addClass('trial-title-complete');
				jQuery(item).find('span.trial-title').removeClass('trial-title');
			}

			//if the item is required, lets make it completed
			if (jQuery(item).find('span.trial-title-required').length > 0) {
				jQuery(item).find('span.trial-title-required').addClass('trial-title-required-complete');
				jQuery(item).find('span.trial-title-required').removeClass('trial-title-required');
			}
		});
	});

	jQuery('.questionReportDropdown').change(function () {

		//verify attribute
		if (jQuery('.questionReportDropdown').attr('data_url') == null) {
			return;
		}

		var url = jQuery('.questionReportDropdown').attr('data_url');

		$(".questionReportDropdown option:selected").each(function () {
			var id = jQuery(this).val();
			id = id.replace('{', '');
			id = id.replace('}', '');
			window.location = url + '?id=' + id;
		});
	});

	//rich text audio links
	WireupRichTextAudioLinks();

	//rich text photo links
	WireupRichTextPhotoLinks();

	//rich text video links
	WireupRichTextVideoLinks();

	//restarts the timer on click of the exam submit button
	WireupExamSubmitButtons();

	//Make layout larger if there is not right sidebar
	ChangeLmsLayout();

	//Bookmark confirmation
	WireUpBookmarkConfirmations();

	//Audio
	WireUpAudio();

	//Exam Dropdown Selector
	WireUpResetButtons();

	//Exam Dropdown Selector
	SetExamSelectorDropdown();

	//make all presentation group items the same size
	//based on the largest group item
	SetPresentationGroupItems();

	//text article sidebar images
	SetTextArticleSidebarImages();

	//wires up the fancybox functionality for credit claiming
	SetClaimCreditButtons();

	//exam summary recommendations
	SetExamRecommendationLinks();

	//sets and limits the counter for the max amount of activities a user can select from
	LmsReportsMaximumSelectableActivities();

	// 'Select All' checkbox for report sub-filters
	LmsReportsSubfilterAllSelector();

	//sets up the behavior for the new report button
	WireUpCreateNewReportButton();
});

//Clears the reporting session and forward the user off to the report selector page
function WireUpCreateNewReportButton()
{
	jQuery('.btnNewReport').click(function (event) {
		
		//prevent default behavior
		event.preventDefault();

		//make ajax request to clear session
		jQuery.ajax({
			url: "/Services/LMS/ReportingService.asmx/ClearSession",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			type: 'POST',
			success: function (data) {
				//forward to selector page
				var url = jQuery('.btnNewReport').attr('data_url');
				if (url != null && url != '') {
					window.location = url;
				}
			},
			error: function () {
				console.log('Reporting Service call Clear Session failed');
			}
		});
	});
}


function LmsReportsMaximumSelectableActivities() {

    //if the attribute doesn't exist, return
    if (!jQuery('.reportActivitySelection').attr('Data_MaximumSelectableActivities')) {
        return;
    }

    MaximumSelectableActivities = parseInt(jQuery('.reportActivitySelection').attr('Data_MaximumSelectableActivities'));
    if (MaximumSelectableActivities == 0) {
        return;
    }

    jQuery('.checkboxClass').click(function (event) {

        jQuery('.reportActivitySelection input[type="checkbox"]').each(function (event, item) {

            //check for removing a selection
            if (!$(this).is(':checked')) {
                SelectedActivities--;
                return;
            }

            //adding a selection
            if (SelectedActivities >= MaximumSelectableActivities) {
                event.preventDefault();
                alert('You have reached the maximum amount of activities to select from.')
                return;
            }

            SelectedActivities++;
        });
    });
}


//sets and limits the counter for the max amount of activities a user can select from
var SelectedActivities = 0;
var MaximumSelectableActivities = 0;
function LmsReportsMaximumSelectableActivities() {

    //if the attribute doesn't exist, return
    if (!jQuery('.reportActivitySelection').attr('Data_MaximumSelectableActivities')) {
        return;
    }

    MaximumSelectableActivities = parseInt(jQuery('.reportActivitySelection').attr('Data_MaximumSelectableActivities'));
    if (MaximumSelectableActivities == 0) {
        return;
    }

    jQuery('.reportActivitySelection input[type="checkbox"]').click(function (event) {

        //check for removing a selection
        if (!$(this).is(':checked')) {
            SelectedActivities--;
            return;
        }

        //adding a selection
        if (SelectedActivities >= MaximumSelectableActivities) {
            event.preventDefault();
            alert('You have reached the maximum amount of activities to select from.')
            return;
        }

        SelectedActivities++;
    });
}

// 'Select All' checkbox for report sub-filters
function LmsReportsSubfilterAllSelector() {
    var allBox = jQuery('.subfilterAllCheckbox input[type="checkbox"]');
    if (allBox == null) { return; }

    // Change handler for 'Select All' box
    allBox.change(function () {
        if (this.checked) {
            jQuery('.reportActivitySelection input[type="checkbox"]').not('.subfilterAllCheckbox [type="checkbox"]').each(function () {
                this.checked = true;
            });
        } else {
            jQuery('.reportActivitySelection input[type="checkbox"]').not('.subfilterAllCheckbox [type="checkbox"]').each(function () {
                this.checked = false;
            });
        }
    });

    // Change handler for all sub-filter items
    jQuery('.reportActivitySelection input[type="checkbox"]').not('.subfilterAllCheckbox [type="checkbox"]').change(function () {
        if (!this.checked) {
            jQuery('.subfilterAllCheckbox input[type="checkbox"]').each(function () {
                this.checked = false;
            });
        }
        else {
            // If all are checked, check the allbox
            var uncheckedCount = jQuery('.reportActivitySelection input[type="checkbox"]').not('.subfilterAllCheckbox [type="checkbox"]').not(':checked').length;
            if (uncheckedCount == 0) {
                jQuery('.subfilterAllCheckbox input[type="checkbox"]').each(function () {
                    this.checked = true;
                });
            }
        }
    });
}

//rich text video links
function WireupRichTextVideoLinks() {
	jQuery('a.LightboxVideo').each(function(index, item) {
		//get height
		var height = parseInt(jQuery(item).attr("modalheight"));
		if (height > 600) {
			height = 600;
		}

		//get width
		var width = parseInt(jQuery(item).attr("modalwidth"));
		if (width > 800) {
			width = 800;
		}

		jQuery(item).fancybox({
			'frameHeight': height,
			'frameWidth': width,
			'overlayShow': true,
			'hideOnContentClick': false,
			'centerOnScroll': false
		});
	});
}

//rich text audio links
function WireupRichTextAudioLinks() {
	jQuery('a.LightboxAudio').fancybox({
		'frameHeight': 225,
		'frameWidth': 500,
		'overlayShow': true,
		'hideOnContentClick': false,
		'centerOnScroll': false
	});
}

//rich text photo links
function WireupRichTextPhotoLinks() {
	jQuery('a.LightboxImage').each(function(index, item) {
		//get height
		var height = parseInt(jQuery(item).attr("modalheight"));
		if(height > 600){
			height = 600;
		}
		
		//get width
		var width = parseInt(jQuery(item).attr("modalwidth"));
		if(width > 800){
			width = 800;
		}

		jQuery(item).fancybox({
			'frameHeight': height,
			'frameWidth': width,
			'overlayShow': true,
			'hideOnContentClick': false,
			'centerOnScroll': false
		});
	});
}

//restarts the timer on click of the exam submit button
function WireupExamSubmitButtons() {
	jQuery("#exam-wrapper input.submit-answer").click(function () {
		//only do this for timed exams
		//Pause timer when you click the 'Submit' button
		if (jQuery('#timerDisplay').length == 0) {
			return;
		}
		pauseTimer();
	});
	jQuery("#exam-wrapper input.submit-answer").ready(function () {
		//only do this for timed exams
		if (jQuery('#timerDisplay').length == 0) {
			return;
		}

		//check to see if the exam is complete
		if (jQuery('.timerCounterField').attr('examcomplete') != null && jQuery('.timerCounterField').attr('examcomplete') == 'true') {
			return;
		}
		playTimer();
	});
}

//exam summary recommendations
function SetExamRecommendationLinks() {

	jQuery("a.show_more").click(function() {
		//hide current link
		jQuery('a.show_more').hide();

		//show link
		jQuery('a.show_less').show();

		//hide
		jQuery('#recommend ul li.hide').removeClass('hide')
	});

	jQuery("a.show_less").click(function() {
		//hide current link
		jQuery('a.show_less').hide();

		//show link
		jQuery('a.show_more').show();

		//show only the first six
		jQuery('#recommend ul li.hide').removeClass('hide')

		jQuery("#recommend ul li").each(function(index, item) {

			//only start on the 5th index (6th record)
			if (index >= 6) {
				jQuery(item).addClass('hide');
			}
		});
	});
}

function ChangeLmsLayout() {

	//verify we have this class to target
	if (jQuery('.object-main-column, #object-main-column').length == 0) {
		return;
	}
	//if the right column exists, abort
	if (jQuery('#object-right-column').length > 0) {
		return;
	}

	//add class to widen the page where the right sidebar normally would be
	jQuery('.object-main-column, #object-main-column').addClass('object-main-column noRightColumn');
}

//Bookmark confirmation
function WireUpBookmarkConfirmations() {
	//bookmark delete confirmation
	jQuery('.bookmarkDeleteButton').each(function(index, item) {
		//wire up click event for each element
		jQuery(item).click(function(event) {
			if (jQuery(item).attr("bookmarktitle") != null) {
				//get title
				var title = jQuery(item).attr("bookmarktitle");

				//confirm box
				var r = confirm("Are you sure you want to delete this bookmark: " + title);

				//if they hit cancel, prevent default otherwise continue with default
				if (r != true) {
					event.preventDefault();
				}
			}
		});
	});
}

//claim credit link on activity summary page
//claim credit on the exam score summary page
function SetClaimCreditButtons() {
	jQuery("a.cmeClaimLink,a.claim-button").fancybox({
		'frameHeight': 715,
		'frameWidth': 550,
		'overlayShow': true,
		'hideOnContentClick': false,
		'centerOnScroll': false,
		'callbackOnClose': function() {
			parent.location.reload(true);
		}
	});
}

//resets the exam and postbacks to refresh
function WireUpAudio() {
	var id = jQuery('.flowPlayerAudio').attr('id');
	var playerHeight = parseInt(jQuery('.flowPlayerAudio').attr('playerHeight'));
	var playerWidth = parseInt(jQuery('.flowPlayerAudio').attr('playerWidth'));
	var playerRepeat = jQuery('.flowPlayerAudio').attr('playerRepeat');
	var audioPath = jQuery('.flowPlayerAudio').attr('href');

	$f(id, "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", {

		// fullscreen button not needed here
		plugins: {
			controls: {
				fullscreen: false,
				height: playerHeight,
				width: playerWidth,
				autoHide: false
			}
		},
		clip: {
			autoPlay: true,
			onBeforeFinish: function() {
				if (playerRepeat) {
					return false;
				}
			}
		}
	});
}

//resets the exam and postbacks to refresh
function WireUpResetButtons() {
	var serverSideId = jQuery("a.reset-buttonSummary").attr("serverSideId");
	jQuery("a.reset-buttonSummary").fancybox({
		'frameHeight': 195,
		'overlayShow': true,
		'hideOnContentClick': false,
		'callbackOnClose': function() {
			__doPostBack(serverSideId, 'reset');
		}
	});
}

//sets the fancybox for the sidebar images
function SetTextArticleSidebarImages() {
	//wire up anchors
	jQuery('.media a').each(function(index, item) {
		//verify we have the correct element attributes
		if (jQuery(item).attr('modalHeight') != null && jQuery(item).attr('modalWidth') != null) {

			//get height and width for popup from anchor element
			var height = parseInt(jQuery(item).attr("modalHeight"));
			var width = parseInt(jQuery(item).attr("modalWidth"));

			//wire up fancybox
			jQuery(item).fancybox({
				'frameHeight': height,
				'frameWidth': width,
				'overlayShow': true,
				'hideOnContentClick': false,
				'centerOnScroll': false
			});
		}
	});
}

function SetExamSelectorDropdown() {
	//only run if subnav is found
	if (jQuery('.topnav .subnav').length == 0) {
		return;
	}
		
	//close sub nav if clicked outside the selector area
	jQuery("body").click(function() {
		jQuery(".topnav ul.subnav").slideUp('fast');
	});
	jQuery("#selectorDiv").click(function(e) {
		e.stopPropagation();
	});

	//click event to open
	jQuery("#selectorDiv").click(function() {
		if (jQuery('.subnav').css('display') == "none") {
			//open window
			jQuery("ul.subnav").slideDown('fast').show();
		}
	});

	//wire up table links
	jQuery('.subnav li').each(function(index, item) {
		//wire up click event for the li element
		jQuery(item).click(function(event) {
			event.preventDefault();
			var clickable = jQuery(item).attr('clickable');
			if (clickable == "True") {
				var currentQuestionNumber = jQuery('#selector').html();
				var clickedQuestionNumber = jQuery(item).attr("questionnumber");
				__doPostBack(currentQuestionNumber, clickedQuestionNumber);
			}
		});
	});

	//my curriculum remove confirmation
	jQuery(".remove_btn").click(function() {
		return confirm("Are you sure you want to remove this item from you curriculum?");
	});
}

function SetPresentationGroupItems() {
	//find max height
	var maxHeight = 0;
	jQuery('ul.presentation').each(function(index) {
		//set height
		var thisHeight = jQuery(this).height();
		if (thisHeight > maxHeight)
			maxHeight = thisHeight;
	});

	//set max height
	jQuery('ul.presentation').each(function(index) {
		jQuery(this).css('height', maxHeight + 'px');
	});
}

function ToggleTrial(rel) {
	jQuery("a.toggle_link:not(a[rel='" + rel + "'])").parent().attr('class', 'trial-bar');
	jQuery("a.toggle_link:not(a[rel='" + rel + "'])").children('span.icon').attr('class', 'expand');
	jQuery('div.trial:not([rel=\'' + rel + '\'])').hide();

	var clickedLink = jQuery("a[rel='" + rel + "']");
	clickedLink.parent().toggleClass('trial-bar-selected');
	clickedLink.parent().toggleClass('trial-bar');
	clickedLink.children('span.icon').toggleClass('collapse');
	clickedLink.children('span.icon').toggleClass('expand');

	jQuery('div[rel=\'' + rel + '\']').slideToggle();

	return true;
}

function UncheckAllCheckBoxes(elementId) {
	if (elementId == null || elementId == undefined)
		return;

	jQuery(elementId + " input[type=checkbox]").each(function() {
		this.checked = false;
	});
}

function SetTimer() {
	if (jQuery('#timerDisplay')) {

		//check to see if the exam is complete
		if (jQuery('.timerCounterField').attr('examcomplete') != null && jQuery('.timerCounterField').attr('examcomplete') == 'true') {
			DisableTimerAndShowDuration();
			return;
		}

		//if the timer is already initialized, return
		if (_timer != null) {
			return;
		}

		_timer = jQuery.timer(function() {
			//exam is not complete, increment display
			if (jQuery('#timerDisplay').html() == '') {
				jQuery('#timerDisplay').html(GetTimerValue(false));
			}
			else {
				jQuery('#timerDisplay').html(GetTimerValue(true));
			}
		});
	}

	if (_timer != null) {
		_timer.set({ time: 1000, autostart: true });
	}
}

function GetTimerValue(increment) {
	//convert to time object
	var count = parseInt(jQuery('.timerCounterField').val());
	if (isNaN(count)) {
		count = 0;
	}

	//set back to counter field
	if (increment) {
		count++;
	}
	
	jQuery('.timerCounterField').val(count)

	//break down seconds into time object
	var time = secondsToTime(++count);

	//break down
	var hours = time['h'];
	var minutes = time['m'];
	var seconds = time['s'];

	//hours
	if (hours < 10) {
		hours = '0' + hours;
	}
	
	//minutes
	if (minutes < 10) {
		minutes = '0' + minutes;
	}

	//seconds
	if (seconds < 10) {
		seconds = '0' + seconds;
	}

	//concatenation
	return hours + ':' + minutes + ':' + seconds;
}

function playTimer() {
	//hide start button element
	jQuery('#timerStartButton').hide();

	//show pause button element
	jQuery('#timerPauseButton').show();

	//verify duration label is not shown
	jQuery('#durationLabel').hide();

	//initiate play
	if (_timer == null) {
		return;
	}

	_timer.play();
}

function pauseTimer() {

	//hide pause button element
	jQuery('#timerPauseButton').hide();

	//show start button element
	jQuery('#timerStartButton').show();

	//verify duration label is not shown
	jQuery('#durationLabel').hide();
	jQuery('.timer').removeClass('timerDuration');
	jQuery('.timerLeft').removeClass('timerDuration');
	
	//initiate pause
	_timer.pause();
}

function DisableTimerAndShowDuration() {
	//hide pause button element
	jQuery('#timerPauseButton').hide();

	//show start button element
	jQuery('#timerStartButton').hide();

	//show duration label
	jQuery('#durationLabel').show();
	jQuery('.timer').addClass('timerDuration');
	jQuery('.timerLeft').addClass('timerDuration');

	//show duration value
	jQuery('#timerDisplay').html(GetTimerValue(false));

	//initiate pause
	if (_timer != null) {
		_timer.pause();
	}
}

function secondsToTime(secs) {
	var hours = Math.floor(secs / (60 * 60));

	var divisor_for_minutes = secs % (60 * 60);
	var minutes = Math.floor(divisor_for_minutes / 60);

	var divisor_for_seconds = divisor_for_minutes % 60;
	var seconds = Math.ceil(divisor_for_seconds);

	var obj = {
		"h": hours,
		"m": minutes,
		"s": seconds
	};
	return obj;
}
