/** 
 * Global Object which all SAT project specific methods.
 * 
 * @namespace   CB.SAT
 * @author      UI Development Team 
 */
if (typeof CB.SAT === 'undefined' || !CB.SAT) {
    CB.SAT = {};
}

var SAT = CB.SAT;

//Ties to modal
SAT.compareStateChartVisualizeHook = (function ($C) {
    var options = {
                    percentageBarGraph: true,
                    labels: false,
                    ylabel: false,
                    ylabelIntervalLine: false,
                    appendKey: false,
                    appendTitle: false,
                    parseDirection: 'x',
                    barMargin: 0,
                    barGroupMargin: 0,
                    colors: ['#787001','#a8931b'],
                    width: 350, 
                    height: 180
                };
    return {
        init: function () {

            $C.jqmWrapper.customize({
                'compareStatsLink': {
                    'actions': {
                        'onLoad': function (o, callbacks) { 
                            $(o.w).find('table#compareState').visualize(options);
                        }
                    }
                }
            });

            $('table#compareState').visualize(options);
        }
    };
})(CB);

//Trigger SAT Test Dates for subject base on subject
SAT.toggleSatTestDates =  (function ($C) {
	var iCounter = 0 ;
    return {
        init: function (o) {	
			$(o.trigger).click(function () {	

                var targetElm = $('#' + o.target + $(this).val()),
                    tablePos = targetElm.parents("table").find('tbody > tr:first'),
                    rowEl;

                if ($(this).attr('checked') == true) {

                    if (iCounter === 0) { 
                        targetElm.parents("div#satTestDateTable").show();
                        targetElm.parents("table").find('thead > tr').show();
                    } 

                    if (tablePos[0] !== targetElm[0]) {
                        rowEl = targetElm.remove();
                        $(rowEl).insertBefore(tablePos).show();
                    } else {
                        targetElm.show();
                    }

                    iCounter++;	

                } else {
					targetElm.hide();	
					iCounter--;	

					if(iCounter === 0) {
                        targetElm.parents("div#satTestDateTable").hide();
                        targetElm.parents("table").find('thead > tr').hide();
					}
				}
			});	

            //Check for those checked on init
            $(o.trigger).each(function () {
                if ($(this).attr('checked')) {
                    $(this).click().attr('checked', 'checked');
                }
            });
		}
	}
})(CB);

//TODO - WHAT THE HECK IS THIS?
CB.timer = $(function(){

    // Page timer function
	pageTimerFn = function(pCurrentCounter){
			// parse a second counter into a readable time
			// then display it in the timerText area
			// triggered by #timerStart onclick, fired once a second
			// until paused or stopped
			var totalSecs = pCurrentCounter.counter++;
			if(totalSecs<10){
				var currentTime = "0:0" + totalSecs;
			}else if(totalSecs<60){
				var currentTime = "0:" + totalSecs;	
			}else if(totalSecs<3600){
				var totalMins = Math.floor(totalSecs/60);
				var remSecs = totalSecs - (totalMins*60);
				if(remSecs<10){
					remSecs = "0" + remSecs;	
				}
				var currentTime = totalMins + ":" + remSecs;
			}else{
				var totalHours = Math.floor(totalSecs/3600);
				var remMins = Math.floor( (totalSecs - (totalHours*3600))/60 );
				if(remMins < 10){
					remMins = "0" + remMins;	
				}
				var remSecs = totalSecs - (remMins*60) - (totalHours*3600);
				var currentTime = totalHours + ":" + remMins + ":" + remSecs;
			}
			$('#timerText').html(currentTime);
	}

	/* pageTimerModal */

		// aria-disable the form for modal control
		$('.questionForm').attr('aria-disabled', 'true');

		var containerHeight = $('#questionFormContainer').height();
		var containerWidth = $('#questionFormContainer').width();
		$('.questionTimerModal, .questionTimerModalBg').css('height',containerHeight);
		$('.questionTimerModal, .questionTimerModalBg').css('width',containerWidth);
		$('.questionTimerModalBg').css('opacity', 1);

		$('#timerModalPanel').append("<a id='timerStart' href='#questionFormContainer'>START TIMER</a>");

	
	/* page timer for timed practice */
	if($('.pageTimer')){
		var currentCounter = new Object({counter: 1});
		var simpleTimer = 0;
		$('#timerStart').click(function(event){
			simpleTimer = setInterval(pageTimerFn, 1000, currentCounter);
			$('.questionTimerModal').css('display', 'none');
			// aria-enable the form
			$('.questionForm').attr('aria-disabled', 'false');
			$('#timerPause').css('display', 'inline');
			event.preventDefault();
		});
	 
		$('#timerPause').click(function(event){
			clearInterval(simpleTimer);
			$('#timerPause').css('display', 'none');
			// aria-disable the form
			$('.questionForm').attr('aria-disabled', 'true');
			$('.questionTimerModal').css('display', 'block');
			event.preventDefault();
		});
	}	
});	// end wrapper function

			
/**
 * customize jqmWrapper for resetting stats in left rail, no longer a page refresh
 *
 * @memberOf    jQuery
 * @type        Method
 * @public
 * @static
 *
 */
