/* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENSE:
 *
 * Released under a MIT License. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 */

jQuery.url = function()
{
	var segments = {};
	
	var parsed = {};
	
	/**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
  	var options = {
	
		url : window.location, // default URI is the page in which the script is running
		
		strictMode: false, // 'loose' parsing by default
	
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}
		
	};
	
    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */		
	var parseUri = function()
	{
		str = decodeURI( options.url );
		
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}

		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
  	 * 
	 * @param string key The key whose value is required
     */		
	var key = function( key )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		} 
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}
	
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	
	/**
     * Returns the value of the required query string parameter.
  	 * 
	 * @param string item The parameter whose value is required
     */		
	var param = function( item )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
     */	
	var setUp = function()
	{
		parsed = parseUri();
		
		getSegments();	
	};
	
    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};
	
	return {
		
	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function( mode )
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */		
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		
		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */	
		segment : function( pos )
		{
			if ( ! parsed.length )
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},
		
		attr : key, // provides public access to private 'key' function - see above
		
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();

(function($){
  $.fn.fieldhighlighter = function(options){
    var settings = jQuery.extend({}, jQuery.fn.fieldhighlighter.settings, options)

    return this.each(function(){
      $(':input:text, :input:password, textarea, select, :input:checkbox').focus(function(){
        $(this).closest(settings.highlightselector).addClass(settings.cssclass);
      }).blur(function(){
        $(this).closest(settings.highlightselector).removeClass(settings.cssclass);
      });
    });
  };
  $.fn.fieldhighlighter.settings = {
    cssclass: "highlight",
    highlightselector: ".fieldmarker"
  };
})(jQuery);

(function($){
  $.fn.preventDoubleSubmit = function(options){
    var settings = jQuery.extend({}, jQuery.fn.preventDoubleSubmit.settings, options);

    return this.each(function(){
      $(this).submit(function(){
        //console.log("SUMBIT");
        $(':submit', this).click(function() {
          //console.log("DENY");
          return false;
        });
      });
    });
  };
  $.fn.preventDoubleSubmit.settings = {
  };
})(jQuery);

(function($){
  $.fn.flasher = function(options){
    var settings = jQuery.extend({}, jQuery.fn.flasher.settings, options)

    return this.each(function(){
      $(this).children("p").append(removeLink($(this).children("p"), this));
      function removeLink(messageContainer, parent_container){
        link = $("<a href=\"#\" id=\"#flasher-close-link\">Close</a>")
        link.css({
          "width" : "3em",
          "text-decoration" : "none",
          "-webkit-border-radius" : ".9em",
          "-moz-border-radius" : ".9em",
          "border" : "none",
          //"float" : "left",
          //"display" : "inline-block",
          "margin" : "0 auto",
          "padding" : ".3em .8em .4em .8em",
          "color" : "#FFF",
          "text-shadow" : "none",
          "background" : $(parent_container).css("color")
        });
        link.click(function(){
          $(this).closest("#notice, #error, #notice").remove();
          $("body").removeClass("flash");
        });
        return $(link);
      }
      
    });
    
  };
  $.fn.flasher.settings = {
  };
})(jQuery);

(function($){
  $.fn.definition_matching = function(options){
    var settings = jQuery.extend({}, jQuery.fn.definition_matching.settings, options)
    return this.each(function(){
      var words = [];
      var definitions = [];
      var references = $("<div class=\'fine-print\'></div>");
      // Definition Title
      $(this).children("dl").children("dt").each(function(index, dt){
        //console.log(index);
        words.push($("<li id=\'"+index+"\'>"+$(dt).html()+"</li>"));
        $(dt).remove();
      });
      
      // Definition
      $(this).children("dl").children("dd").each(function(index, dd){
        definitions.push($("<li id=\'"+index+"\'>"+$(dd).html()+"</li>"));
        $(dd).remove();
      });
      
      // References
      $(this).children("p").each(function(index, r){
        references.append($("<p id=\'"+index+"\'>"+$(r).html()+"</p>"));
        $(r).remove();
      });
      
      $(this).children("dl").each(function(){ $(this).remove(); });
      var word_list = $("<ol id=\'match-left\'></ol>");
      var definition_list = $("<ol id=\'match-right\'></ol>");
      var alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
      var word_answers = [];
      var definition_answers = [];
      var definitions_key = '';

      //console.log(words);
      //Randomize arrays
      words.sort(function() {return 0.5 - Math.random()});
      definitions.sort(function() {return 0.5 - Math.random()});

      $.each(words,
        function(index, word){
          word_list.append(word);
          //console.log(word.attr("id"))
          word_answers.push(word.attr("id"));

        }
      );

      $.each(definitions,
        function(index, definition){
          definition_list.append(definition);
          definition_answers.push(definition.attr("id"));
        }
      );

      $(this).append(definition_list);
      $(this).append(word_list);

      $.each(word_answers,
        function(index, word_answer){
          alphabet_index = definition_answers.indexOf(word_answer);
          if(index == 0){
            definitions_key = "ANSWERS: " + (index+1) + "-" + alphabet[alphabet_index] + ", "
          }else if(index == (word_answers.length - 1)){
            definitions_key += (index+1) + "-" + alphabet[alphabet_index];
          }else{
            definitions_key += (index+1) + "-" + alphabet[alphabet_index] + ", ";
          }
          //console.log((index+1) + "-" + word_answers + "-" + alphabet[alphabet_index]);
          //console.log(word_answer + " " + definition_answers.indexOf(word_answer));
        }
      );
      //var defintions_key_paragraph = Builder.node('p', definitions_key);
      $(this).append( "<div class=\'fine-print\'><p>"+definitions_key+"</p></div>" );
      //console.log(definitions_key);

      $(this).append(references)
      
    });
  };
  $.fn.definition_matching.settings = {
  };
})(jQuery);

$j = jQuery.noConflict();
g = {};

$jc = function( c )
{
  return $j( '.' + c );
};

$jid = function( id )
{
  return $j( '#' + id );
};

(function($){
  $.fn.tabify = function(options){
    var settings = jQuery.extend({}, jQuery.fn.flasher.settings, options)

    return this.each(function(i){
      //console.log("current:" + i + " length:" + $(this).length);
      $(this).attr("id", "tabify-"+i);
      var contents = $("#tabify-"+i+" ."+settings.targetClass);
      var targetName = settings.targetClass
      //console.log("#tabify-"+i+" "+settings.targetClass)
      var tabHeadings = [];
      if(contents.length < 2){
        return false;
      }else{
        contents.each(function(fi){
          $(this).attr("id", "tabify-"+targetName+"-"+fi);
          //console.log("Set ID");
          //console.log("VAR FORMS: current:" + i + " length:" + $(this).length);
          //console.log("#tabify-"+targetName+"-"+fi+" "+settings.headingSelector)
          tabHeadings.push({tabLabel: $.trim($("#tabify-"+targetName+"-"+fi+" "+settings.headingSelector).text()), tabID: "#tabify-"+targetName+"-"+fi});
          if(fi != 0){
            //console.log(i);
            $(this).hide();
          }
        });
        var tabHTML = "";
        $.each(tabHeadings, function(index, value){
          tabHTML = tabHTML + "<li><a href=\"#\" rel=\""+value.tabID+"\">"+value.tabLabel+"</a></li>"
          //console.log(value.tabLabel + " " + value.tabID);
        });
        $("<div class=\""+settings.tabClass+"\"><ul>"+tabHTML+"</ul></div>").prependTo($(this));
        $("."+settings.tabClass+" ul li:first").addClass("current");
        $("."+settings.tabClass+" ul li a").click(function() {
          $("."+settings.tabClass+" ul li").removeClass("current"); //Remove any "active" class
          $(this).parent("li").addClass("current"); //Add "active" class to selected tab
          $("."+settings.targetClass).hide(); //Hide all tab content

          var activeTab = $(this).attr("rel"); //Find the href attribute value to identify the active tab + content
          $(activeTab).show(); //Fade in the active ID content
          return false;
        });
        //console.log(tabHeadings);
      }
    });
    
  };
  $.fn.flasher.settings = {
    targetClass:  "form",
    tabClass:     "tabs",
    headingSelector:"h1"
  };
})(jQuery);

var videoJSPlayers=new Array();(function(){var initializing=false,fnTest=/xyz/.test(function(){xyz;})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(prop){var _super=this.prototype;initializing=true;var prototype=new this();initializing=false;for(var name in prop){prototype[name]=typeof prop[name]=="function"&&typeof _super[name]=="function"&&fnTest.test(prop[name])?(function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);this._super=tmp;return ret;};})(name,prop[name]):prop[name];}function Class(){if(!initializing&&this.init)this.init.apply(this,arguments);}Class.prototype=prototype;Class.constructor=Class;Class.extend=arguments.callee;return Class;};})();var VideoJS=Class.extend({init:function(element,setOptions){this.video=element;this.video.controls=false;this.options={num:0,controlsBelow:false,controlsHiding:true,defaultVolume:0.85,flashVersion:9,linksHiding:true};if(typeof setOptions=="object")_V_.merge(this.options,setOptions);this.box=this.video.parentNode;this.flashFallback=this.getFlashFallback();this.linksFallback=this.getLinksFallback();if(VideoJS.browserSupportsVideo()||((this.flashFallback||VideoJS.isIE())&&this.flashVersionSupported())){this.hideLinksFallback();}
if(VideoJS.browserSupportsVideo()){if(this.canPlaySource()==false){this.replaceWithFlash();return;}}else{return;}
if(VideoJS.isIpad()){this.options.controlsBelow=true;this.options.controlsHiding=false;}
if(this.options.controlsBelow){_V_.addClass(this.box,"vjs-controls-below");}
this.percentLoaded=0;this.buildPoster();this.showPoster();this.buildController();this.showController();this.video.addEventListener("loadeddata",this.onLoadedData.context(this),false);this.video.addEventListener("play",this.onPlay.context(this),false);this.video.addEventListener("pause",this.onPause.context(this),false);this.video.addEventListener("ended",this.onEnded.context(this),false);this.video.addEventListener('volumechange',this.onVolumeChange.context(this),false);this.video.addEventListener('error',this.onError.context(this),false);this.video.addEventListener('progress',this.onProgress.context(this),false);this.watchBuffer=setInterval(this.updateBufferedTotal.context(this),33);this.playControl.addEventListener("click",this.onPlayControlClick.context(this),false);this.video.addEventListener("click",this.onPlayControlClick.context(this),false);if(this.poster)this.poster.addEventListener("click",this.onPlayControlClick.context(this),false);this.progressHolder.addEventListener("mousedown",this.onProgressHolderMouseDown.context(this),false);this.progressHolder.addEventListener("mouseup",this.onProgressHolderMouseUp.context(this),false);this.setVolume(localStorage.volume||this.options.defaultVolume);this.volumeControl.addEventListener("mousedown",this.onVolumeControlMouseDown.context(this),false);this.volumeControl.addEventListener("mouseup",this.onVolumeControlMouseUp.context(this),false);this.updateVolumeDisplay();this.fullscreenControl.addEventListener("click",this.onFullscreenControlClick.context(this),false);this.video.addEventListener("mousemove",this.onVideoMouseMove.context(this),false);this.video.addEventListener("mouseout",this.onVideoMouseOut.context(this),false);if(this.poster)this.poster.addEventListener("mousemove",this.onVideoMouseMove.context(this),false);if(this.poster)this.poster.addEventListener("mouseout",this.onVideoMouseOut.context(this),false);this.controls.addEventListener("mouseout",this.onVideoMouseOut.context(this),false);this.onEscKey=function(event){if(event.keyCode==27){this.fullscreenOff();}}.context(this);this.onWindowResize=function(event){this.positionController();}.context(this);this.fixPreloading()},fixPreloading:function(){if(typeof this.video.hasAttribute=="function"&&this.video.hasAttribute("preload")){this.video.autobuffer=true;}},buildController:function(){this.controls=_V_.createElement("ul",{className:"vjs-controls"});this.video.parentNode.appendChild(this.controls);this.playControl=_V_.createElement("li",{className:"vjs-play-control vjs-play",innerHTML:"<span></span>"});this.controls.appendChild(this.playControl);this.progressControl=_V_.createElement("li",{className:"vjs-progress-control"});this.controls.appendChild(this.progressControl);this.progressHolder=_V_.createElement("ul",{className:"vjs-progress-holder"});this.progressControl.appendChild(this.progressHolder);this.loadProgress=_V_.createElement("li",{className:"vjs-load-progress"});this.progressHolder.appendChild(this.loadProgress)
this.playProgress=_V_.createElement("li",{className:"vjs-play-progress"});this.progressHolder.appendChild(this.playProgress);this.timeControl=_V_.createElement("li",{className:"vjs-time-control"});this.controls.appendChild(this.timeControl);this.currentTimeDisplay=_V_.createElement("span",{className:"vjs-current-time-display",innerHTML:"00:00"});this.timeControl.appendChild(this.currentTimeDisplay);this.timeSeparator=_V_.createElement("span",{innerHTML:" / "});this.timeControl.appendChild(this.timeSeparator);this.durationDisplay=_V_.createElement("span",{className:"vjs-duration-display",innerHTML:"00:00"});this.timeControl.appendChild(this.durationDisplay);this.volumeControl=_V_.createElement("li",{className:"vjs-volume-control",innerHTML:"<ul><li></li><li></li><li></li><li></li><li></li><li></li></ul>"});this.controls.appendChild(this.volumeControl);this.volumeDisplay=this.volumeControl.children[0]
this.fullscreenControl=_V_.createElement("li",{className:"vjs-fullscreen-control",innerHTML:"<ul><li></li><li></li><li></li><li></li></ul>"});this.controls.appendChild(this.fullscreenControl);},getLinksFallback:function(){return this.box.getElementsByTagName("P")[0];},hideLinksFallback:function(){if(this.options.linksHiding&&this.linksFallback)this.linksFallback.style.display="none";},getFlashFallback:function(){if(VideoJS.isIE())return;var children=this.box.getElementsByClassName("vjs-flash-fallback");for(var i=0,j=children.length;i<j;i++){if(children[i].tagName.toUpperCase()=="OBJECT"){return children[i];}}},replaceWithFlash:function(){if(this.flashFallback){this.box.insertBefore(this.flashFallback,this.video);this.video.style.display="none";}},showController:function(){this.controls.style.display="block";this.positionController();},positionController:function(){if(this.controls.style.display=='none')return;if(this.videoIsFullScreen){this.box.style.width="";}else{this.box.style.width=this.video.offsetWidth+"px";}
if(this.options.controlsBelow){if(this.videoIsFullScreen){this.box.style.height="";this.video.style.height=(this.box.offsetHeight-this.controls.offsetHeight)+"px";}else{this.video.style.height="";this.box.style.height=this.video.offsetHeight+this.controls.offsetHeight+"px";}
this.controls.style.top=this.video.offsetHeight+"px";}else{this.controls.style.top=(this.video.offsetHeight-this.controls.offsetHeight)+"px";}
this.sizeProgressBar();},hideController:function(){if(this.options.controlsHiding)this.controls.style.display="none";},updatePosterSource:function(){if(!this.video.poster){var images=this.video.getElementsByTagName("img");if(images.length>0)this.video.poster=images[0].src;}},buildPoster:function(){this.updatePosterSource();if(this.video.poster){this.poster=document.createElement("img");this.video.parentNode.appendChild(this.poster);this.poster.src=this.video.poster;this.poster.className="vjs-poster";}else{this.poster=false;}},showPoster:function(){if(!this.poster)return;this.poster.style.display="block";this.positionPoster();},positionPoster:function(){if(this.poster==false||this.poster.style.display=='none')return;this.poster.style.height=this.video.offsetHeight+"px";this.poster.style.width=this.video.offsetWidth+"px";},hidePoster:function(){if(!this.poster)return;this.poster.style.display="none";},canPlaySource:function(){var children=this.video.children;for(var i=0,j=children.length;i<j;i++){if(children[i].tagName.toUpperCase()=="SOURCE"){var canPlay=this.video.canPlayType(children[i].type);if(canPlay=="probably"||canPlay=="maybe"){return true;}}}
return false;},onPlay:function(event){this.playControl.className="vjs-play-control vjs-pause";this.hidePoster();this.trackPlayProgress();},onPause:function(event){this.playControl.className="vjs-play-control vjs-play";this.stopTrackingPlayProgress();},onEnded:function(event){this.video.pause();this.onPause();},onVolumeChange:function(event){this.updateVolumeDisplay();},onError:function(event){console.log(event);console.log(this.video.error);},onLoadedData:function(event){this.showController();},onProgress:function(event){if(event.total>0){this.setLoadProgress(event.loaded/event.total);}},updateBufferedTotal:function(){if(this.video.buffered){if(this.video.buffered.length>=1){this.setLoadProgress(this.video.buffered.end(0)/this.video.duration);if(this.video.buffered.end(0)==this.video.duration){clearInterval(this.watchBuffer);}}}else{clearInterval(this.watchBuffer);}},setLoadProgress:function(percentAsDecimal){if(percentAsDecimal>this.percentLoaded){this.percentLoaded=percentAsDecimal;this.updateLoadProgress();}},updateLoadProgress:function(){if(this.controls.style.display=='none')return;this.loadProgress.style.width=(this.percentLoaded*(_V_.getComputedStyleValue(this.progressHolder,"width").replace("px","")))+"px";},onPlayControlClick:function(event){if(this.video.paused){this.video.play();}else{this.video.pause();}},onProgressHolderMouseDown:function(event){this.stopTrackingPlayProgress();if(this.video.paused){this.videoWasPlaying=false;}else{this.videoWasPlaying=true;this.video.pause();}
_V_.blockTextSelection();document.onmousemove=function(event){this.setPlayProgressWithEvent(event);}.context(this);document.onmouseup=function(event){_V_.unblockTextSelection();document.onmousemove=null;document.onmouseup=null;if(this.videoWasPlaying){this.video.play();this.trackPlayProgress();}}.context(this);},onProgressHolderMouseUp:function(event){this.setPlayProgressWithEvent(event);},onVolumeControlMouseDown:function(event){_V_.blockTextSelection();document.onmousemove=function(event){this.setVolumeWithEvent(event);}.context(this);document.onmouseup=function(){_V_.unblockTextSelection();document.onmousemove=null;document.onmouseup=null;}.context(this);},onVolumeControlMouseUp:function(event){this.setVolumeWithEvent(event);},onFullscreenControlClick:function(event){if(!this.videoIsFullScreen){this.fullscreenOn();}else{this.fullscreenOff();}},onVideoMouseMove:function(event){this.showController();clearInterval(this.mouseMoveTimeout);this.mouseMoveTimeout=setTimeout(function(){this.hideController();}.context(this),4000);},onVideoMouseOut:function(event){var parent=event.relatedTarget;while(parent&&parent!==this.video&&parent!==this.controls){parent=parent.parentNode;}
if(parent!==this.video&&parent!==this.controls){this.hideController();}},sizeProgressBar:function(){this.updatePlayProgress();this.updateLoadProgress();},getControlsPadding:function(){return _V_.findPosX(this.playControl)-_V_.findPosX(this.controls)},getControlBorderAdjustment:function(){var leftBorder=parseInt(_V_.getComputedStyleValue(this.playControl,"border-left-width").replace("px",""));var rightBorder=parseInt(_V_.getComputedStyleValue(this.playControl,"border-right-width").replace("px",""));return leftBorder+rightBorder;},trackPlayProgress:function(){this.playProgressInterval=setInterval(function(){this.updatePlayProgress();}.context(this),33);},stopTrackingPlayProgress:function(){clearInterval(this.playProgressInterval);},updatePlayProgress:function(){if(this.controls.style.display=='none')return;this.playProgress.style.width=((this.video.currentTime/this.video.duration)*(_V_.getComputedStyleValue(this.progressHolder,"width").replace("px","")))+"px";this.updateTimeDisplay();},setPlayProgress:function(newProgress){this.video.currentTime=newProgress*this.video.duration;this.playProgress.style.width=newProgress*(_V_.getComputedStyleValue(this.progressHolder,"width").replace("px",""))+"px";this.updateTimeDisplay();},setPlayProgressWithEvent:function(event){var newProgress=_V_.getRelativePosition(event.pageX,this.progressHolder);this.setPlayProgress(newProgress);},updateTimeDisplay:function(){this.currentTimeDisplay.innerHTML=_V_.formatTime(this.video.currentTime);if(this.video.duration)this.durationDisplay.innerHTML=_V_.formatTime(this.video.duration);},setVolume:function(newVol){this.video.volume=parseFloat(newVol);localStorage.volume=this.video.volume;},setVolumeWithEvent:function(event){var newVol=_V_.getRelativePosition(event.pageX,this.volumeControl.children[0]);this.setVolume(newVol);},updateVolumeDisplay:function(){var volNum=Math.ceil(this.video.volume*6);for(var i=0;i<6;i++){if(i<volNum){_V_.addClass(this.volumeDisplay.children[i],"vjs-volume-level-on")}else{_V_.removeClass(this.volumeDisplay.children[i],"vjs-volume-level-on");}}},fullscreenOn:function(){if(!this.nativeFullscreenOn()){this.videoIsFullScreen=true;this.docOrigOverflow=document.documentElement.style.overflow;document.addEventListener("keydown",this.onEscKey,false);window.addEventListener("resize",this.onWindowResize,false);document.documentElement.style.overflow='hidden';_V_.addClass(this.box,"vjs-fullscreen");this.positionController();this.positionPoster();}},nativeFullscreenOn:function(){if(typeof this.video.webkitEnterFullScreen=='function'&&false){if(!navigator.userAgent.match("Chrome")){this.video.webkitEnterFullScreen();return true;}}},fullscreenOff:function(){this.videoIsFullScreen=false;document.removeEventListener("keydown",this.onEscKey,false);window.removeEventListener("resize",this.onWindowResize,false);document.documentElement.style.overflow=this.docOrigOverflow;_V_.removeClass(this.box,"vjs-fullscreen");this.positionController();this.positionPoster();},flashVersionSupported:function(){return VideoJS.getFlashVersion()>=this.options.flashVersion;}})
var _V_={addClass:function(element,classToAdd){if(element.className.split(/\s+/).lastIndexOf(classToAdd)==-1)element.className=element.className==""?classToAdd:element.className+" "+classToAdd;},removeClass:function(element,classToRemove){if(element.className.indexOf(classToRemove)==-1)return;var classNames=element.className.split(/\s+/);classNames.splice(classNames.lastIndexOf(classToRemove),1);element.className=classNames.join(" ");},merge:function(obj1,obj2){for(attrname in obj2){obj1[attrname]=obj2[attrname];}return obj1;},createElement:function(tagName,attributes){return _V_.merge(document.createElement(tagName),attributes);},blockTextSelection:function(){document.body.focus();document.onselectstart=function(){return false;};},unblockTextSelection:function(){document.onselectstart=function(){return true;};},formatTime:function(seconds){seconds=Math.round(seconds);minutes=Math.floor(seconds/60);minutes=(minutes>=10)?minutes:"0"+minutes;seconds=Math.floor(seconds%60);seconds=(seconds>=10)?seconds:"0"+seconds;return minutes+":"+seconds;},getRelativePosition:function(x,relativeElement){return Math.max(0,Math.min(1,(x-_V_.findPosX(relativeElement))/relativeElement.offsetWidth));},findPosX:function(obj){var curleft=obj.offsetLeft;while(obj=obj.offsetParent){curleft+=obj.offsetLeft;}
return curleft;},getComputedStyleValue:function(element,style){return window.getComputedStyle(element,null).getPropertyValue(style);}}
VideoJS.setup=function(options){var elements=document.getElementsByTagName("video");for(var i=0,j=elements.length;i<j;i++){videoTag=elements[i];if(videoTag.className.indexOf("video-js")!=-1){options=(options)?_V_.merge(options,{num:i}):options;videoJSPlayers[i]=new VideoJS(videoTag,options);}}}
VideoJS.browserSupportsVideo=function(){if(typeof VideoJS.videoSupport!="undefined")return VideoJS.videoSupport;return VideoJS.videoSupport=!!document.createElement('video').canPlayType;}
VideoJS.getFlashVersion=function(){if(typeof VideoJS.flashVersion!="undefined")return VideoJS.flashVersion;var version=0;if(typeof navigator.plugins!="undefined"&&typeof navigator.plugins["Shockwave Flash"]=="object"){desc=navigator.plugins["Shockwave Flash"].description;if(desc&&!(typeof navigator.mimeTypes!="undefined"&&navigator.mimeTypes["application/x-shockwave-flash"]&&!navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)){version=parseInt(desc.match(/^.*\s+([^\s]+)\.[^\s]+\s+[^\s]+$/)[1]);}}else if(typeof window.ActiveXObject!="undefined"){try{var testObject=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");if(testObject){version=parseInt(testObject.GetVariable("$version").match(/^[^\s]+\s(\d+)/)[1]);}}
catch(e){}}
return VideoJS.flashVersion=version;}
VideoJS.isIE=function(){return!+"\v1";}
VideoJS.isIpad=function(){return navigator.userAgent.match(/iPad/i)!=null;}
Function.prototype.context=function(obj){var method=this
temp=function(){return method.apply(obj,arguments)}
return temp}

// This sets up the proper header for rails to understand the request type,
// and therefore properly respond to js requests (via respond_to block, for example)
$j.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

// Patch for IE to use indexOf
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
   for(var i=0; i<this.length; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  }
}

