jQuery.fn.extend({
    exampleQuestion: function(options) {
        var defaults, init, submit; 
        defaults = { 
            type: 'multi',
            storedAnswer: '#qotdStoredAnswer',
            explanation: '#qotdExplanation',
            result: '#qotdQuestionResult, .sprQuestionResult',
            showAnswer: '#qotdQuestionResultShowAnswer',
            error: '.errors',
            errorAnswerText: '.errorAnswer',
            textAnswer: '.textAnswer',
            incorrectAnswer: '.incorrectAnswer',
            correctAnswer: '.correctAnswer',
            correctClass: 'correct',
            incorrectClass: 'incorrect',
            errorsClass: 'errors'
        };  

        jQuery.extend(defaults, options);

        init = function (parentCont, submit) {
            var d = defaults;

            if (!submit) {
                $('input:checked', parentCont).removeAttr('checked');
            }

            $('input.button', parentCont).show();
            $(d.result + ',' + 
            d.explanation + ',' + 
            d.result + ',' + 
            d.showAnswer + ',' + 
            d.error + ',' + 
            d.incorrectAnswer + ',' + 
            d.correctAnswer, parentCont).hide();

            $(d.result, parentCont).find('p').hide();
            $(d.result, parentCont).removeClass(d.incorrectClass).removeClass(d.correctClass).removeClass(d.errorsClass);
            $('input[type=radio]', parentCont).parents('li').removeClass(d.incorrectClass).removeClass(d.correctClass);
        };

        showAnswer = function (el) {
            var form = $(el).parents('form'), d = defaults;
            $('input[type=radio][value=' + $(d.storedAnswer).val() + ']').attr('checked','checked');
            $('input.button', form).click();
        }

        submit = function (submitEl) {
            var form = $(submitEl).parents('form'), sprTxtVals = '', sprRadioVals = '', d = defaults;

            init($(submitEl).parents('form'), 1);
            if (d.type === 'multi') {
                if (!$('input[type=radio]:checked', form)[0]) {
                    $(d.error, form).show();
                    return false;
                }

                //Incorrect
                if ($('input[type=radio]:checked', form).val() == $(d.storedAnswer, form).val()) {
                    $('input.button', form).hide();
                    $(d.explanation + ',' + d.result + ',' + d.correctAnswer, form).show();
                    $('input[type=radio]:checked', form).parents('li').addClass(d.correctClass);
                    $('input[type=radio]', form).attr('disabled', 'true');
                    $(d.result, form).addClass(d.correctClass);
                //Correct
                } else {
                    $(d.result + ',' + d.incorrectAnswer + ',' + d.showAnswer, form).show();
                    $('input[type=radio]:checked', form).parents('li').addClass(d.incorrectClass);
                    $(d.result, form).addClass(d.incorrectClass);
                    return false;
                }
            } else if (d.type === 'spr') {
                if (!$('input[type=radio]:checked', form)[0]) {
                    $(d.result, form).show().addClass(d.errorsClass);
                    $(d.errorAnswerText, form).show();
                    return false;
                }

                //Gather each values
                $('input[id^=answerTyped]', form).each(function (i) {
                    sprTxtVals += (!$(this).val()) ? ' ' : $(this).val();
                });

                var sprRadioVals =  ($('input[name^=answerBubble-0-1-mathSPRq]:checked', form).val() || ' ') + 
                                    ($('input[name^=answerBubble-0-2-mathSPRq]:checked', form).val()  || ' ') +
                                    ($('input[name^=answerBubble-0-3-mathSPRq]:checked', form).val()  || ' ') +
                                    ($('input[name^=answerBubble-0-4-mathSPRq]:checked', form).val() || ' ');
                
                //Answer can't start and end with a space, nor can it have a space in the middle, so I'm checking both here
                if (/^\s+.*?\s$|.*?[\.\\\d]\s+[\.\\\d]/.test(sprTxtVals) || /^\s+.*?\s$|.*?[\.\\\d]\s+[\.\\\d]/.test(sprRadioVals)) {
                    $(d.result + ',' + d.incorrectAnswer , form).show();
                    $(d.result, form).addClass(d.incorrectClass);
                    $(d.textAnswer, form).show();
                    return false;
                } else if ((sprRadioVals != sprTxtVals) || sprTxtVals === $(d.storedAnswer, form).val()) {
                    $(d.result + ',' + d.incorrectAnswer , form).show();
                    $(d.result, form).addClass(d.incorrectClass);
                    $(d.textAnswer, form).show();
                    return false;
                } else {
                    $(d.result + ',' + d.correctAnswer, form).show();
                    $(d.result).addClass(d.correctClass);
                    return false;
                }
            }
            
        };  
        
        return this.each(function() {
            init(this);
            $('input.button', this).click(function () { 
                submit(this);
                return false;
            }); 

            $(defaults.showAnswer, this).click(function () { 
                showAnswer(this);
                return false;
            }); 
        }); 
    }   
});