CB.jqmWrapper.customize({
    'cbmTriggerResetStats': {
        'actions': {
            'onLoad': function (o, callbacks) { 
                jQuery('#myOrgQotdResetReset', o.w).click(function () {
                    jQuery('tr', '#myOrgQotdStats').each(function () {
                        jQuery(jQuery('td', this)[1]).html('0/0');
                        jQuery(jQuery('td', this)[2]).html('0%');
                    });
                });
            }
        }
    }
});

/**
 * customize jqmWrapper for handshake modal 
 *
 * @memberOf    jQuery
 * @type        Method
 * @public
 * @static
 *
 */
CB.jqmWrapper.customize({
    'cbmTriggerHandshake': {
        'actions': {
            'onShow': function (o, callbacks) { 
                o.c.ajax = "/html/cbm/handshake.html";
            },
            'onLoad': function (o, callbacks) {
                CB.utils.setParams(jQuery(o.t), {'decorator': 'none'}, true);
                o.w.find('#handshakeContinue').attr('href', jQuery(o.t).attr('href'));

                //Fire exit site page name
                CB.omniture.init({
                    'type': 'pageView', 
                    'properties': {
                        'pageName': 'SATSitePopup:exitsite'
                    }
                });

            }
        }
    }
});

/**
 * customize jqmWrapper inline/static omniture implementation
 *
 * @memberOf    jQuery
 * @type        Method
 * @public
 * @static
 *
 */
CB.jqmWrapper.customize({
    'cbmTriggerInline': {
        'actions': {
            'onShow': function (o, callbacks) { 
                CB.omniture.init({
                    'type': 'pageView', 
                    'properties': {
                        //Takes the value of the href, which is really the id of the inline content to display
                        'pageName': 'SATSitePopup:' + jQuery(o.t).text().replace(/\s/g,'')
                    }
                });
            }
        }
    }
});

CB.jqmWrapper.customize({
    'cbmTriggerVisualize': {
        'actions': {
            'onShow': function (o, callbacks) { 
                CB.omniture.init({
                    'type': 'pageView', 
                    'properties': {
                        //Takes the value of the href, which is really the id of the inline content to display
                        'pageName': 'SATSitePopup:' + jQuery(o.t).text().replace(/\s/g,'')
                    }
                });
            }
        }
    }
});


CB.jqmWrapper.customize({
    'cbmTriggerStatic': {
        'actions': {
            'onShow': function (o, callbacks) { 
                CB.omniture.init({
                    'type': 'pageView', 
                    'properties': {
                        //Takes the value of the href, which is really the id of the inline content to display
                        'pageName': 'SATSitePopup:' + jQuery(o.t).text().replace(/\s/g,'')
                    }
                });
            }
        }
    }
});


	
	
