﻿var C_FAV_TYPE_YOUR_QUESTION = "";

var START_SESSION_OVERRIDE = false;
var START_SESSION_QS = '';
var START_SESSION_TIMEOUT = 0;

var PRESESSION_ADVANCED_MODE = false;
var IS_IE = false;

function doClassroom(analyticsTrackId, fileUploadId, whiteboardId, ignoreLowBalance) {

	//if js vars haven't loaded yet, try again
	if (typeof CLASSROOM_CAN_CONNECT == 'undefined') {
		setTimeout("doClassroom('" + analyticsTrackId + "', '" + fileUploadId + "', '" + whiteboardId + "', '" + ignoreLowBalance + "')", 500);
		return;
	}

	//check req fields
	if (typeof Page_ClientValidate != 'undefined' && Page_ClientValidate() == false)
		return;

	if (typeof analyticsTrackId != 'undefined') {
		Analytics_TrackPage('/account?start=' + analyticsTrackId, '/account?start=' + analyticsTrackId)
	}

	/*check
	1) do they have a low balance 
	2) AND this is not an override or it is but they closed the spotlight instead of clicking a button (so we want to show the spotlight again)
	if true then show the low balance notificatin overlay
	else pop the classroom
	*/
	START_SESSION_OVERRIDE = false;

	//check file
	if (typeof fileUploadId != 'undefined' && isValidFile(fileUploadId, true) == false) {
		return;
	}

	//#OS# store whiteboard messages in hidden field
	if (typeof whiteboardId != 'undefined' && document.getElementById(whiteboardId) != null) {
		document.getElementById(whiteboardId).value = top.IEnvironmentManager_GetPreSessionWhiteboardMessages().toString();
		//#OS# clearing whiteboard messagges so that they don't get accumulated if user makes another session request
		top.IEnvironmentManager_ClearPresessionMessage();
	}

	if (CLASSROOM_MINUTES < CLASSROOM_MINUTES_BELOW
        && (typeof (ignoreLowBalance) == 'undefined' || ignoreLowBalance == null || ignoreLowBalance == false)
    ) {
		doClassroomSubmit(false, '2'); //#OS# account ballance is low
	}
	else {
		//#OS# loading classroom; determining either to open it in new window or not based on if user
		//is remebered or logged in
		if (isRemembered() == true || CLASSROOM_CAN_CONNECT == 'True')
			doClassroomSubmit(true, '1');
		else
			doClassroomSubmit(false, '1');
	}
}

function doStartASession(loc, qs, isOld, ignoreLowBalance) {
	//if js vars haven't loaded yet, try again
	if (typeof CLASSROOM_CAN_CONNECT == 'undefined') {
		setTimeout("doStartASession('" + loc + "','" + qs + "'," + isOld + "," + ignoreLowBalance + ")", 500);
		return;
	}

	if (typeof loc != 'undefined') {
		Analytics_TrackPage('/account?start=' + loc, '/account?start=' + loc)
	}

	//we are are not launching after showing the low balance notificaiton then reset the START_SESSION_QS var
	if (typeof (START_SESSION_QS) == 'undefined' || START_SESSION_QS == '') {
		START_SESSION_QS = (typeof qs != 'undefined') ? qs : (typeof CLASSROOM_QS != 'undefined') ? CLASSROOM_QS : '';
	}

	//are they just reviewing a session? if so, then we don't care if they can connect or not
	var isReview = (START_SESSION_QS.indexOf('RSId=') != -1);

	if (isReview || CLASSROOM_CAN_CONNECT == 'True') {
		/*check
		1) do they have a low balance 
		2) AND this is not an override
		3) AND it's not review (we just want to open the classroom no matter what for review)
		if true then show the low balance notificatin overlay
		else pop the classroom
		*/
		if (CLASSROOM_CAN_CONNECT == 'True'
    			&& CLASSROOM_MINUTES < CLASSROOM_MINUTES_BELOW
                && (typeof (ignoreLowBalance) == 'undefined' || ignoreLowBalance == null || ignoreLowBalance == false)
                && !isReview
            ) {

			SpotlightElement('You are almost out of minutes!', null, 700, 450, jQuery('#StartASessionMinutesOverlay').children('.spotlight_content').html());

			START_SESSION_OVERRIDE = true;
			Analytics_TrackPage('/overlay/lowBalanceDecision', '/overlay/lowBalanceDecision')
			return;
		}
		else {
			START_SESSION_OVERRIDE = false;

			//old or new classroom?
			if (typeof isOld == 'undefined' || isOld == false) {
				popSilverlightClassroomWindow(START_SESSION_QS);

			} else {
				popStudentClassroomWindow(START_SESSION_QS);
			}

			//reset query string variable
			START_SESSION_QS = '';

			//remove cookie that tracks sessions for callouts
			jQuery.cookie("minutes_left", null);
		}
	}

	/*redirect if: 
	a) we are not currently on the page we want to be on
	b) it's not a review
	*/
	else if (requiresRedirect()) {
		if (CLASSROOM_CAN_CONNECT == 'True') {
			window.location = CLASSROOM_URL_REDIRECT; //if we opened the classroom then don't add var to query
		} else {
			redirectWithGetATutorQuery();
		}
	}
}

