$(document).ready(function () {	
    /***********************************************************************************
    * SAT GLOBAL INIT LOGIC
    ***********************************************************************************/

    /**
     * Suckerfish CB wrapper in global nav
     *
     * @see common/js/cb.js
     */
    CB.utils.sfHover($('.cbNav li'));

    if ($.browser.msie) {
        $('.pageTabs .roundies, .pageTabs .roundies12').ieTabStates();
    }

    /**
     * Logo change state in global header, with achieve more logo
     */
    $('.siteBranding span').mouseover(
        function () {
            $('.satLogoAM').show();
        }
    ).mouseout(
        function () {
            $('.satLogoAM').hide();
        }
    );
    
    /**
     * Swapping default text in inputs.  Simple custom plugin
     *
     * TODO: MOVE TO COMMON
     * @see sat/js/plugins/jquery.sat.plugins.js
     */
    $('#siteSearchText, #myOrgUserName').inputText();
	
    /**
     * JS override of date in footer to accommodate year changes.
     *
     * @see sat/js/sat.js
     */
	SAT.formatDate('#footerYear');

    /**
     * Modal init.
     *
     * @see common/js/cb.js
     */
    CB.jqmWrapper.init();

    /**
     * These are the 'twirler' implementations.  Basically the show/hide carrots throughout the site.
     * In addtion this is passed an object with the omniture option turned on to track each reveall.
     *
     * @see common/js/cb.js
     */
    CB.twirl({'omniture': true});

    /**
     * Handles onload firing of default browser print modal.
     *
     * @see common/js/cb.js
     */
	CB.utils.printPage('pgContainer', 'printPage');
	
    /**
     * Simple class based plugin to attach default print dialog to element via click.
     *
     * @see common/js/plugins/jquery.cb.plugins.js
     */
	jQuery('.cbTriggerPrint').printDialog();

    /**
     * Simple class based wrapper method for switching logo in global nav on print pages
     *
     * @see common/js/cb.js
     */
	CB.utils.addOrSwpImg({
        'el': $('#bannerSpan'), 
        'klass': 'printOnly', 
        'imgSrc': '/img/satLogoOver.gif'
    });

    /**
     * Option, when class cbSmoothScroll is classed to an anchor, and given an #id as the value of the href attribute to and id
     * of an element on the page, it scrolls to that element, smooth-style
     *
     * @see sat/js/sat.js 
     * @see common/js/cb.js (jqmWrapper)
     */
    $('a.cbSmoothScroll:not(.twirlerThirdParty), .cbSmoothScroll a:not(.twirlerThirdParty)').click(function () {
        $($(this).attr('href')).scrollTo('500');
        return false;
    });

    /**
     * Quick wrapper script that initializes the modal fired from left nav, once logged in that displays chart of stats
     *
     * @see sat/js/sat.js 
     * @see common/js/cb.js (jqmWrapper)
     */
    SAT.compareStateChartVisualizeHook.init();


    /***********************************************************************************
    * PRACTICE INIT LOGIC
    ***********************************************************************************/
    if (jQuery('body').hasClass('practiceSection')) { 
        /**
         * Simple util for triggering a popup via JS, on QOTD Print
         *
         * @see common/js/cb.js
         */
        CB.utils.browserPopUp($('#questionMetaContainer a.popUp')); 

        /**
         * Plugin that handles pie chart on QOTD
         *
         * @see common/js/plugins
         */
        $('.qotdPercentCorrectTable').visualize(
            {
                labels: false,
                type: 'pie',
                colors: ['#788981', '#c8cecc'], 
                appendTitle: false,
                pieMargin: 0,
                appendKey: false, 
                width:32, 
                height:32
            }
        );

        /**
         * OOTD, sets the value of a hidden input for tracking purposes if hint is viewed
         *
         * @see common/js/plugins/jquery.cb.plugins
         */
        $('#wantAHintLink').setFormElementValue('#hintUsed', 'true', 'click');

        /**
         * Plugin that custom radio buttons in SPR type questions
         *
         * @see common/js/plugins
         */
        $('.answerBubbleTable input, .pracScanTronList input').customInput();

        /**
         * Simple pager plugin that handles practice tips
         *
         * TODO: MOVE TO COMMON
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('#practiceTips').simplePager({
            'content': '.practiceTip', 
            'targetPagerCont': '.practiceTipsNav', 
            'prevNextCont': '.practiceTipsPrevNext',
            'prevClass': 'button floatLeft',
            'nextClass': 'button floatRight',
            'navULClass': 'pageTabs topNumberedTabs', 
            'navLIClass': 'roundies',
            'callback': function (ul) {
                if ($.browser.msie) {
                    if (ul.hasClass('pageTabs')) {
                        $('.roundies', ul).ieTabStates();
                    }
                }
            }
        });

        /**
         * Simple pager plugin that handles question sets in the online practice questions
         * in free practice test
         *
         * TODO: MOVE TO COMMON
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('.fpTestPaginate').simplePager({
            'content': '.fpTestContent', 
            'targetPagerCont': '.fpTipsNav', 
            'prevNextCont': '.fpTestPrevNext',
            'prevClass': 'button drm',
            'scrollTo': '#fullPracticeQuestion',
            'nextClass': 'button',
            'navULClass': 'pageTabs topNumberedTabs', 
            'navLIClass': 'roundies',
            'callback': function (ul, contentDiv) {
                if ($.browser.msie) {
                    if (ul.hasClass('pageTabs')) {
                        $('.roundies', ul).ieTabStates();
                    }
                }

                //Handle Nested Anchors linked to from the review
                $(ul).find('li').each(function(i) {
                    var anchor = $(contentDiv[i]).find(window.location.hash);
                    if (anchor.length !== 0 && i !== 0) {
                        $('a', this).click();
                        $(anchor).scrollTo();
                    }
                });  
            }
        });

        /**
         * Clearing radio buttons/form elements in the online practice test
         */
        $('a[class^=cbClearFormElement]').click(function () {
            var klass = this.className.match(/\bcbClearFormElement.*?\b/)[0];
            $('input.' + klass + 'Target:text, .' + klass + 'Target input:text').val('');
            $('input.' + klass + 'Target:radio, .' + klass + 'Target input:radio').attr('checked','');
            $('input.' + klass + 'Target:radio, .' + klass + 'Target input:radio').parents('.custom-radio').find('.checked').removeClass('checked');
            return false;
        }); 

        /**
         * Clearing radio buttons/form elements in the online practice test
         */
        $('#freePracticeTabs li a').tabs({'selectorMethod':'parent'}); //practice/sat-practice-test

        /**
         * This is a plugin to handle client side questions in the practice question 'Try It Out' sections.
         * Second call is for SPR type questions.
         *
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('#practiceMethodDirectionsExampleQ').exampleQuestion();
        $('#answerTableForm-mathSPRq1, #answerTableForm-mathSPRq2,#answerTableForm-mathSPRq3').exampleQuestion({type: 'spr'});

        /**
         * This is a plugin to handle more client side fake question experiences in Skills Insight Section
         *
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('#testYourSkillsInThisBandList .reviewAnswerListContent').skillsInsight();


        /**
         * This is a plugin to sizing white content modules next to each other to the same height in subject tests.
         * The second is to match when a column contains multiple modules to make sure the last expands to the height
         * it needs to fill the gap, check biology pages
         *
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('.subjectTestFillHeight > .contentModule').fillHeight();
        $('.subjectTestFillHeight, .subjectTestFillHeightMulti').fillHeight({type: 'multi', toMatch: '.contentModule'});

        /**
         * Validation plugin init for SAT Study Plan, /practice/sat-study-plan 
         *
         * @see common/js/plugins/..
         */
        $('#studyPlanForm').validate({
            messages: {
                testType: "Please select a test",
                testFreq: "Please indicate how many times you've taken it",
                testDate: "Please indicate when you'll take it"
            },
            errorContainer: '#studyPlanErrors',
            errorLabelContainer: '#studyPlanErrors ul',
            wrapper: 'li'	
        });
		
		
		/**
         * This is a plugin for binding submit to other elements within form.
         * commons/js/plugins/jquery.cb.plugins.js
        */
		$('#qotdShowAnswer').submitForm({eventType:'click',formName:'#showAnswerForm'});
	    
		/**
        * some clean up code to make the answers explanation pages of the practice section accessible
		* @see sat/js/sat.js
		*
		*/
		SAT.answerExplanations();
        
        /**
        * code to section selection menu on paper practice test form automatically submit on change
		* @see sat/js/sat.js
		*
		*/
		//SAT.sectionSelectorPaperVersion();

    /***********************************************************************************
    * REGISTER INIT LOGIC
    ***********************************************************************************/
    } else if (jQuery('body').hasClass('registerSection')) {

        /**
         * This is a custom method to handle the SAT Subject Test dates on the client side.  Checking check box elements
         * show/hides test dates available.
         *
         * @see sat/js/sat.js
         */
        SAT.toggleSatTestDates.init({trigger:'#satSubjTestDateFinder input[type=checkbox]', target:'satSubjectTestDates'});

        /**
         * Simple plugin, show/hide swap text, yourTestDay.ftl
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#showHideCDPlayerLink').toggleShowHide('Remove it from the list.');

        /**
         * Simple plugin, show/hide content on Your Test Day, yourTestDay.ftl
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#removeCDPlayerLink').smoothHide({
            'callback': function () {
                $('#showHideCDPlayerLink').toggleText('Remove it from the list.', 'Add it to the list.');
            }
        });

        /**
         * XHR Form plugin for Code Search, register/sat-code-search
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#codeSearchTypeForm').xhrForm({
            responseLocation: '#searchResultsWrapper',
            setup: function (form) {
                form.find('#codeSearchSection').submitForm({eventType:'change'});
            },
            callback: function (response) {
                $(this.responseLocation).empty();
                var flagEls = $(response).find('input, select');	
                if (!flagEls[0]) {
                    $('#codeSearchResultsWrapper').html(response);				
                } else {
                    $('#searchFormFieldsWrapper').html(response).find('#codeSearchSection, #codeSearchMajorsSelect, #codeSearchRegion').submitForm({eventType:'change'});
                    $('#codeSearchCountrySelect', '#searchFormFieldsWrapper').change(function () {
                        if ($(this).val() === 'US' || $(this).val() === '000') {
                            $('#codeSearchStateSelect').attr('disabled','');
                            $('#codeSearchStateSelect').removeClass('setDisabled');
                        } else {
                            $('#codeSearchStateSelect').attr('disabled','true');
                            $('#codeSearchStateSelect').addClass('setDisabled');
                            $('#codeSearchStateSelect').val($('#codeSearchStateSelect option:first').val());
                        }
                    });
                }			
            }
        });

        /**
         * XHR Form plugin for Code Search, register/sat-code-search
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#codeSearchForm').xhrForm({
            responseLocation: '#searchResultsWrapper',
            setup: function (form) {
                //Just in case check for all possibilities
                form.find('#codeSearchSection, #codeSearchMajorsSelect, #codeSearchRegion').submitForm({eventType:'change'});
            },
            callback: function (response) {
                jQuery(this.responseLocation).html('');
                jQuery(response).appendTo(this.responseLocation);
                jQuery(this.responseLocation).scrollTo('500');
                jQuery('input.setDisabled, select.setDisabled', '#codeSearchForm').attr('disabled', 'true');
            }
        });

        /**
         * XHR Form plugin for Overseas Code Search, /register/overseas-advising-center 
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#overseasAdvisingCenterForm').xhrForm({
            responseLocation: '#formFieldsWrapper',
            setup: function (form) {
                form.find('#overseasRegion, #overseasCountry, #overseasCity').submitForm({eventType:'change'});
            },
            callback: function (response) {
                $('#codeSearchResultsWrapper').empty();
                var flagEls = $(response).find('input, select');	
                if (!flagEls[0]) {
                    $('#codeSearchResultsWrapper').html(response);
                    $('#codeSearchResultsWrapper').scrollTo('500');
                } else {
                    $('#formFieldsWrapper').html(response).find('#overseasRegion, #overseasCountry, #overseasCity').submitForm({eventType:'change'});
                }
            }
        });

        /**
         * Tabs plugin 
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#scoreFAQTabs li a').tabs({'selectorMethod':'parent'});  //register/sat-score-choice
        $('#scoresCompareScoresTabs li a').tabs({'selectorMethod':'parent'});  //register/sat-score-choice
        $('.selectAGradeLevel a').tabs({
			callback: function(el){
				$(el.attr('href')).scrollTo('500');
			}
		});  //register/when-to-take-sat	
        $('#compareScores > ul a').tabs({'selectorMethod':'parent'});	//register/understanding-sat-scores
        $('#closedTestCentersTabBlockTabs li a').tabs({'selectorMethod':'parent'});  //register/sat-test-center-closings


    /***********************************************************************************
    * SCORES INIT LOGIC
    ***********************************************************************************/
    } else if(jQuery('body').hasClass('scoresSection')) {

        /**
         * Tabs plugin 
         *
         * @see commons/js/plugins/jquery.cb.plugins.js
         */
        $('#verifySatScoresTabs a').tabs({'selectorMethod':'parent'});	//scores/verify-sat-scores

        /**
         * This is a plugin to sizing white content modules next to each other to the same height.
         * /scores/cancel-sat-scores
         *
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('#cancelingScore > .contentModule, #cancelByNotice > .contentModule').fillHeight();


    /***********************************************************************************
    * WHY SAT? INIT LOGIC
    ***********************************************************************************/
    } else if(jQuery('body').hasClass('whysatSection') || /^\/about-tests/.test(location.pathname)) {
       //Placeholder 

    /***********************************************************************************
    * HOME INIT LOGIC
    ***********************************************************************************/
    } else if(jQuery('body').hasClass('homeSection') && /^\/home/.test(location.pathname)) {

        /**
         * Simple pager plugin that handles homepage rotator
         *
         * TODO: MOVE TO COMMON
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('#homeLatestNewsContainer .contentModule').simplePager({
             'content': '.rotatingPromo', 
             'targetPagerCont': '.homeLatestNewsButtons',
             'autoRotate': '5',
             'transition': 'fast',
             'callback': function (ul, contentDiv) {
                 $(ul).find('li').each(function(i) {
                    var anchor = $(contentDiv[i]).find('h4 a');
                    if (anchor.length === 0) {
                        $(contentDiv[i]).find('h4').addClass('default');
                        $(this).addClass('default');
                    } else { 
                        var href = anchor.attr('href');
                        if (/\//ig.test(href)) {
                            var section = anchor.attr('href').split("/")[1].toLowerCase(); 
                            section = (section == 'practice' || section == 'register' || section == 'scores' || section == 'why-sat') ? section : 'default'; 
                            $(contentDiv[i]).find('h4').addClass(section);
                            $(this).addClass(section); 
                        } else  {
                            $(this).addClass('default'); 
                        }
                    }
                 });  
             }

        });

        /**
         * One-off omniture click map override
         */
        //s_objectID = 'sat_' + this.id; 
        $('#satNavPractice, #satNavRegister, #satNavScores, #subNavIdpracticeHome, #subNavIdregisterSATHome, #subNavIdscoresSATHome, #practiceHeaderLink, #regHeaderLink, #scoreHeaderLink, #regNowContLink, #sendScoresContLink').click(
            function () { 
                var _url, _delay; 

                mboxUpdate('SAT_Homepage', 'click=' + this.id);
                _url =  (this.href) ? this.href : $('a', this).attr('href');
                _delay= function () {
                    setTimeout(function () { location=_url; }, 150);
                };
                _delay();
                return false;
            }
        );

        /**
         * This is a plugin to sizing white content modules next to each other to the same height. Homepage columns
         *
         * @see sat/js/plugins/jquery.sat.plugins.js
         */
        $('#homeVertRegister > .contentModule, #homeVertPractice > .contentModule, #homeVertScores > .contentModule').fillHeight();
        $('#homeWhySATCallout > .contentModule, #homeFeedbackCallout > .contentModule').fillHeight();
        $('#homeLatestNewsContainer, #registerNowContainer').fillHeight({type: 'multi', toMatch: '.contentModule'});

    }

	

    /***********************************************************************************
    * MODULE INIT LOGIC
    ***********************************************************************************/

    /**
     * XHR From Plugin: Overseas Module
     *
     * @see common/js/plugins/jquery.cb.plugins.js
     */
	//xhr search (overseas module)
    $('#overseasAdvisingCenterModuleForm').xhrForm({
        responseLocation: '#formFieldsWrapper',
        setup: function (form) {
            form.find('#overseasRegion, #overseasCountry, #overseasCity').submitForm({eventType:'change'});
        },
        callback: function (response) {
			$('#formFieldsWrapper').html(response);
            $('#formFieldsWrapper').find('#overseasCity').bind('change', function () {
                $(this).parents('form').unbind().submit();
            });
            $('#formFieldsWrapper').find('#overseasRegion, #overseasCountry').submitForm({eventType:'change'});
        }
    });

    /**
     * XHR From Plugin: Challenge a Friend Module
     *
     * @see common/js/plugins/jquery.cb.plugins.js
     */
    $('#challengeFriendCalloutForm').xhrForm({
        responseLocation: '#challengeFriendModule form',
		valid: function() {
			return jQuery(this.responseLocation).valid();
		},
        callback: function (response) {
            if (jQuery(response).is('#challengeFriendConfirmModule')) {
                jQuery(this.responseLocation).attr('action', jQuery(response).find('form').attr('action'))
            }

            jQuery(this.responseLocation).html('');
            jQuery(jQuery(response).find('form').html()).appendTo(this.responseLocation);

            //Extract the script and make sure it gets called for tracking
            jQuery(response).each(function () {
                if (jQuery(this).is('script')) {
                    eval(jQuery(this).html());
                }
            });
        }
    });

    /**
     * XHR From Plugin: Practice Times Module
     *
     * @see common/js/plugins/jquery.cb.plugins.js
     */
    $('#practiceTipsSignupForm').xhrForm({
        responseLocation: '#signUpForPracticeTipsCallout form',
		valid: function() {
			return jQuery(this.responseLocation).valid();
		},
        callback: function (response) {
            jQuery(this.responseLocation).html('');
            jQuery(jQuery(response).find('form').html()).appendTo(this.responseLocation);
        }
    });

    /**
     * XHR From Plugin: Subscribe to QOTD Module
     *
     * @see common/js/plugins/jquery.cb.plugins.js
     */
    $('#pageModuleSubscribeForm').xhrForm({
        responseLocation: '#moreQotdLoggedIn',
        callback: function (response) {
            jQuery(this.responseLocation).html(jQuery(response).find(this.responseLocation).html());
        }
    });

    /**
     * UL to Select Elm Plugin:  For SAT Subject Tests Modules
     *
     * TODO: MOVE TO COMMON
     * @see SAT/js/plugins/jquery.sat.plugins.js
     */
    $('#satSubjectTestMenu').ulToSelectElm({
        'initialOption': 'Choose One',
        'callback': function (selectElm) {
            var initialOption = this.initialOption;
            selectElm.change(function () {
                //Technically this condition should never happen - but just in case
                if (jQuery(this).val() !== initialOption) { 
                    window.location = jQuery(this).val();
                }
            });
        }
    });



    /***********************************************************************************
    * VALIDATION LOGIC
    ***********************************************************************************/
    //Contact Us Email
    $.validator.addMethod('matchEmailContact',function() {return $('#contactConfirmEmail').val() == $('#contactYourEmail').val()});
	$.validator.addMethod('inquiryTypeRequired',function() {return $('#inquiryType').val() != -1});
    $('#contactUsForm').validate({
        rules: {
            sender: {
                email: true
            },
            contactConfirmEmail: {
                matchEmailContact: true
            },
			inquiryType: {
				inquiryTypeRequired: true
			}
        },
        messages: {
            contactYourName: "Please enter your name",
            sender: {
                required: "Please enter your e-mail address",
                email: "Your email address must be in the format of name@domain.com"
            },
            contactConfirmEmail: {
                required: "Please confirm your e-mail address",
                matchEmailContact: "Please make sure that your e-mail addresses match"
            },
            Subject: "Please enter the subject of your message",
            inquiryType: "Please select an inquiry type",
            comments: "Please enter a comment"
        },
        errorContainer: '#contactErrors',
        errorLabelContainer: '#contactErrors ul',
        wrapper: 'li'		
    });	
	//Module forms
	$('#practiceTipsSignupForm').validate({
		rules: {
			email: {
				email: true
			}
		},
		messages: {
          	email: {
             	required: "Please enter your e-mail address",
             	email: "Your email address must be in the format of name@domain.com"
         	},
			qotdEmailCaptcha: "Please enter the letters above"
		},
		errorContainer: '#practiceTipsErrors',
		errorLabelContainer: '#practiceTipsErrors ul',
        wrapper: 'li'	
	});
	$('#challengeFriendCalloutForm').validate({
		rules: {
			email: {
				email: true
			}
		},
		messages: {
          	email: {
             	required: "Please enter your e-mail address",
             	email: "Your email address must be in the format of name@domain.com"
         	},
			friendEmails: "Please enter at least one email address",
			qotdEmailCaptcha: "Please enter the letters above"			
		},
		errorContainer: '#challengeFriendErrors',
		errorLabelContainer: '#challengeFriendErrors ul',
        wrapper: 'li'			
	});
	//MyOrg login (left nav)
    $('#myOrgLogin').validate({
        messages: {
			password: "<strong>!</strong> Enter your password"
        },   
   		errorContainer: '#myOrgErrors',
		errorLabelContainer: '#myOrgErrors ul',
   		wrapper: "li"		
    });	
    
/*********************************************************
* Search Results page. Results per page    ***************
*********************************************************/  
/**
* Change number of results displayed on page via dropdown menu.
* Submit form onchange to change number of displayed search results
* 
* @see SAT/js/plugins/jquery.sat.plugins.js
*/
$('#resultsSelect').submitForm({eventType:'change'});
   
});