//Test Day Simulator
SAT.TDS = (function ($C) {
    var init, drawPlayer, drawThumbs, changeClip;

    init  = function (config) {
        if (!jQuery("#" + config.drawPlayerTo)[0]) {
            return false;
        } else {
            drawPlayer(config);
            drawThumbs(config);
        }

    };
    
    drawPlayer = function (config) {
		CB.utils.swfObject({
			'swfUrl': config.src,
			'id': config.drawPlayerTo,
			'width': config.width,
			'height': config.height,
			'params': {
				'allowFullScreen': 'true',
				'allowScriptAccess': 'always',
				'wmode': 'transparent',
				'quality': 'autohigh'
			},
			'flashvars': {
				'JSON': escape(jQuery.toJSON({ 
					'config': {},
					'custom': config.json,
					'aSrcAccount': s_account
				}))
			},
			'attributes': {
				'id': config.playerId
			}				
		});
    };

    drawThumbs = function (config) {
        var i = 0, 
            clip,
            ulCont,
            li,
            a,
            img,
            div;

        jQuery(config.drawThumbsTo).html('');

        ulCont = jQuery('<ul class="testDaySimVideoBlocks"></ul>').appendTo(config.drawThumbsTo);

        for (i; i < config.json.clips.length; i++) {
            li = jQuery('<li class="videoBlockContent roundies"></li>').appendTo(ulCont);
            div = jQuery('<div class="videoBlockContent"></div>').appendTo(li);
            a  = jQuery('<a href="#' + config.drawPlayerTo + '" title="' + config.json.clips[i].title + '"></a>').appendTo(div);
            img = jQuery('<img src="' + config.json.clips[i].thumbPath + '" alt="' + config.json.clips[i].title + '" />').appendTo(a);
            jQuery('<div><h5 style="color:#' + config.json.clips[i].color.split('x')[1] + '">' + config.json.clips[i].title + '</h5></div>').appendTo(div);

            //Closure 
            jQuery(li, a, div).css('cursor','pointer').bind('click', function (count) {
                return function () {
                    changeClip(count, config);
                };
            }(i));
        }

        Cufon.replace(config.drawThumbsTo + " h5");
    };

    changeClip = function (count, config) {
        var fc = jQuery('#' + config.playerId);
        if(fc[0]){
            fc[0].loadThisClip(count); 
        }   
    };

    return {
        init: init
    };

})(CB);
// CountDown Timer for full practice test pages
SAT.countdownTimer = (function ($C) {
	var _init, _totalTimeArr, _startTimer, _newColor, _countdownTarget, _noJSClass, _normalClass, _endedClass, _timeOutScroll, _initScroller, _originalOffset, _startTime, _endTime, _countDown, _onScroll, _timerInterval, _lastScrollAmount;
	
	_init = function(config){
		_totalTimeArr = jQuery('#'+config.timeRemainingId).html().split(':');
		_countdownTarget = jQuery('#'+config.countDownContainerId);
		_noJSClass = config.noJSClass;
		_normalClass = config.countingDownClass;
		_endedClass = config.endedClass;
		_lastScrollAmount = 10;
		
		_originalOffset = _countdownTarget.offset().top;
		_initScroller();
		_startTimer();
	};
	
	_initScroller = function(){
		jQuery(window).scroll(function(){
			if(_timeOutScroll) clearTimeout(_timeOutScroll);
			_timeOutScroll = setTimeout("SAT.countdownTimer.onScroll()", 100);
		});		
	}
	
	_startTimer = function (){
		_startTime = new Date();
		_endTime = new Date();
		var totalSeconds = parseInt(_totalTimeArr[0] * 60) + parseInt(_totalTimeArr[1]);

		_countdownTarget.removeClass(_noJSClass);
		_countdownTarget.addClass(_normalClass);
		_countdownTarget.html(_twoDgt(_totalTimeArr[0])+":"+_twoDgt(_totalTimeArr[1]));
		
		if(totalSeconds <= 0){
			_countdownTarget.html("00:00");
			_changeColor();
		}else{
			_endTime.setSeconds(_endTime.getSeconds() + totalSeconds);
			_timerInterval = setInterval("SAT.countdownTimer.countDown()", 1000);
		}
	}
	
	_countDown = function(){
		var e = _endTime;
		var timeDiff = _toUTC(e) - _toUTC(_startTime);

		var newTime = new Date(timeDiff);
		newTime.setSeconds(newTime.getSeconds() - 1);
		e.setSeconds(e.getSeconds() - 1);
		_countdownTarget.html(_twoDgt(newTime.getMinutes()) + ":" + _twoDgt(newTime.getSeconds()));
		
		if (newTime.valueOf() <= 0){
			_changeColor();
			clearInterval(_timerInterval);		
			return;
		}
	}
	
	_onScroll = function(){
		_countdownTarget.stop();
		var scrollTop = jQuery(window).scrollTop();
		var scrollLimit = $('#cancelButton').offset().top - 100;
		var scrollAmount = (scrollTop > _originalOffset && scrollTop < scrollLimit)? scrollTop - _originalOffset + 20 : (scrollTop > scrollLimit)? _lastScrollAmount : 10;
		_countdownTarget.animate({'top': scrollAmount},{'duration':'fast', 'easing':'linear'});
		_lastScrollAmount = scrollAmount;
		_timeOutScroll = null;
	}
	
	_twoDgt = function(n){
		return String(n).replace(/^(\d)$/, "0$1");
	}
	
	_changeColor = function(){
		_countdownTarget.removeClass(_normalClass);
		_countdownTarget.addClass(_endedClass);
	}

	_toUTC = function (dateObj){
		var d = dateObj;
		return Date.UTC(d.getFullYear(),
						d.getMonth(),
						d.getDay(),
						d.getHours(),
						d.getMinutes(),
						d.getSeconds(),
						d.getMilliseconds()
						);
	}
	
	return {
		init: _init,
		countDown: _countDown,
		onScroll: _onScroll
	};
})(CB);
//Answers Imagined
SAT.AI = (function ($C) {

    var init, drawPlayer, drawIndicators, drawThumbs, cleanAnswers;

    init = function (config) {
        if (!jQuery("#" + config.playerTop)[0]) {
            return false;
        } else {
            cleanAnswers();
			drawIndicators(config);			
            drawPlayer(config, 0, 1);
			// once the player is drawn we need set it to the playerId since swfObject wipes out the original div id.
			config.drawPlayerTo = config.playerId;
			drawThumbs(config);		
        }
    };

    cleanAnswers = function () {
        jQuery('.qotdChoiceList li').css('background', 'none');
        jQuery('.qotdChoiceList input').addClass('accessHide');
        jQuery('.qotdChoiceList label').css({'padding-left': 0, 'margin-left': 0});
    };

    drawPlayer = function (config, count, init) {
        jQuery(config.json.aiConts).hide();
        jQuery(jQuery(config.json.aiConts)[count]).show();

		CB.utils.swfObject({
			'swfUrl': config.json.aiQs[count].swfPath,
			'id': config.drawPlayerTo,
			'width': '680',
			'height': '245',
			'version': '10',			
			'params': {
				'allowFullScreen': 'true',
				'allowScriptAccess': 'always',
				'wmode': 'opaque',
				'quality': 'autohigh'
			},
			'flashvars': {
				'JSON': escape(jQuery.toJSON({ 
					"aSrcAccount": s_account
				}))
			},			
			'attributes': {
				'id': config.playerId,
				'tabindex': 1
			}				
		});		
		
        if (typeof init === 'undefined' || !init) {
            CB.omniture.init({
                'type': 'pageView', 
                'properties': {
                    'pageName': (count === 0) ? s.pageName : 'sat/practice/answers-imagined/' + config.json.aiQs[count].pageName, 
                    'events': 'event7' 
                }
            });
        }

   };
	drawIndicators = function(config){
		var j, ulCont, li, a;
		
		ulCont = jQuery('<ul class="none answersImagingedBar"></ul>').appendTo(jQuery('#aiQuestionsBar'));		
		
		for (j = 0; j < config.json.aiQs.length; j++) {
			li = jQuery('<li class="floatLeft '+ (((j+1) == config.json.aiQs.length)? 'last' : '') + ' ' + ((j == 0)? 'active' : '') + '"></li>').appendTo(ulCont);
			a =  jQuery('<a href="#' + config.playerTop + '" title="' + config.json.aiQs[j].title + '">'+config.json.aiQs[j].title.replace('>', '><br />') +'</a>').appendTo(li);
			
			jQuery(a)
			.css('cursor','pointer').bind('click', function (count) {
				return function () {
					jQuery(this).parent().parent().children().removeClass('active');
					jQuery(this).parent().addClass('active');
					drawPlayer(config, count);
				};  
			}(j));			
		}
	};
    drawThumbs = function (config) {
        var i = 0,  
            ulCont,
            li, 
            a,  
            img;

        jQuery(config.drawThumbsTo).html('');

        ulCont = jQuery('<ul class="none moreAnswersImagined"></ul>').appendTo(config.drawThumbsTo);

        for (i; i < config.json.aiQs.length; i++) {
            li = jQuery('<li class="floatLeft"></li>').appendTo(ulCont);
            a  = jQuery('<a href="#' + config.playerTop + '" title="' + config.json.aiQs[i].title + '"' + ((i%2) ? ' class="dlm"' : '') + '></a>').appendTo(li);
            img = jQuery('<img src="' + config.json.aiQs[i].thumbPath + '" alt="' + config.json.aiQs[i].title + '" />').appendTo(a);

            //Closure 
            jQuery(a).css('cursor','pointer').bind('click', function (count) {
                return function () {
                    drawPlayer(config, count);
                };  
            }(i));
        }   



    };

    return {
        'init': init
    }

})(CB);