jQuery.fn.extend({
    simplePager: function(options) {
        var defaults, 
            goToSlide, 
            slide, 
            prevNexControlsDisplay, 
            autoRotate, 
            startAutoRotate, 
            killAutoRotate, 
            parentCont, 
            content, 
            pagination, 
            currentEl,
            actionPageEl, 
            prevButton,
            nextButton,
            currentIndex = 0,
            autoRotateSlideIndex,
            autoRotateInterval,
            autoRotateTimeout; 

        if (this.length === 0) {
            return false;
        }

        defaults = { 
            content: null,
            targetPagerCont: null,
            pageControl: null,
            pageControlActiveClass: 'current',
            prevControl: null,
            nextControl: null,
            callback: null
        };  

        jQuery.extend(defaults, options);
        parentCont = this;
        content = $($(defaults.content), this); 
        pagination = $('<ul></ul>').appendTo($(this).find(defaults.targetPagerCont));

        if (defaults.navULClass) {
            pagination.addClass(defaults.navULClass);
        }

        goToSlide = function (el, slideIndex, suspendRotate) {
            autoRotateSlideIndex = slideIndex; //For global scope

            if (suspendRotate && defaults.autoRotate) { //This is only true on click
                killAutoRotate();
            }

            if (currentEl) {
                currentEl.removeClass(defaults.pageControlActiveClass);
            }

            currentEl = $(el).parents('li').addClass(defaults.pageControlActiveClass);

            if (defaults.transition) {
                $(content[currentIndex]).fadeOut(defaults.transition, function () {
                    $(content[slideIndex]).show();            
                    currentIndex = slideIndex;
                });
            } else {
                $(content[currentIndex]).hide();
                $(content[slideIndex]).show();            
                currentIndex = slideIndex;
            }

            if (defaults.prevNextCont) {
                prevNextControlsDisplay(currentIndex);
            }
        };

        slide = function (newIndex) {
            if ($('a', pagination)[newIndex]) {
                $($('a', pagination)[newIndex]).click();
                currentIndex = newIndex;
            }
            prevNextControlsDisplay(newIndex);
        };

        prevNextControlsDisplay = function (i) {

            if (i === $('a', pagination).length - 1) {
                nextButton.hide();
                prevButton.show();
            } else if (i <= 0) {
                prevButton.hide();
                nextButton.show();
            } else if (i > 0 ) {
                prevButton.show();
                nextButton.show();
            }

        };

        startAutoRotate = function () {
            autoRotateInterval = setInterval(function () { autoRotate(currentIndex); }, defaults.autoRotate * 1000);
        };

        killAutoRotate = function () {
            clearInterval(autoRotateInterval); //Clear rotate
            clearTimeout(autoRotateTimeout);
            autoRotateTimeout = setTimeout(
                function () {
                    startAutoRotate()
                }, 
                5000
            ); //Kick it off again in 10
        };

        autoRotate = function () {
            autoRotateSlideIndex = (content.length === (autoRotateSlideIndex + 1)) ? 0 : autoRotateSlideIndex += 1;
            goToSlide($('a', pagination)[autoRotateSlideIndex], autoRotateSlideIndex);
        };


        if (content.length <= 1 || !content[0]) { 
            return false;
        }

        content.each(function (i) {
            $(this).hide(); 
            actionPageEl = $('<li class="page' + i + '"><a href="#">' + (i + 1) + '</a></li>').appendTo(pagination);

            if (defaults.navLIClass) {
                actionPageEl.addClass(defaults.navLIClass);
            }

            $('a', actionPageEl).click(function (e) {
                goToSlide(this, i, true); 
                return false;
            });

        });

        if (defaults.prevNextCont) {
            prevButton = $('<a href="#" title="Previous">Previous</a>').appendTo(defaults.prevNextCont);
            nextButton = $('<a href="#" title="Next">Next</a>').appendTo(defaults.prevNextCont);
            if (defaults.prevClass) {
                prevButton.addClass(defaults.prevClass);
            }
            if (defaults.nextClass) {
                nextButton.addClass(defaults.nextClass);
            }

            $(prevButton).hide().click(function () {
               slide(currentIndex - 1)
                if (defaults.scrollTo) {
                    $(defaults.scrollTo).scrollTo('500');
                }
                return false;
            });
            $(nextButton).click(function () {
                slide(currentIndex + 1);
                if (defaults.scrollTo) {
                    $(defaults.scrollTo).scrollTo('500');
                }
                return false;
            });
        }

        if (defaults.callback) {
            defaults.callback(pagination,content);
        }

        if (defaults.autoRotate) {
            startAutoRotate();
        }

        goToSlide($('a', pagination)[currentIndex], currentIndex);
        
        return this;
    }
});