function replaceMinutesInOverlay() {

	if ($('StartASessionMinutesOverlay') != null) {
		//get the element we need
		var el = $('StartASessionMinutesOverlay').down('.spotlight_content').down('p');
		//adjust grammar if only have 1 minute
		if (CLASSROOM_MINUTES == 1) {
			el.innerHTML = el.innerHTML.replace('xx minutes', 'xx minute');
		}
		//replace 'xx' with minutes
		el.innerHTML = el.innerHTML.replace('xx', CLASSROOM_MINUTES);
	}
}

function removeFile() {
	//need to re-write the elemnt (IE won't let you set value property)
	document.getElementById('fileuploaddiv').innerHTML = document.getElementById('fileuploaddiv').innerHTML;
}

function isValidFile(fileUploadId, showWarning) {

	var sFileName = '';

	if (document.getElementById(fileUploadId) != null)
		sFileName = document.getElementById(fileUploadId).value;

	if (sFileName != '') {
		// check extension
		var sFileExtension = sFileName.substring(sFileName.lastIndexOf(".") + 1).toLowerCase();

		var allowedExtensions = ["bmp", "doc", "docx", "gif", "htm", "html", "jpg", "jpeg", "pdf", "ppt", "pptx", "rtf", "txt", "xls", "xlsx", "zip"];

		var bAllowed = false;

		for (x = 0; x < allowedExtensions.length; x++) {
			if (sFileExtension == allowedExtensions[x]) {
				bAllowed = true;
				break;
			}
		}

		// render judgment
		if (bAllowed == false) {
			var allowedExtensionsStr = "";
			for (var i = 0; i < allowedExtensions.length; i++) {
				allowedExtensionsStr = allowedExtensionsStr + ", " + allowedExtensions[i];
			}
			allowedExtensionsStr = allowedExtensionsStr.substring(2);

			alert("The file type you have chosen is not allowed. \n\n" +
						"Accepted file formats are: " +
						allowedExtensionsStr
				);

			return false;
		}
		else {
			//warn about sharing personal information.
			if (!showSharingPersonalInfoDialog(showWarning))
				return false;
		}
	}

	return true;
}

function spotlightAdvancedOptions(presessionAdvancedUrl) {

	var selectedTopic = jQuery('.presession_topics').find('input[type="radio"]:checked').val();
	var selectedSubtopic = jQuery('.presession_sub_topics_list').val();

	if (typeof (selectedSubtopic) == 'undefined')
		selectedSubtopic = '';

	var favTutor = '';
	if (jQuery('#favTutorsList').length > 0)
		favTutor = jQuery('#favTutorsList').val();
	
	var question = jQuery('.presession_question_textarea').val();	
	if (typeof question == 'undefined')
		question = '';

	var topicName = '';
	switch (selectedTopic) {
		case 'rdbMath':
			topicName = 'Math';
			break;
		case 'rdbScience':
			topicName = 'Science';
			break;
		case 'rdbEnglish':
			topicName = 'English';
			break;
		case 'rdbSocialStudies':
			topicName = 'SocialStudies';
			break;
	}

	if (favTutor == C_FAV_TUTORS_CHOOSE_PROMPT)
		favTutor = '';

	if (question == C_FAV_TYPE_YOUR_QUESTION)
		question = '';
	else
	{
		question = escape(question);
		
		if (question.length > 2000)
			question = question.substring(0, 1999);
	}

	var queryString = '?';
	if (presessionAdvancedUrl.indexOf('?') > 0)
		queryString = '&';

	queryString += 'topic=' + topicName + '&subtopic=' + selectedSubtopic + '&favtutor=' + favTutor + '&question=' + question;

	SpotlightElement('Get a Tutor', null, 885, 485, '<iframe frameborder="0" src="' + presessionAdvancedUrl + queryString + '" width="855" height="420"></iframe>');
}