SAT.timeline = (function ($C) {

    var init, localConfiger, drawPlayer, drawTextBlocks, prepContent, currentContent, showText, JSON;
    JSON = { 
        "clips" : [
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1901.flv",
                "year" : "1901",
                "title" : "What started as an acorn"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1926.flv",
                "year" : "1926",
                "title" : "Leveling the playing field"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1937.flv",
                "year" : "1937",
                "title" : "Achievement Tests show where students shine"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1939.flv",
                "year" : "1939",
                "title" : "Bubble sheets and electronic scoring"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1941.flv",
                "year" : "1941",
                "title" : "Standardizing the SAT"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1958.flv",
                "year" : "1958",
                "title" : "Students get to see their scores"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1965.flv",
                "year" : "1965",
                "title" : "Civil rights and the SAT"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1969.flv",
                "year" : "1969",
                "title" : "Introduction of student fee waivers"
		 	},
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1977.flv",
                "year" : "1977",
                "title" : "A nationwide test"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1984.flv",
                "year" : "1984",
                "title" : "Getting to know the SAT"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1994.flv",
                "year" : "1994",
                "title" : "Changing times, changing test"
            },
            {
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/1995.flv",
                "year" : "1995",
                "title" : "The original College Board Online"
            },
			{
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/2005.flv",
                "year" : "2005",
                "title" : "The new SAT"
            },
			{
                "flvPath" : "http://media.collegeboard.com/SAT/media/video/history-of-sat/2009.flv",
                "year" : "2009",
                "title" : "It's your choice"
            }
        ]
    };

    init  = function (config) {
        if (!jQuery('#' + config.drawPlayerTo)[0]) {
            return false;
        } else {
            localConfig = config;
            drawPlayer(config);
            prepContent(config.content);
        }

    };

    prepContent = function (content) {
        jQuery(document).ready(function () {
            jQuery('div:not(:first)', content).addClass('accessHide');
            currentContent = jQuery('div', content).eq(0);
        });
        
    };

    showText = function (i) {
       jQuery(currentContent).fadeOut('1000', function () {
            jQuery(this).addClass('accessHide').attr('style', '');
            jQuery('div', localConfig.content).eq(i).removeClass('accessHide').css({zoom:1});
        } );

        currentContent = jQuery('div', localConfig.content).eq(i);
        jQuery(localConfig.title).html(JSON.clips[i].title);

    };
    
    drawPlayer = function (config) {
		CB.utils.swfObject({
			'swfUrl': config.src,
			'id': config.drawPlayerTo,
			'width': config.width,
			'height': config.height,
			'params': {
				'allowFullScreen': 'true',
				'allowScriptAccess': 'always',
				'wmode': 'transparent',
				'quality': 'autohigh'
			},
			'flashvars': {
				'JSON': escape(jQuery.toJSON({ 
					"config": {},
					"custom": JSON,
					"aSrcAccount": s_account
				}))
			},
			'attributes': {
				'id': config.playerId
			}				
		});		
    };
	
    return {
        JSON: JSON,
        showText: showText,
        init: init
    };

})(CB);


