
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 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 autoLaunch(showReceipt) {
//    //show or hide info on printing receipt later
//    if (showReceipt) {
//        $('autoLaunchReceiptInfo').show();
//    } else {
//        $('autoLaunchReceiptInfo').hide();
//    }
//    //set up the spotlight
//    OLD_SPOTLIGHT_CONTENT_LOCATION = $('AutoLaunchClassroomOverlay');
//    SpotlightElement("You're ready to get a tutor!");
//    //make sure start a session will happen without an low balance notification
//    START_SESSION_OVERRIDE = true;
//    Analytics_TrackPage('/overlay/autoLaunchClassroom', '/overlay/autoLaunchClassroom')
    return;
}
		
var START_SESSION_OVERRIDE = false;
var START_SESSION_QS = '';
var START_SESSION_TIMEOUT = 0;
function doStartASession(loc, qs, isOld) {
    //if js vars haven't loaded yet, try again
    if (typeof CLASSROOM_CAN_CONNECT == 'undefined') {
        setTimeout("doStartASession('" + loc + "," + qs + "," + isOld + "')", 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 (CLASSROOM_CAN_CONNECT == 'True' || isReview || (document.cookie.match('username') != null)) {
        /*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)
        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_MINUTES < CLASSROOM_MINUTES_BELOW
                && (!START_SESSION_OVERRIDE || (START_SESSION_OVERRIDE && OLD_SPOTLIGHT_CONTENT_LOCATION == null))
                && !isReview
            ) {
            OLD_SPOTLIGHT_CONTENT_LOCATION = $('StartASessionMinutesOverlay');
            SpotlightElement('You are almost out of minutes!');
            START_SESSION_OVERRIDE = true;
            Analytics_TrackPage('/overlay/lowBalanceDecision', '/overlay/lowBalanceDecision')
            return;
        } 
        else {
            START_SESSION_OVERRIDE = false;

            //decode the query string before we send it to the classroom
            START_SESSION_QS = decodeQueryString(START_SESSION_QS);
            
            //old or new classroom?
            if (document.cookie.match('username') != null)
            {
            	var page = "/LoginInClassroom.aspx";
            	if (CLASSROOM_CAN_CONNECT)
            		page = "/Classroom/SLDetector.aspx";
					
                var url = 'http://' + CLASSROOM_URL_PREFIX + page + ((typeof START_SESSION_QS == 'undefined') ? '' : START_SESSION_QS);

                popClassroomWin(url, 984, 665, 'no');
                
            } else 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
            Cookie.erase('total_sessions');
        }
    }
		
    /*redirect if: 
    a) we are not currently on the page we want to be on
    b) it's not a review
    */
    if (requiresRedirect() && !isReview && (document.cookie.match('username') == null)) {
        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 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: 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 decodeQueryString(qs) {
    //while it starts with some url encoding
    while (qs.indexOf('%') == 0) {
        qs = decodeURIComponent(qs);
    }

    return qs;
}

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) {
	if (typeof hasRightFlashVersion != 'undefined' && hasRightFlashVersion == false)
	{
		if (typeof qs == 'undefined' || qs == '')
			qs = '?';
		else
			qs += '&';

		qs += 'NoFlash=1';
	}

	url = 'http://' + CLASSROOM_URL_PREFIX + '/Classroom/SLDetector.aspx' + ((typeof qs == 'undefined') ? '' : qs);

    popClassroomWin(url, 984, 665, 'no');
}

function popClassroomWin(url, width, height, scrollbars) {
    //if get called by an html link, ignore
    if (popClassroomWin.caller == null)
        return;

    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";
        }
    }
    catch (e) {
        //if we throw an exception here, it means the window is already open
        alert('Please first close your current classroom window.');
        return;
    }

    classroomWin.location = url;
    classroomWin.focus();
}