//personal information warning.
var sharingPersonalInfoDialogMsg = "Please ensure the document you are about to share \ncontains no personal information such as your name, email \naddress or school. \n\nClick 'Cancel' to not share this file so you can remove \npersonal information from the file.";
function showSharingPersonalInfoDialog(showWarning) {

	if (showWarning) {
		if (window.confirm(sharingPersonalInfoDialogMsg))
			return true;
		else
			return false;
	} else
		return true;

}

function showLowBalanceSpotlight() {

	if (PRESESSION_ADVANCED_MODE == true) {
		window.parent.showLowBalanceSpotlight();
		return;
	}

	SpotlightElement('You are almost out of minutes!', null, 700, 450, jQuery('#StartASessionMinutesOverlay').children('.spotlight_content').html());
	jQuery('#SpotlightControl_JQuery').find('#get_tutor_overlay_btn').click(function() { doClassroomSubmit(true, '3'); TurnSpotlightOff(this); });

	START_SESSION_OVERRIDE = true;
	Analytics_TrackPage('/overlay/lowBalanceDecision', '/overlay/lowBalanceDecision')
}

function doClassroomSubmit(intoBlankClassroomWin, preSessionSubmitMode) {

	if (document.getElementById('PreSessionSubmitMode') != null)
		document.getElementById('PreSessionSubmitMode').value = preSessionSubmitMode;

	if (intoBlankClassroomWin == true) {
		//pop classroom
		var classroomWindow = popBlankClassroomWin(1004, 663, 'no');
		if (classroomWindow == null)
			return;

		document.forms[0].target = 'classroomWindow';
	}
	else
		submitTheForm();
}

function submitTheForm() {
	try {
		document.forms[0].submit();

		//#OS# resetting form so that we don't get into the session when page gets refreshed (case 4679)
		resetTheForm();

		if (PRESESSION_ADVANCED_MODE == true && CLASSROOM_MINUTES >= CLASSROOM_MINUTES_BELOW) {
			//#OS# resetting pre-session control (case 4737)
			window.parent.resetTheForm();
		
			//#OS# closing advanced options spotlight (case 4682)
			//we don't close it in case balance is low; it will be replaced by "low balance" spotlight instead
			window.parent.TurnSpotlightOff();
		}
	}
	catch (e) {
		if ((e.number & 0xFFFF).toString() == "5") {
			flipLoading(false, hRefId);

			if (classroomWindow)
				classroomWindow.close();

			alert('The input file could not be found. Please try again.');

			return;
		}
	}
}

function resetTheForm() {
	jQuery(':radio[value=rdbMath]').attr('checked', true);
	
	if (typeof(populateSubtopics) != 'undefined')
		populateSubtopics('Math');

	jQuery('.presession_sub_topics_list').val(0);
	jQuery('.presession_question_textarea').val('');
	jQuery('#PreSessionSubmitMode').val('');
}

function isRemembered() {

	if (jQuery.cookie('displayname') != null && jQuery.cookie('minutes_left') != null)
		return true;
	else
		return false;
}

function popWindow(url) {
	//pop window
	posX = (screen.availWidth / 2) - 470;
	posY = (screen.availHeight / 2) - 300;

	url = 'http://' + CLASSROOM_URL_PREFIX + url;

	var win = window.open(url, '', 'resizable=yes,scrollbars=yes,width=940,height=600,left=' + posX + ',top=' + posY + ',screenX=' + posX + ',screenY=' + posY);
	win.focus();
}

function requiresRedirect() {
	//set the cases just to be sure
	var currLoc = window.location.toString().toLowerCase();
	CLASSROOM_URL_REDIRECT = CLASSROOM_URL_REDIRECT.toLowerCase();

	//strip default.aspx out of both strings
	currLoc = currLoc.replace('default.aspx', '');
	CLASSROOM_URL_REDIRECT = CLASSROOM_URL_REDIRECT.replace('default.aspx', '');

	//use the last index in case we're redirecting to the root ('/')
	var posRedirect = currLoc.lastIndexOf(CLASSROOM_URL_REDIRECT);

	//if the current location doesn't contain the redirect
	//  this is the most common scenario so we're checking first
	if (posRedirect == -1) {
		return true;
	}

	//make sure the current location isn't another page in the same folder
	// i.e. we want to redirect to /account/ and we are currently at /account/notdefault
	// so check the index of the redirect (which will be shorter since it'll never contain http:// etc)
	//  the index of the redirect in the curr location + length of redirect should equal length of curr loc if we are on the same page
	var lenCurr = currLoc.length;
	var lenRedirect = CLASSROOM_URL_REDIRECT.length;
	if ((posRedirect + lenRedirect) != lenCurr) {
		return true;
	}

	return false;
}