//adding the current year to the footer
SAT.formatDate = (function (id) {
		var d=new Date();
		fullYear = d.getFullYear();
		jQuery(id).html(fullYear);
});

/**
* Object controls section selection via dropdown menu and pagination for the Question & Answer section of the Full Practice Test reports.
* Also displays submit buttons if javascript is disabled allowing pages to still be accesible. The object affects the following FTL pages only:
*  
*  /SAT/ftl/practice/fullPracticeTest/fullPracticeViewExplanations.ftl
*  /SAT/ftl/practice/fullPracticeTest/fullPracticeQuestionsAndAnswersReport.ftl
*  /SAT/ftl/practice/fullPracticeTest/fullPracticeViewExplanations.ftl
* @author David Cho
*/
SAT.answerExplanations = (function(){
    if (jQuery('#mainBody').hasClass('viewQA')){
        $('#sectionSubmit').addClass('sectionSubmitOff');	
        $('#sectionSelector').submitForm({eventType:'change'});		
			
        $('#answersExplanation').submitForm({eventType:'click',formName:'#viewAnswersAndExplanationsForm'});
        $('#ansExplanations').addClass('ansExplanationsOff');		
			
        $('#summaryLink').submitForm({eventType:'click',formName:'#viewAnswersAndExplanationsForm'});
        $('#summaryBtn').addClass('summaryBtnOff');
			
        $('#previousSection').click(function () {
                var previous = $('#viewAnswersAndExplanationsForm_sectionNumber').val();
                document.getElementById('explanationSectionChooser').sectionNumber.value = previous - 1;
                $('#explanationSectionChooser').submit(); 
        });
			
        $('#nextSection').click(function () {
                var next = $('#viewAnswersAndExplanationsForm_sectionNumber').val();
                document.getElementById('explanationSectionChooser').sectionNumber.value = parseInt(next)+1;
                $('#explanationSectionChooser').submit(); 
        });		
    }
});



/**
 *  Mbox Draft 
 */

SAT.mboxes = (function () {
    
    var controllers;

    controllers =  {
        swapText: function (o) {
            jQuery(o.location).html(o.locationText);
            return controllers;
        },

        setEvent: function (o) {
            jQuery(o.location)[o.eventType](o.eventToSet);
            return controllers;
        }
    };

    return {
        controllers: controllers
    };

})(); 