jQuery.fn.extend({
    fillHeight: function(options) {

        if (this.length === 0) {
            return false;
        }

        var defaults, 
            tallestColHeight = 0,
            tallestModulesHeight = 0, 
            modulesHeight = 0, 
            numberCols = 0, 
            fillHeight = 0,
            remainder = 0,
            tallestCol, 
            tallestModule; 

        defaults = { 
            type: 'standard',
            toMatch: null
        };  

        jQuery.extend(defaults, options);
       
        if (defaults.type === 'standard') { 
            this.each(function () {
                if ($(this).outerHeight() >= tallestColHeight) {
                    tallestColHeight = $(this).outerHeight();
                } 
            });        

            this.each(function () {
                remainder =  tallestColHeight - (parseInt($(this).css('padding-top'), 10) + parseInt($(this).css('padding-bottom'), 10));
                remainder = remainder - $(this).height();
                $(this).height($(this).height() + remainder); 
            });

        } else if (defaults.type === 'multi') {
            numCols = this.length;

            this.each(function () {
                if ($(this).outerHeight() >= tallestColHeight)  {
                    
                    tallestColHeight = $(this).outerHeight();
                    tallestCol = this;
                } 
            });        

            this.each(function () {
                if (this != tallestCol) {
                    $(defaults.toMatch, this).each(function () {
                        modulesHeight += $(this).outerHeight();
                    });

                    fillHeight = tallestColHeight - modulesHeight - ($(defaults.toMatch+':last', this).outerHeight() - $(defaults.toMatch+':last', this).height()); 
                    
                    $(defaults.toMatch+':last', this).height($(defaults.toMatch+':last', this).height() + fillHeight);

                    //Account for margin
                    if ($(defaults.toMatch, this).length === 1) {
                        $(defaults.toMatch+':last', this).height($(defaults.toMatch+':last', this).height() + (tallestColHeight - $(this).height())) 
                    } 
                
                }
            });

        }

        return this;
    }
});

jQuery.fn.extend({
    skillsInsight: function(options) {
        var defaults,
            answerMap = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6};

        defaults = {
            answersContainer: 'skillChoiceList'
        };  

        jQuery.extend(defaults, options);

        setIt = function (button, container) {
            var klass = button.className.match(/\b[abcdefg]{1,1}\b/i)[0];
            var index = answerMap[klass.toLowerCase()];
            $($('ul.' + defaults.answersContainer + ' li', container)[index]).addClass('correct');
        };
       
        return this.each(function () {
            var container = this;
            $(this).find('.revealAnswerLink').click(function () {
                setIt(this, container); 
                return false;
            });
        });
    }
});