/* ********April 5, 20011 RELEASE CHANGES********
  * ***************  sat.int.js *****************/
    // needed to determine if users browser is IE or not 
	// SAT SUBJECT PRACTICE TEST -- Result Summary Icons
$(document).ready(function () {	
var isIE = false;
    var pos;
    var idNumber;
    jQuery.each(jQuery.browser, function(i) {
                    if($.browser.msie){
                                    isIE = true;
                    }else{
                                    isIE = false;
                    }
    });
    
    $(".viewQuestion").click(function () { 
    		//Get the id of this clicked item
    				pos = $(this).attr("id");
                    idNumber = pos.substr(12);				
		
                    //get the parsed name of the LI id we need to make visible
                    showName = "#subQsReview" + idNumber;
                    
                    //make answer area visible

                    $('#subQsReviewContent').addClass('makeMeVisible');
                    
                    //hide all LI's
                    $('#subQsReviewList').children("li").addClass('makeMeHide');

                    //make the only LI we need visible
                    $(showName).removeClass('makeMeHide').addClass('makeMeVisible');

                    $(".viewQuestion").removeClass("roundies");
                    $(".viewQuestion").removeClass("activeAnswer");
                    $(this).addClass('activeAnswer');
                    
                    if (!isIE) {
                                    $(this).addClass('roundies');
                    }
});
 /********************************************************
     * OPTIMIZE 435 - SAT Fee Example  Modal 
  	********************************************************/     
    $(function () {  	
 
    	$('#sptStudyGuideLink').click(function(){
        		$('#cbmTriggerInlineModal:has(#sptStudyGuideBody)').addClass('sptGuideModal');
        		$('#cbmTriggerInlineModal:has(#sptStudyGuideBody).cbmContents').css('z-index', '1');
        		$('.practiceSection .jqmOverlay').css('z-index', '1');
        		
   	});        			
    });    

    /********************************************************
     * OPTIMIZE 435 - SAT Fee Example  Modal 
     ********************************************************/
    $(function () {  	
    	$('#satRegFeeExampleLink').click(function(){
    		$('#cbmTriggerInlineModal:has(#satRegFeeExample)').addClass('feesExampleModal');
    	});
    });
    /********************************************************
    * Visualize Results Summary - Graph bars
    *********************************************************/
    $(function () { 
    	
    	$("#totalResultsSummary div dl").horizontalBarGraph({
    		colors: ["#019464", "#FD0000","#FFF"],  
    		interval: 1.1});

    	$("#easyResultsSummary dl").horizontalBarGraph({
    		colors: ["#019464", "#FD0000","#FFF"],  
    		interval: 1.1});
    	
    	$("#mediumResultsSummary dl").horizontalBarGraph({
    		colors: ["#019464", "#FD0000","#FFF"],  
    		interval: 1.1});

    	$("#hardResultsSummary dl").horizontalBarGraph({
    		colors: ["#019464", "#FD0000","#FFF"],  
    		interval: 1.1});
    	
    	$('#visualResultsLink').click(function(){
    		$('#cbmTriggerInlineModal:has(#totalResultsSummary)').addClass('visualModal');
    	});
    }); 

	 /***************************************************************
	  * ** ------------------ REWRITE VERSION -------------------- **
	  * **  		Rewrite of the Pagination Implementation	   ** 
	  * **					(April 5th Release) 					   **
	  * *************************************************************/
	 var current = new Number($("#indexOfCurrent").val())-1;//  Get the index of the currently selected question
	 var currentUrl = getCurrentUrl();
	 var totalNumOfQuestions = new Number($("#totalNumOfQuestions").val());
	 var questionsDisplayed = 5; //The pagination will only show 5 question at a time	
	 //var subSection;
	 //var subSectionId;
	 var totalPages;
	 var totalTabs = getTotalTabs();
	 var currentPage = -1;

	 // if there are tabs, then initialize the required parameters
		
		if(isTabbed()=='true'){	
			totalTabs = getTotalTabs();
			var sectionPattern = /\&subSectionStateId\=(\d*)/i;// regular expression string to find the tab's/subSections's substring in the question's url
	 	 	var subSection = new String(currentUrl.match(sectionPattern));	 	 	
	 	 	var subSectionId = new Number(subSection.substr((subSection.length-1)));//obtains the tab's/subsection's id number from the current question's url
		}
		else{
			var subSectionId = -1;
		}	
		initPagination();
	 //Driver function that invokes the necessary Pagination functionality
	 function initPagination(){

		 if(getCurrentUrl()){

			 //initTabVars();
		totalPages = new Number(getTotalPages());
		currentPage = displayQuestions();
		setPrevFiveIcon();
		setNextFiveIcon();
		setPrevIcon();
		setNextIcon();
	 }

	 }

	  
	// Creates the pagination functionality by only displaying the questions on the current page.  
	 function displayQuestions(){
	 var page;
	 var index;
	 	for(  page=0, index = 0, count=1; count<totalNumOfQuestions && page < totalPages; count++ ) {
	 		if( index<= current  && current < (index + questionsDisplayed)){
	 			showPage(page);
	 			break;
	 		}else{
	 			index = index + questionsDisplayed;
	 			page++;
	 		}
	 	}
	 	return page;
	 }

	//Sets the navigation state and url for the 'PrevFiveIcon'
	 function setPrevFiveIcon(){
		 
		 if ( isFirstPage()==true && isFirstTab()==true) {
			 	 	disableID("#prevFiveIcon","#prevFiveLink" );
			 }else{
		 			enableID("#prevFiveIcon", "#prevFiveLink");
		 			if(isFirstPage()==false){
		 				var prevIndex = (questionsDisplayed * (currentPage-1));
		 				var prevPage = getQuestionUrl(prevIndex);
		 				$('#prevFiveLink').attr('href', prevPage);
		 			}
		 			else{

		 				//var prevTab = new String(currentUrl + "&tabAction=previous5");
		 				var prevIndex = subSectionId -1;
		 				var prevTab = getPrev5TabUrl(prevIndex);
	 					$('#prevFiveLink').attr('href', prevTab);
		 			}
		 	}
	 }	
	//Sets the navigation state and url for the 'NextFiveIcon'
	 function setNextFiveIcon(){
		 	if (isLastPage()==true && isLastTab()==true) {
		 	 	disableID("#nextFiveIcon","#nextFiveLink" );
		 }else{
			 	enableID("#nextFiveIcon", "#nextFiveLink");
			 	if(isLastPage()==false){
			 		var nextIndex = (questionsDisplayed * (currentPage +1));
			 		var nextPage = getQuestionUrl(nextIndex);
			 		$('#nextFiveLink').attr('href', nextPage);
			 	} else{
		 			var nextTab = new Number(subSectionId)+1;
		 			var nextTabUrl = getTabUrl(nextTab);
		 			$('#nextFiveLink').attr('href', nextTabUrl);
			 	}		 	
	 	}
	 }
	//Sets the navigation state and url for the 'PrevIcon'
	 function setPrevIcon(){

		 	if (isFirstQuestion()==true  && isFirstPage()==true && isFirstTab()==true) {
		 	 	disableID("#prevIcon");
		 	 	$('#prevLink img').attr('src', '/img/prevBigGrayArrow.gif');
		 	}else{
		 		enableID("#prevIcon");
		 		
		 		if(isFirstQuestion()==false)	{
		 			var prev = getQuestionUrl(new Number(current-1));
		 			$('#prevLink').attr('href', prev);
		 		}else{				 			
						//var prevTab = new String(currentUrl + "&tabAction=previous");
		 			var prevIndex = subSectionId-1;
		 			var prevTab = getPrevTabUrl(prevIndex);
		 				
	 					$('#prevLink').attr('href', prevTab);
		 		}

		 			$('#prevLink img').attr('src', '/img/prevBigArrow.gif');
		 	}
	 }
	//Sets the navigation state and url for the 'NextIcon'
	 function setNextIcon(){
		 	if (isLastQuestion()==true && isLastPage()==true && isLastTab()==true) {
		 	 	disableID("#nextIcon");
		 	 	$('#nextLink img').attr('src', '/img/nextBigGrayArrow.gif');
		 	}else{
		 		enableID("#nextIcon");
		 		if(isLastQuestion()==false){
		 			var next = getQuestionUrl(current+1);
		 			$('#nextLink').attr('href', next);
		 		} else{
		 			var nextTab = subSectionId+1;
		 			var nextTabUrl = getTabUrl(nextTab);
		 			$('#nextLink').attr('href', nextTabUrl);
		 		}	
		 		$('#nextLink img').attr('src', '/img/nextBigArrow.gif');
		 	} 
	 }
	 //Obtains and returns the url of the selected question 
	 function getQuestionUrl(index){
		 return $("#practiceTestProgress li.roundies a").eq(index).attr("href");
	 }
	 //Returns the new tab subSection url string
	 function getSectionString(){
		 return ("&subSectionStateId="+ new String(subSectionId));
	 }
	//obtains the current questions's url
	 function getCurrentUrl(){
		 return $("#practiceTestProgress li.roundies a").eq(current).attr("href");  
	 }	 
	// Checks to see whether the question section has subsections or tabs
	 function isTabbed(){
		 return $("#practiceIsTabbed").val(); 	 
	 }
	//obtains the total number of question sections/tabs are in thie practice section
	 function getTotalTabs(){
		 return $("#practiceTestTabMenu li").length; 
	 }
	//checks if this is the first question of the section
	 function isFirstQuestion(){
		 return new Boolean((current==0?true:false)); 
	 }	 
	//checks if this is the last question of the section
	 function isLastQuestion(){
		 var lastQuestion = totalNumOfQuestions-1; //gets the last question's id (index begins with zero)
		 return new Boolean((current==lastQuestion?true:false)); 	 
	 }
	 //Checks if this the last 'page' of the questions being displayed	 
	 function isLastPage(){	 
		 return new Boolean((currentPage==(totalPages-1)?true:false)); 
	 }	 
	 //Checks if this the first 'page' of the questions being displayed
	 function isFirstPage(){
			return new Boolean((currentPage==0?true:false)); 
		 }	 
	//checks to see if the first tab/subsection is selected
	 function isFirstTab(){
		 if(subSectionId==-1 ||subSectionId==undefined){
			 return true;
		 }	 
		 return new Boolean((subSectionId==1?true:false)); 
	 } 
	//checks to see if the last tab/subsection is selected
	 function isLastTab(){
		 if(subSectionId==-1 ||subSectionId==undefined ){
			 return true;
		 }
		 return new Boolean((subSectionId==(totalTabs)?true:false));
	 }	
	//calculates the number of pages the current section
	 function getTotalPages(){
		 var totalPages = Math.round (totalNumOfQuestions / questionsDisplayed); 
		 // If there are more questions than pages, add another page.
		 if((totalPages * questionsDisplayed) <totalNumOfQuestions ) {
			 totalPages++; 
	 	}	 
	 	return totalPages;
	 }
	 //Using the current question's url, it replaces key parameters to the next tab's first question set. and returns the new url
	 function getTabUrl(index){
		var url = new String(currentUrl);
		var sectionPattern = "subSectionStateId";
		var newSection = new String("&subSectionStateId="+index);
		var exp = new RegExp("");
		exp.compile("\\&" + sectionPattern + "\\=(\\d*)", "i");		
		url = url.replace(exp, newSection);
		
		var questionSetPattern = "questionSetStateId";
		exp = new RegExp("");
		exp.compile("\\&" + questionSetPattern + "\\=(\\d*)", "i");
		url = url.replace(exp, "&questionSetStateId=1");
		
		var questionPattern = "questionStateId";		
		exp = new RegExp("");		
		exp.compile("\\&" + questionPattern + "\\=(\\d*)", "i");
		url = url.replace(exp, "&questionStateId=1");
		return url;
	 }	
	 function getPrev5TabUrl(index){
			var url = new String(currentUrl);
			var sectionPattern = "subSectionStateId";
			var newSection = new String("&subSectionStateId="+index +"&tabAction=previous5");
			var exp = new RegExp("");
			exp.compile("\\&" + sectionPattern + "\\=(\\d*)", "i");		
			url = url.replace(exp, newSection);
			return url;
	 }	
	 function getPrevTabUrl(index){
			var url = new String(currentUrl);
			var sectionPattern = "subSectionStateId";
			var newSection = new String("&subSectionStateId="+index +"&tabAction=previous");
			var exp = new RegExp("");
			exp.compile("\\&" + sectionPattern + "\\=(\\d*)", "i");		
			url = url.replace(exp, newSection);
			return url;
	 }	
	 /****************** END OF VIEWR APP REWRITE ******************************************/
	 
	// Applies the pageShow class to the id passed to the function to display the selected id to the user 	
	 function showPage(page){

	 	var start = (questionsDisplayed * page);
	 	var end = (questionsDisplayed *(page+1));
	 
	 	for (index = start; index<end && current >= start && current <end; index++){
	 		$("#practiceTestProgress li.roundies").eq(index).removeClass("pageHide");
		}
	 }
	 
	// Applies the Enabled class to the id passed to the function 	
	function enableID (id, linkId){
		if($(id).hasClass("disabled")){
			$(id).removeClass("disabled");
		}

		if($(linkId).hasClass("linkDisabled"))
		{
			$(linkId).removeClass("linkDisabled");
		}		
		
		$(id).addClass("enable");
	 }

	// Applies the Disabled class to the id passed to the function
	function disableID (id, linkId){
		if($(id).hasClass("enabled"))
		{
			$(id).removeClass("enabled");
		}
		$(linkId).addClass("linkDisabled");
		$(id).addClass("disabled");
	 }
	
	function next(elem) {
	    do {
	        elem = elem.nextSibling;
	    } while (elem && elem.nodeType != 1);
	    return elem;                
	}
    	
	/************************ OPTIMIZE 471 ************************/
	$('#sptAdditionalThingsExpand').click(function() {
		$('#sptAdditionalInfo1').addClass('twirled');
		$('#choosingMath12Twirldown').show();
		
		$('#sptAdditionalInfo2').addClass('twirled');
		$('#useCalculatorTwirldown').show();
		
		$('#sptAdditionalInfo3').addClass('twirled');
		$('#calculatorTipsTwirldown').show();
		
		$('#sptAdditionalInfo4').addClass('twirled');
		$('#questionsGeometicTwirldown').show();

	});
	
	$('#sptAdditionalThingsCollapse').click(function() {
		$('#sptAdditionalInfo1').removeClass('twirled');
		$('#choosingMath12Twirldown').hide();
		
		$('#sptAdditionalInfo2').removeClass('twirled');
		$('#useCalculatorTwirldown').hide();
		
		$('#sptAdditionalInfo3').removeClass('twirled');
		$('#calculatorTipsTwirldown').hide();
		
		$('#sptAdditionalInfo4').removeClass('twirled');
		$('#questionsGeometicTwirldown').hide();
	});	
	/****************  END OF SAT.INIT.JS CHANGES *****************/
 
});
