
    var currentQid = null;
    var ROTATE_PREFFIX = '#rotate-';

    function rotateDiv( qid ){
        if( currentQid != null ){
            $j( ROTATE_PREFFIX + currentQid ).fadeOut( FADE_SPEED, function () {
                                                                                $j( ROTATE_PREFFIX + currentQid ).css({'display':'none'});
                                                                                showDiv( qid ); } );
        }
        else{
            showDiv( qid );
        }
    }

    function showDiv( qid ){
        $j( ROTATE_PREFFIX + qid ).fadeIn( FADE_SPEED,
            function () {
                currentQid = qid;
                var nextQid = qid + 1;
                if ( $j(ROTATE_PREFFIX + nextQid).length == 0  ){
                    nextQid = 0;
                }
                window.setTimeout('rotateDiv(' + nextQid + ');', QUOTE_TIME);
            }
        );
    }

    function goOverviewTab(){
        showTab(OVERVIEW_TAB, AP_TAB_ID);
    }

    function selectEpisode(id){
        var newEpName = 'ep-' + id;
        var newBmName = 'bm-' + id;
        var currentEpName = 'ep-' + currentId;
        var currentBmName = 'bm-' + currentId;

        //----------------------------
        // Episode Div
        if( document.getElementById(currentEpName) ){
            // className =  document.getElementById(currentEpName).className;
            // document.getElementById(currentEpName).className = ;
            $j('#' + currentEpName).removeClass('episode-playing');
            $j('#' + currentEpName).addClass('episode');
        }

        //document.getElementById(newEpName).className = 'episode-playing';
        $j('#' + newEpName).removeClass('episode');
        $j('#' + newEpName).addClass('episode-playing');

        //----------------------------
        // Bonus Material Div

        if( document.getElementById(currentBmName) ){
            document.getElementById(currentBmName).className = 'bonus-material';
        }

        if( !document.getElementById(newBmName) ){
            newBmName = 'bm-course';
        }

        if( document.getElementById(newBmName) ){
            document.getElementById(newBmName).className = 'bonus-material-selected';
        }
    }

    function goVideo(id, epid){

        EPISODE_ID = epid;

        if( id != null ){
            loadVideo(id);
        }

        selectEpisode(id);

        //-----------
        // SET NEW CURRENT EPISODE
        currentId = id;

        //scroll2Episode(id);
    }

    /*
    function scroll2Episode(pid){
        document.getElementById('episodes').scrollTop = document.getElementById('ep-' + pid).offsetTop;
    }
    */
    function scroll2Episode(id){
        var foundIt = false;
        var i = 0;
        var count = EPISODES_ORDER.length;

        while( !foundIt && i < count){
            if( EPISODES_ORDER[i] == id ){
                foundIt = true;
            }
            else{
                i++;
            }
        }

        if(!foundIt){
            i = 0;
        }

        document.getElementById('episodes').scrollTop = ( i * 95 );

    }

    function scroll2BonusMaterial(){
        if( document.getElementById('bm-' + currentId) ){
            document.getElementById('bonus-materials').scrollTop = document.getElementById('bm-' + currentId).offsetTop;
        }
    }
    
    function goBuyBox(){
    	if ( document.getElementById('call-action') )
        {
            $j.facebox(document.getElementById('call-action').innerHTML);
        }
    }

    //Show a message corresponding to the course type and 
    //user status
    //@author jcastro
    function goAccessCourse(){
    	// ACT and SAT have access to the free trial
    	var isUserLogged = document.getElementById('userId').value;
    	var trialStatus = document.getElementById('freeTrialStatus');
    	var locked = document.getElementById('locked');
    	    	
    	//is not promo course, show go buy box
    	if(null == trialStatus || null == locked) {
    		goBuyBox();
    	} else {
    		//user is not logged, show login popup
    		if('0' == isUserLogged) {
    			showLoginPopup();
    		} else if(1 == locked.value){
    			showTrialStatus(trialStatus.value);
    		}
    	}
    }
    
    /**
     * Shows the corresponding message if the free trial is
     * to be activated, or if is it expired
     * @param trialStatus
     * @return corresponding div according to the status
     */
    function showTrialStatus(trialStatus){
    	if ( document.getElementById(trialStatus) )
        {
    		$j.facebox($j('#' + trialStatus).html().replace(/COPY/g, ''));
        }
    }
    
    /**
     * This function is meant to be called from the "Try it now" link
     * on the overview page.
     * It will take the user to the Practice tab and  show the Free trial
     * activation popup according to the case
     * @author jcastro
     */
    function tryItNow(){
    	showSatTab(PRACTICE_RV_TAB);
    	goAccessCourse();
    }

    /**
     * This function activates the free trial mode for SAT/ACT courses.
     * If the user is login with facebook, and he hasn't accept to receive emails 
     * from Brightstorm 
     * @author jcastro
     */
    function activateCourse() {
    	jQuery(document).trigger('close.facebox');
    	jBlockUI();
    	var askReceiveEmail = document.getElementById('askReceiveEmail').value;
    	if (askReceiveEmail == 'true' || askReceiveEmail == 1){
    		FB.Connect.showPermissionDialog("email", submitActivateForm);
    	} else {
    		submitActivateForm();
    	}
    }
    
    function submitActivateForm(){
    	var form = document.getElementById('activateForm');
    	form.submit();
    }

    // Shows a message when the user's course expire
    // @author ijiron
    function showExpiredCourseMsg() {
        if ( document.getElementById('expire-course-msg') )
        {
            $j.facebox(document.getElementById('expire-course-msg').innerHTML);
        }
    }



    function showLearnMoreBox(){
        $j.facebox(document.getElementById('learn_more').innerHTML);
    }

    function getObjs4search(){
        var episodeObjs = document.getElementById('episodes').childNodes;
        var bonusObjs = Array();
        if (document.getElementById('bonus-materials') != null )
            bonusObjs = document.getElementById('bonus-materials').childNodes;
        var resultArray = new Array();
        var j = 0;
        for (var i in episodeObjs){
            resultArray[j++] = episodeObjs[i];
        }
        for (var i in bonusObjs){
            resultArray[j++] = bonusObjs[i];
        }
        return resultArray;
    }

    function changeDisplay(domObj, value){
        if(domObj && domObj.style ){
            domObj.style.display = value;
        }
    }

    function searchEpisode(inputObject){
        var divObjs = getObjs4search();
        var searchStr = inputObject.value.toLowerCase();
        if (searchStr != ''){
            var episodesIds2show = new Array();
            var i = 0;
            for (var id in EPISODES_TEXT){
                if( EPISODES_TEXT[id].indexOf(searchStr) >= 0){
                    episodesIds2show[i++] = id;
                }
            }

            var episodesIds2showLength = episodesIds2show.length;
            var episodeDivId = '';
            var bonusMaterialsDivId = '';
            var foundIt = false;
            var c = 0;

            for (var i in divObjs){
                changeDisplay(divObjs[i], 'none');
                c = 0;
                foundIt = false;
                while(!foundIt && c < episodesIds2showLength){
                    bonusMaterialsDivId = 'bm-' + episodesIds2show[c];
                    episodeDivId = 'ep-' + episodesIds2show[c++];
                    if( episodeDivId == divObjs[i].id || bonusMaterialsDivId == divObjs[i].id){
                        changeDisplay(divObjs[i], 'block');
                        foundIt = true;
                    }
                }
            }

        }
        else{
            for (var i in divObjs){
                changeDisplay(divObjs[i], 'block');
            }
        }
    }

    function goClassroomEpisode(vid, eid, autostart){
        window.scrollTo(0,0);
        showTab(CLASSROOM_TAB, AP_TAB_ID);
        showTab(EPISODES_TAB, CLASSROOM_TAB_ID);
        scroll2Episode(vid);
        createVideoPlayer(vid, autostart);
        if( autostart ){
            selectEpisode(vid);
        }
        EPISODE_ID = eid;
        currentId = vid;

        gaTrackViewsBetweenTabs(COURSE_ID, CLASSROOM_TAB);
    }

   /**
    * Tracks Bonus Material for users
    * @param int bonusMaterialId bonus material's id
    */
    function downloadBM(bonusMaterialId)
    {
        var userId = $j('#userId').val();

        var url = '/download/bonusmaterial';
        $j(document).ready(
                function() {
                    if (userId != 0 )
                        $j.post(url,{bonus_material_id: bonusMaterialId, user_id : userId },function(data)
                                    {
                                        //$j("#"+div).html(data);
                                    }
                        );
                    $j('.image_' + bonusMaterialId ).attr('src', '/images/ap/icons/checkbox_checked.png');
               }
        );
    }

   /**
    * Tracks Bonus Materials
    * @param string filename selected file
    * @param int bonusMaterialId bonus material's id
    */
    function trackBonusMaterial(filename , bonusMaterialId)
    {
        downloadBM(bonusMaterialId);
        gaTrackBonusMaterial(filename);
    }


   /**
    * Store when the user start/finish to watch a video
    */
   function trackVideo(event) {

        var videoId = event.video.id;
        var userId = $j('#userId').val();
        var url = '/download/trackprogressvideo';

        alert("VideoID:".event.video.id);
           alert("UserID:".userId);

        $j(document).ready(
                function() {
                    $j.post(url,{video_id: videoId, user_id : userId },function(data)
                                    {
                                        //$j("#"+"outputAjax").html(data);
                                    }
                    );
                    //$j('#image_' + bonusMaterialId ).attr('src', '/images/ap/icons/checkbox_checked.png');
               }
        );
    }

   /**
    * Set the text-decoration css style to underline for the episode name and topics
    */
    function underlineEpisodeName( episodeId)
    {
        $j('#topicsEpisodeSpan_' + episodeId ).css("text-decoration","underline");
        $j('#nameEpisodeSpan_' + episodeId ).css("text-decoration","underline");
    }

   /**
    * Unset the text-decoration css style (underline) for the episode name and topics
    */
    function undoUnderlineEpisodeName( episodeId)
    {
        $j('#topicsEpisodeSpan_' + episodeId ).css("text-decoration","none");
        $j('#nameEpisodeSpan_' + episodeId ).css("text-decoration","none");
    }

   /**
    * Set the text-decoration css style to underline for the course name and topics
    */
    function underlineCourseNameBM( bonusMaterialId )
    {
        $j('#nameCourseBM_' + bonusMaterialId ).css("text-decoration","underline");
        $j('#topicsCourseBM_' + bonusMaterialId ).css("text-decoration","underline");
    }

   /**
    * Unset the text-decoration css style (underline) for the course name and topics
    */
    function undoUnderlineCourseNameBM( bonusMaterialId )
    {
        $j('#nameCourseBM_' + bonusMaterialId ).css("text-decoration","none");
        $j('#topicsCourseBM_' + bonusMaterialId ).css("text-decoration","none");
    }

   /**
    * Pause the video, DE662: IE7 and IE6: when user reproduces a video on classroom tab and change the tab he can still hear the video
    */
    function pauseVideo()
    {
        if ( modVP != null && typeof modVP != "undefined" )
        {
           if (modVP.isPlaying())
           {
               modVP.pause(true);
           }
       }
    }


   /**
    * Remember the last selected tab Id.  Fix-DE679
    * @author ijiron
    */
    function rememberSelectedTabId(tabId, pageName) {
          document.cookie = 'selectedTabId=' + tabId + ';path=/' + pageName;
    }

   /**
    * Go to the Classroom tab, select an episode the episode tab, select the quiz tab and make the quiz tab at the top of the browser
    * @author aluna
    */
    function goClassroomQuiz(vid, eid, autostart){

        //window.scrollTo(0,25);
        showTab(CLASSROOM_TAB, AP_TAB_ID);
        showTab(EPISODES_TAB, CLASSROOM_TAB_ID);
        showTab(QUIZ_TAB, CLASSROOM_TAB_ID2);
        scroll2Episode(vid);
        createVideoPlayer(vid, autostart);

        selectEpisode(vid);
        EPISODE_ID = eid;
        currentId = vid;

        gaTrackViewsBetweenTabs(COURSE_ID, CLASSROOM_TAB);
    }

   /**
    * Scroll to the episode quiz tab
    * @author aluna
    */
    function scrollToEpisodeQuizTab( ){
        document.getElementById('quizImage').onload = function(){
            x = $j('#commentQuizSec');
            offset = x.offset();
            window.scrollTo(0,offset.top);
            //$('html,body').animate({scrollTop: offset.top}, 1000);
            document.getElementById('quizImage').onload = null;
        };
    }

   /**
    * Scroll to the episode quiz tab when a video has finished
    * @author aluna
    */
    function onVideoCompleteShowEpisodeQuizTab(){
        if ( (typeof CLASSROOM_TAB_ID2 != "undefined") && ( typeof $j('#tab_' + CLASSROOM_TAB_ID2 + '1') != "undefined" )){
            if (($j('#tab_' + CLASSROOM_TAB_ID2 + '1').is(':visible') )){
                showTab(QUIZ_TAB, CLASSROOM_TAB_ID2);
                x = $j('#commentQuizSec');
                offset = x.offset();
                //window.scrollTo(0,offset.top);
                $j('html,body').animate({scrollTop: offset.top}, 2000);
            }
        }
    }

    function showCommentTabEpisodeNotFinished(){
        if ( !( $j('#div-' + currentId).hasClass('finished') ) )
            showTab(COMMENT_TAB, CLASSROOM_TAB_ID2);
    }

   /**
     * Login Validation, bonus material downloading and tracking
     * @param string filename selected file
     * @param int bonusMaterialId bonus material's id
     * @param string type bonus material's type
     */
    function downloadBonusMaterialLoginRequired(filename , bonusMaterialId, type){
        var userId = USER_ID;
        if (userId == 0){
            // aluna - DE-1103: PSAT - Login Through quizzes - After that the question tab is displayed as default
            if ( typeof loginWhileAnsweringEpisodeQuiz != "undefined" ){
                loginWhileAnsweringEpisodeQuiz = 'false';
            }
            // ...aluna - DE-1103: PSAT - Login Through quizzes - After that the question tab is displayed as default
            showLoginPopup();
        }
        else{
            downloadBM(bonusMaterialId);
            gaTrackBonusMaterial(filename);

            if ( type == 'PDF' ){
                filename = 'bonus-materials/' + filename;
            }
            var newWindow = window.open(filename, '_blank');
            newWindow.focus();
        }
    }

   /**
    * Load subcategory for questions and answers functionality
    * @param int episodeId episode's id
    */
    function loadSubcategoryId(episodeId){
        if ( typeof eps4Questions != "undefined" ){
            var subCategoryId = eps4Questions[episodeId]['category_level2_id'];
            $j('#categoryLevel2Id').val(subCategoryId);
        }
    }

    /**
     * Show question tab
     * @param int QUESTION_TAB question tab id
     * @param int CLASSROOM_TAB_ID2 classroom tab id
     */
    function showQuestionTab(){
        if ( typeof QUESTION_TAB != "undefined" ){
            showTab(QUESTION_TAB, CLASSROOM_TAB_ID2);
        }
    }

   /**
    * Google analytic tracking views between tabs
    * @param int courseId course id
    * @param int tabId tab id
    */
    function gaTrackViewsBetweenTabs(courseId, tabId){
        var url = '';
        switch( courseId ){
            case '8':
            case '9':
            case '26':
            case '31':
                url = '/' + currentPage + '/';
                break;

            case '32':
                url = '/sat/';
                break;
            case '33':
                url = '/act/';
                break;
            case '36':
                url = '/sat-confidential/';
                break;
            case '37':
                url = '/psat/';
                break;
            default:
                url = '/sat/';
        }

        url = url + 'area/';

        switch( tabId ){
            case '0':
                url = url + 'overview';
                break;
            case '1':
                url = url + 'classroom';
                break;
            case '2':
                url = url + 'studyplan';
                break;
            case '3':
                url = url + 'mystuff';
                break;
            case '4':
                url = url + 'purchase';
                break;
            case '5':
                url = url + 'practice';
                break;
            case '6':
                url = url + 'flashcards';
                break;
            default:
                url = url + 'overview';
                break;
        }
	if((typeof(pageTracker) != 'undefined' ) && (pageTracker != null))
        pageTracker._trackPageview( url );
    }