jQuery.fn.extend({
	inputText: function() {     	
    	this.each(function() {
			var attVal = $(this).attr('value'); 
    		$(this).focus(function(){ 
    			if ($(this).val() == attVal) { 
    				$(this).val(''); 
    			} 
    		}).blur(function() { 
                if ($(this).val() == '' ) { 
                    $(this).val(attVal); 
                } 
            });     
        }); 
    } 
}); 
//ieTabStates
jQuery.fn.extend({
    ieTabStates: function(options) {
        var defaults,
            el,
            width,
            backgroundColor,
            paddingRight,
            paddingLeft,
            paddingBottm,
            paddingTop,
            initIE;

        defaults = {
            'activeKlass': 'current'
        };  

        jQuery.extend(defaults, options);

        //Legacy - possible reuse
        var init = function (el) {
            el = jQuery(el); 
            href = jQuery('a', el).attr('href');
            width = el.outerWidth();
            backgroundColor = el.css('background-color');
            paddingRight = el.css('padding-right');
            paddingLeft = el.css('padding-left');
            paddingBottom = el.css('padding-bottom');
            paddingTop = el.css('padding-top');

            el.css({
                'padding': '0',
                'background': 'none',
                'border': 'none'
            });

            //Weird IE bug here, when I move the contents, the anchor, get's prepended with the full URL
            el.html('<div class="tabWrapper">'+el.html()+'</div>');
            //So I stored it and reset it.
            jQuery('a', el).attr('href', href);

            jQuery('<div class="tl"><div class="tr"></div></div><div class="bl"><div class="br"></div></div>').prependTo(el);

            jQuery('.tl, .bl', el).css({
                'width': width - 10 + 'px'
            });

            jQuery('.bl', el).css({
                'bottom': 0
            });

            jQuery('.tl', el).css({
                'top': 0
            });

            jQuery('.tabWrapper', el).css({
                'padding': '0px ' + paddingRight + ' 0px ' +  paddingLeft
            });

            if(parseFloat(paddingBottom, 10)) {
                jQuery('.tabWrapper', el).css({
                    'margin-bottom': paddingBottom
                });
            }

            if(parseFloat(paddingTop, 10)) {
                jQuery('.tabWrapper', el).css({
                    'margin-top': paddingTop
                });
            }

            jQuery(el).mouseover(function() { 
                jQuery(this).addClass('hover');
            }).mouseout(function () { 
                jQuery(this).removeClass('hover');
            });

        };

        var currentEl;

        initIE = function (el) {
            el = jQuery(el);

            jQuery(el).mouseover(function() { 
                jQuery(this).css({
                    'background-color':'#003D5A'
                });
            }).mouseout(function () { 
                if (jQuery(this).hasClass(defaults.activeKlass)) {
                    jQuery(this).css('background-color', '#ffffff');
                } else {
                    jQuery(this).css('background-color', '#85948D');
                }
            })

            $('a', el).click(function () {
                jQuery(this).parents('ul').find('li').css('background-color', '#85948D');
                jQuery(this).parent().css('background-color', '#ffffff');
            });

        };

        return this.each(function () {
            //Legacy
            //init(this);
            initIE(this);
        });
    }
});

//Accessible UL with links - to select elment with onchange action to url
jQuery.fn.extend({
    ulToSelectElm: function(options) {

        var init, selectElm, defaults, anchor;

        defaults = {
            'klass': 'selectBox'
        };  

        jQuery.extend(defaults, options);

        init = function (ul) {
            
            selectElm = jQuery('<select id="' + jQuery(ul).attr('id') + '" name = "' + jQuery(ul).attr('id')  + '" class="' + defaults.klass + '"></select>').insertAfter(ul),
            anchors = jQuery('li a', ul);

            jQuery('<option selected>' + defaults.initialOption + '</option>').appendTo(selectElm); 

            anchors.each(function () {
                jQuery('<option value="' + jQuery(this).attr('href') + '">' + jQuery(this).html() + '</option>').appendTo(selectElm); 
            });

            jQuery(ul).remove();

            if (defaults.callback) {
                defaults.callback(selectElm);
            }

        };

        return this.each(function () {
            if (jQuery(this).is('ul')) {
                init(this);
            }
        });

    }
});