function redirectWithGetATutorQuery(loc) {
	var url;
	if (typeof loc == 'undefined')
		url = CLASSROOM_URL_REDIRECT;
	else
		url = loc;

	//if it hasn't already been added
	if (url.indexOf('getatutor') == -1) {

		//see if there are already query parameters
		if (url.indexOf('?') == -1)
			url += '?';
		else
			url += '&';

		//rmg: always go to account homepage after login
		//        //rmg: if we're not on the homepage, put the location we're at now on the querystring "Go" param so that we get redirected back here if we login
		//        if (location.pathname != "/" && location.pathname != "/default.aspx")
		//        {
		//            //aem: if we came from a frameset page, we need to go back to the frameset and not just the top frame.
		//            if (location.pathname.substr(0,32).toLowerCase().match("/resources/resourceframetop.aspx") != null)
		//            {
		//                //we actually want the url of the framesetpage WITH the id of the content item.
		//                var urlToFrameset = '/resources/resourceframe.aspx';
		//                url += 'go=' + encodeURIComponent(urlToFrameset) + encodeURIComponent(encodeURIComponent(location.search));
		//            }
		//            else
		//            {
		//			    url += 'go=' + encodeURIComponent(location.pathname) + encodeURIComponent(encodeURIComponent(location.search));
		//			}
		//		}

		url += 'getatutor=';

		//if no query then just set to '1' else set with query string
		if (START_SESSION_QS == '')
			url += '1';
		else {
			//we need to encode the query string twice so if it's not encoded right now then encode
			if (START_SESSION_QS.indexOf('?') != -1) {  //if there's a ?
				START_SESSION_QS = encodeURIComponent(START_SESSION_QS);
			}
			//encode again
			url += encodeURIComponent(START_SESSION_QS);
		}
	}

	//aem: case 3011: setting the location of 'top' instead of 'window' will ensure that we break out of the frame faster.	
	top.location = url;
}

function popStudentClassroomWindow(prevSessionGuid) {
	if (popStudentClassroomWindow.caller != doStartASession)
		return;

	//checking for necessary space (with slight padding)
	if (screen.availWidth < 857)
		width = 780;
	else
		width = 857;

	if (screen.availHeight < 665)
		height = 550;
	else
		height = 665;

	url = 'http://' + CLASSROOM_URL_PREFIX + '/Apps/SocWeb/Main.aspx';

	if (typeof prevSessionGuid != 'undefined')
		url += '?SessionGuid=' + prevSessionGuid;

	popClassroomWin(url, width, height, 'yes');
}

function popSilverlightClassroomWindow(qs) {	
	url = 'http://' + CLASSROOM_URL_PREFIX + '/Classroom/SLDetector.aspx' + ((typeof qs == 'undefined') ? '' : qs);

	popClassroomWin(url, 1004, 663, 'no');
}

function popClassroomWin(url, width, height, scrollbars) {
	//if get called by an html link, ignore
	if (popClassroomWin.caller == null)
		return;

	var classroomWin = popBlankClassroomWin(width, height, scrollbars);

	classroomWin.location = url;
	classroomWin.focus();
}

function popBlankClassroomWin(width, height, scrollbars) {
	posX = (screen.availWidth / 2) - (width / 2);
	posY = (screen.availHeight / 2) - (height / 2);

	//open up the classroom window; below, we will check to make sure the window has opened before posting to it
	// we will do all the work we can until we need to Post (to give the window as much time as possible to open)				
	var classroomWin;
	try {
		classroomWin = window.open('', 'classroomWindow', 'scrollbars=' + scrollbars + ',resizable,width=' + width + ',height=' + height + ',left=' + posX + ',top=' + posY + ',screenX=' + posX + ',screenY=' + posY);

		/* if the window is already open, this will either:
		- throw an exception when accessing .location (FireFox)
		- location won't be blank and we'll explicitly throw the exception (IE)
		*/
		if (classroomWin.location != 'about:blank') {
			throw "alreadyOpen";
		}
		
		//#OS# loading some page to prevent security problem with IE (case 4698)
		classroomWin.location.href = '/misc/PreSessionPost.aspx';
	}
	catch (e) {
		//if we throw an exception here, it means the window is already open
		alert("Please first close your current classroom window.");
		return null;
	}

	classroomWin.focus();
	return classroomWin;
}