replace_id = function(s){
  //console.log(s);
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}
$j(document).ready(function(){
  // UJS authenticity token fix: add the authenticy_token parameter
  // expected by any Rails POST request.
  $j(document).ajaxSend(function(event, request, settings) {
    // do nothing if this is a GET request. Rails doesn't need
    // the authenticity token, and IE converts the request method
    // to POST, just because - with love from redmond.
    if (settings.type == 'GET') return;
    if (typeof(AUTH_TOKEN) == "undefined") return;
    settings.data = settings.data || "";
    settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  });
  $j(".sort").sortable({
      axis: 'y',
      dropOnEmpty:false,
      handle:   '.handle',
      cursor:   'move',
      items:    'li',
      opacity:  0.4,
      scroll:   true,
      update:   function(event, ui){
        $j.ajax({
          type: 'post',
          data: $j(this).sortable('serialize'),
          dataType: 'script',
          success: function(){
            $j(".sort").effect('highlight');
          },
          url: $j(this).attr("rel")
        })
      }
    });
  $j("#formtabs").tabify({targetClass:"form", tabClass:"tabs", headingSelector:".heading h1"});
  $j("#listtabs").tabify({targetClass:"list", tabClass:"course-tabs", headingSelector:"h2"});
  //$j("form, form:not(#test-form)").preventDoubleSubmit();
  $j(".append_nested_item").click( function() {
      var template = eval($j(this).attr("href").replace(/.*#/, ''));
      template = replace_id(template);
      template_object = $j(template);
      if($j($j(this).attr("rel")+" > li:last").hasClass("cycle-even")){
        template_object.removeClass("cycle-even");
        template_object.addClass("cycle-odd");
      }else{
        template_object.removeClass("cycle-odd");
        template_object.addClass("cycle-even");
      }
      //$j($j(this).attr("rel")).prepend(template).hide().slideDown('slow');
      template_object.appendTo($j(this).attr("rel")).hide().slideDown('slow');
      return false;
      
    });
  $j(".prepend_nested_item").click( function() {
      var template = eval($j(this).attr("href").replace(/.*#/, ''));
      //console.log(template);
      template = replace_id(template);
      template_object = $j(template);
      if($j($j(this).attr("rel")+" > li:first").hasClass("cycle-even")){
        template_object.removeClass("cycle-even");
        template_object.addClass("cycle-odd");
      }else{
        template_object.removeClass("cycle-odd");
        template_object.addClass("cycle-even");
      }
      //$j($j(this).attr("rel")).prepend(template).hide().slideDown('slow');
      template_object.prependTo($j(this).attr("rel")).hide().slideDown('slow');
      return false;
    });
  $j("#notice, #error").flasher();
  if($j("#user_roles_input_3 input[type='checkbox']:checked").attr('checked')){
    $j("#required-student").show();
  }else{
    $j("#required-student").hide();
  }
  $j("#user_roles_input_3 label").click(function(){
    if($j("#user_roles_input_3 input[type='checkbox']:checked").attr('checked')){
      $j("#required-student").slideDown();
    }else{
      $j("#required-student").slideUp();
    }
  });
  
  $j(".course-library dt").each(function(){
    $j(this).toggleClass("collapsed")
    $j(this).click(function(){
      $j(this).next("dd").slideToggle('slow');
      $j(this).toggleClass("collapsed")
    });
  });
  $j(".course-library dd").each(function(){
    $j(this).hide();
  });
  
  $j("#test-form").validate({
    errorClass: "error",
    highlight: function(element, errorClass){
          $j(element).parent().parent().parent().parent().addClass(errorClass);
        },
    invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
          var message = errors == 1
            ? 'There is a problem! You missed 1 question. It has been highlighted in red.'
            : 'There is a problem! You missed ' + errors + ' questions. They have been highlighted in red.';
          $j("#notice").remove();
          $j("#error").remove();
          $j("body").prepend("<div id='error'><p>"+message+"</p></div>");
          $j('html, body').scrollTop(0);
          $j(':submit', form).click(function() {return true;});
        }
      },
    errorPlacement: function(error, element) {
        
      },
    submitHandler: function(form){
      $j(':submit', form).click(function() {return false;});
      form.submit();
      }
  });
  
  $j(window).load(function(){
    VideoJS.setup();
    $j("form").fieldhighlighter();
    $j(':input:visible:enabled:first').focus();
  });
  $j("#definitions").definition_matching();
});