//Adds play button via canvas, for video thumbs
jQuery.fn.extend({
    playButton: function(options) {
        var defaults, 
            makeButton, 
            button;

        defaults = {'width': '30', 'height': '30', 'top': 0, 'left': 0 };  

        jQuery.extend(defaults, options);

        makeButton = function (el) {

            var canvasElem = document.createElement('canvas'); 
            var ctx = $(canvasElem).attr({'width': defaults.width, 'height': defaults.height}).appendTo(el)[0];

            if (typeof (G_vmlCanvasManager) === 'object') { // ie IE
                G_vmlCanvasManager.initElement(ctx); 
            }

            ctx = ctx.getContext('2d');

            ctx.arc(15,15,12,0,Math.PI*2,true);
            ctx.fillStyle = '#00abf9';
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 3;
            ctx.fill();
            ctx.stroke();

            // Triangle
            ctx.beginPath();
            ctx.moveTo(12, 8);
            ctx.lineTo(12, 22);
            ctx.lineTo(21, 15);
            ctx.fillStyle = '#fff';
            ctx.fill();
            ctx.closePath();

        };
       
        return this.each(function () {
            makeButton(this); 
        });
    }
});

(function($){$.fn.horizontalBarGraph=function(options){var opts=$.extend({},$.fn.horizontalBarGraph.defaults,options);this.children("dt,dd").each(function(i){var el=$(this);if(el.is("dt")){el.css({display:"block","float":"left",clear:"left"}).addClass("hbg-label");return;}else{(isTitleDD(el)&&opts.hasTitles?createTitle:createBar)(el,opts);}
setBarHover(el,opts);});tryShowTitle(this);if(opts.animated){createShowButton(opts,this).insertBefore(this);}
if(opts.colors.length){setColors(this.children("dd"),opts);}
if(opts.hoverColors.length){setHoverColors(this.children("dd"),opts);}
scaleGraph(this);return this;};function scaleGraph(graph){var maxWidth=0;graph.children("dt").each(function(){maxWidth=Math.max($(this).width(),maxWidth);}).css({width:maxWidth+"px"});}
function setBarHover(bar,opts){bar.hover(function(){bar.addClass("hbg-bar-hover");},function(){bar.removeClass("hbg-bar-hover");});}
function createShowButton(opts,graph){var button=$("<span />").text(opts.button).addClass("hbg-show-button");button.click(function(){graph.children("dd").show('slow',function(){button.fadeOut('normal');});});return button;}
function createBar(e,opts){var val=e.text();e.css({marginLeft:e.prev().is("dt")?"5px":"0px",width:Math.floor(val/opts.interval)+"px"});e.html($("<span/>").html(val).addClass("hbg-value"));applyOptions(e,opts);}
function createTitle(e,opts){var title=e.text();e.prev().attr("title",title);e.remove();}
function tryShowTitle(graph){var title=graph.attr("title");if(title){$("<div/>").text(title).addClass("hbg-title").insertBefore(graph);graph.css({overflow:"hidden"});}}
function setColors(bars,opts){var i=0;bars.each(function(){var c=i++%opts.colors.length;$(this).css({backgroundColor:opts.colors[c]});});}
function setHoverColors(bars,opts){var i=0;bars.each(function(i){var bar=$(this);var c=bar.css("background-color");var hc=opts.hoverColors[i++%opts.hoverColors.length];bar.hover(function(){$(this).css({backgroundColor:hc});},function(){$(this).css({backgroundColor:c});});});}
function applyOptions(e,opts){e.css({'float':'left'}).addClass("hbg-bar");if(opts.animated){e.hide();}}
function isTitleDD(e){return(e.is(":even")&&e.prev().is("dd"));}
$.fn.horizontalBarGraph.defaults={interval:1,hasTitles:false,animated:false,button:'Show Values',colors:[],hoverColors:[]};})(jQuery);
