
// common.js

// share the $
var $j = jQuery;
// active4D will interprelate $j as a local var.
// eventually switch all jquery calls to this name
var j$ = jQuery;
jQuery.noConflict();

/* Manage the conditional topic logic  */

function updateConditionalTopics() {
	// process any conditional hide / show logic
	j$('input:radio, input:checkbox').each(function(){executeConditionalLogic(this);});
}

function executeConditionalLogic(theObject) {
	//alert(theObject.name);
	var GroupNameArray = new Array();
	function addToArray(s) {
		// break string s into an array and append it to GroupNameArray array
		/*
			the conditional question class names use "^" as a part delimiter
			array element 0 is just the preample part of the class name and is discarded.
			elements 1 is the Group Name, and element 2 is the action, either hide or show.
		*/
		if((s) && (s!= '')) {
			//alert('s string = ' + s  + ' Length = ' + s.length);
			var myArray = new Array();
			myArray = s.split("^");
			// add the second and 3rd elements to the final array
			var i;
			for(i = 1; i < myArray.length; i++) {
				s = myArray[i];
				//alert(s+" Added to array")
				if((s) && (s!= '')) {
					GroupNameArray.push(s);
				}
			}
		}
	}
	function getGroupNameArray(myObject) {
		/*
			Load up the array GroupNameArray with the data gleaned from
			the special class names added to all checkbox and radio controls
			The class names are formated as "onSelectAction^<Conditional Group Name>^<hide | show>"
			and "onDeSelectAction^<Conditional Group Name>^<hide | show>".
			
			If the conditional group name is not empty, the data will be used to manage the visibilty of the
			questions that are part of that class. 
		*/
		GroupNameArray.length = 0; //clear the array before we start
		//var s = $.trim(myObject.className).match(/onSelectAction\S*/);
		var s = (myObject.className).match(/onSelectAction\S*/);
		if((s) && (s.length > 0)) {
			//alert('Matched class 1 = ' + s[0]);
			addToArray(s[0]);
		}
		//var s = $.trim(myObject.className).match(/onDeSelectAction\S*/);
		var s = (myObject.className).match(/onDeSelectAction\S*/);
		if((s) && (s.length > 0)) {
			//alert('Matched class 2 = ' + s[0]);
			addToArray(s[0]);
		}
	}

	getGroupNameArray(theObject); // GroupNameArray may now hold values
	if(GroupNameArray.length >3) {
		conditionalChange(theObject, GroupNameArray[0], GroupNameArray[1], GroupNameArray[2], GroupNameArray[3])
	}
	
} // function executeConditionalLogic

function conditionalChange(theObject, selectGroup, selectAction, deselectGroup, deselectAction) {
	function clearQuestion (theClass){
		// Clear all the inputs of the questions we are about to hide
		// 4D will handle deleting any data recorded for these questions
		/* don't want to do this now?...
		j$(theClass+" input:radio").removeAttr('checked');
		j$(theClass+" input:checkbox").removeAttr('checked');
		j$(theClass+" input:text").val('');
		j$(theClass+" textarea").val('');
		*/
	}
	var newState = theObject.checked;

	if(newState){ // The control has just been checked
		var theClass = '.'+selectGroup;
		//alert("Checked: "+ theClass);
		// option is checked
		if(selectAction =="Show"){
			j$(theClass).show();
			//alert("onSelect Show: "+ theClass);
			}
		else { 
			// clear the controls and then hide
			clearQuestion(theClass);
			//alert("onSelect Hide: "+ theClass);
			j$(theClass).hide();
			}
	}
	else { // Control has been un-checked
		var theClass = '.'+deselectGroup;
		//alert("Un-Checked: "+ theClass + " deselect action: " + deselectAction);
		// option is un-checked
		if(deselectAction == "Show"){
			j$(theClass).show();
			//alert("onDeselect Show: "+ theClass);
			}
		else {
			clearQuestion(theClass);
			//alert("onDeselect hide: "+ theClass);
			j$(theClass).hide();
			}
	}
}

/* End of Conditional logic manager */

// hide the old image buttons and replace them with customizable links and spans
j$(function(){
    j$('.imageButton').hide();
	j$('.jsButton').show();
	})

// Manage inpput form Security quesitons
function setSecure(which) { j$(which).hide();}

// used with buttons above. Submit the form that encloses the link
function submitEnclosingForm(obj) {
    // Ex: submitEnclosingForm(this)
	var node = obj.parentNode;
          while (node.tagName !='FORM' && node !=null && node.tagName!='HTML'){
           node = node.parentNode;
          }
         if (node.tagName == 'HTML') {
			// no from found
			alert('No form found in function submitEnclosingForm');
         } 
		else {
			node.submit();
		}
 }
 
// preload the button images
var busyImage = new Image();
busyImage.src = "/images/busy.gif";
var saveImage = new Image();
saveImage.src = "/images/buttons/save-disabled.gif";

function busy(ObjectID,isBusy){
	if($(ObjectID)){
		if(isBusy){
			$(ObjectID).innerHTML='<img style="height:16px;width:16px" src="/images/busy.gif" alt="busy"/>';
		} else {
			$(ObjectID).innerHTML= '';
		}
	}
}

function cleanWordEncoding(obj) {
	/*
		Based on code from jonathan Hedley as cleanWordClipboard : 
			http://jonathanhedley.com/articles/2008/03/convert-microsoft-word-to-plain-text
			
		Renamed and modifed to act directly on the reference to the object passed in.
		bl - 7/31/2008
	*/
	var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 63743); // dec codes from char at
	var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...", "(tm)", "apple");  
	
	var output = obj.value;
   // debug for new codes
   //  for (i = 0; i < output.length; i++)  alert("'" + output.charAt(i) + "': " + output.charCodeAt(i));

    for (i = 0; i < swapCodes.length; i++) {
        var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
        output = output.replace(swapper, swapStrings[i]);
    }

	obj.value = output;
}


// Hide or show an object
function displayElement(objectID,showMe) {
	if(showMe){
		$(objectID).style.display = 'block';
	}
	else{
		$(objectID).style.display = 'none';
	}
}

// Handle the insertion and removal of Regions in select lists
// Clicking on one list inserts element in the other. 
// Clicking the element in the receiving list removes it from that list

function insertOption(fromSelectObj,toSelect,maxOptions,maxResionText)
{
	if (!maxOptions) var maxOptions = 0;
	if ((!maxResionText) || (maxResionText =="")) var maxResionText = "Limit Reached";
	var x=document.getElementById(toSelect);
	var y=document.createElement('option');
	y.text=fromSelectObj.options[fromSelectObj.selectedIndex].text;
	y.value=fromSelectObj.options[fromSelectObj.selectedIndex].value;
	var inList = false;
	var optValue = y.value;
	for (i=0;i<x.length;i++)
   {
		if (x.options[i].value == optValue) {
			inList = true;
			break;
		}
	}
	
	// test limit
	if ((maxOptions == 0) || (x.length < maxOptions )) {
		if (!inList)
		{
	 	  try
	 	    {
	 	    x.add(y,null); // standards compliant
	 	    }
	 	  catch(ex)
	 	    {
	 	    x.add(y); // IE only
			} //catch
 	    } // not in list
	} // within limit
	else if (!inList) {
		alert(maxResionText);
	} // exceeded limit
} // insertOption

function deleteOption(selectObj)
{
  var x=selectObj;
  x.remove(x.selectedIndex);
}

function selectAllOptions(selectID) {
	// Select All the options in the select object
	var x = $(selectID);
	for (i=0;i<x.length;i++)
	{
		x.options[i].selected = true;
	}
}

// Pause script execution for a bit
function executeLater(scriptToRun,pauseTime) {
	// pass pauseTime as seconds
	if(!pauseTime) var pauseTime = 2;
	if(!scriptToRun) var scriptToRun = "";
	pauseTime = pauseTime * 1000; // convert to miliseconds
	var pauseTimer = setTimeout(scriptToRun,pauseTime);
}


// Code to determine the Mouse postition and display a popup div
// Used to display preview of sample images.

<!-- //Copyright 2006,2007 Bontrager Connection, LLC
// http://bontragerconnection.com/ and http://willmaster.com/
// Version: July 28, 2007
//http://www.willmaster.com/blog/css/Floating_Layer_At_Cursor_Position.html
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
if(self.pageYOffset) {
	rX = self.pageXOffset;
	rY = self.pageYOffset;
	}
else if(document.documentElement && document.documentElement.scrollTop) {
	rX = document.documentElement.scrollLeft;
	rY = document.documentElement.scrollTop;
	}
else if(document.body) {
	rX = document.body.scrollLeft;
	rY = document.body.scrollTop;
	}
if(document.all) {
	cX += rX; 
	cY += rY;
	}
d.style.left = (cX+6) + "px";
d.style.top = (cY+0) + "px";
}
var contentTimer;
function HideContent(d) {
if(d.length < 1) { return; }
if(!$(d)) {return;}
contentTimer = setTimeout('$("'+d+'").style.display = "none"',1000);
}

function KeepContent(d) {
if(d.length < 1) { return; }
clearTimeout(contentTimer);
}

//function ShowContent(d) {
function ShowContent(d,loc,url) {
if(d.length < 1) { return; }
clearTimeout(contentTimer);
var dd = $(d);
//AssignPosition(dd);
var loc; // object used to set the popup location
var coords = [0, 0];
coords = findPos($(loc));
dd.style.display = "block";
dd.style.position = "absolute";
dd.style.left = (coords[0]+24) + "px";
dd.style.top = (coords[1]+6) + "px";
busy(d,true);
setTimeout('ajaxRequest(\''+d+'\',\''+url+'\',\'\',\'\',true,true)',0);
}

// get the position of an object
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var wimpyUserAgent = navigator.appName.indexOf("Microsoft");
var wimpyButtonIDs = wimpyButtonIDs || Array();
function wimpyButtonStopOthers(myid_in){
	for(i=0; i<wimpyButtonIDs.length; i++){
		if(wimpyButtonIDs[i] != myid_in){
			if (wimpyUserAgent != -1) {
				window[wimpyButtonIDs[i]].js_wimpy_pause();
			} else {
				document[wimpyButtonIDs[i]].js_wimpy_pause();
			}
		}
	}
}
// 10/23/08 - BL - renamed function and added parm
//was: function writeWimpyButton(theFile, wimpyWidth, wimpyHeight, wimpyConfigs, backgroundColor){
function writeWimpyButton4(theFile, wimpyWidth, wimpyHeight, wimpyConfigs, backgroundColor, regCode){
	var wimpyReg = (regCode == null) ? "" : regCode; // get regCode from parm now
	var defaultWidth = 20;
	var defaultHeight = 20;
	var defaultConfigs = "";
	var baseURL = "";
	var wimpySwf = "/assets/wimpy_button4.swf";
	var wimpyWidth = (wimpyWidth == null) ? defaultWidth : wimpyWidth;
	var wimpyHeight = (wimpyHeight == null) ? defaultHeight : wimpyHeight;
	var wimpyConfigs = (wimpyConfigs == null) ? defaultConfigs : wimpyConfigs;
	var backgroundColor = (backgroundColor == null) ? false : backgroundColor;
	var myid = "wimpybutton"+Math.round((Math.random()*1000)+1);
	wimpyButtonIDs[wimpyButtonIDs.length] = myid;
	var flashCode = "";
	var newlineChar = "\n";
	var backgroundColor = (backgroundColor == null) ? false : backgroundColor;
	if(typeof(backgroundColor) == "string"){
		var Astring = backgroundColor.split("");
		if(Astring[0] == "#"){
			Astring.shift();
			backgroundColor = Astring.join("");
		}
	}
	if(backgroundColor == false){
		tptParam = '<param name="wmode" value="transparent" />'+newlineChar;
		tptEmbed = ' wmode="transparent"';
	} else {
		tptParam = '<param name="bgcolor" value="#'+backgroundColor+'" />'+newlineChar;
		tptEmbed = ' bgcolor="#'+backgroundColor+'"';
	}
	flashCode += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+wimpyWidth+'" height="'+wimpyHeight+'" id="'+myid+'">'+newlineChar;
	flashCode += '<param name="movie" value="'+wimpySwf+'" />'+newlineChar;
	flashCode += '<param name="loop" value="false" />'+newlineChar;
	flashCode += '<param name="menu" value="false" />'+newlineChar;
	flashCode += '<param name="quality" value="high" />'+newlineChar;
	flashCode += '<param name="wmode" value="transparent" />'+newlineChar;
	flashCode += '<param name="flashvars" value="theFile='+baseURL+theFile+wimpyConfigs+'&wimpyReg='+wimpyReg+'&myid='+myid+'" />'+newlineChar;
	flashCode += '<embed src="'+wimpySwf+'" width="'+wimpyWidth+'" height="'+wimpyHeight+'" flashvars="theFile='+baseURL+theFile+wimpyConfigs+'&wimpyReg='+wimpyReg+'&myid='+myid+'"'+tptEmbed+' loop="false" menu="false" quality="high" name="'+myid+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>'+newlineChar;
	//document.write('<br>'+myid+'<br><textarea name="textarea" cols="40" rows="3">'+flashCode+'</textarea><br>')+newlineChar;
	document.write(flashCode);
}


/*
Ajax using the prototype.js routines
*/
function ajaxRequest(ObjectID,url,params,FormID ,noScroll ,noEval){
	// Ex: ajaxRequest('descriptionDisplay',$XFA_onSubmit,'mode=cancel','DescForm')
	var formParams = "";
	var pars = "";
	
	if(params){
		pars = params;
	}
	
	if(FormID){
		formParams=Form.serialize(FormID);
		pars += "&" +formParams;
	}
	
	// Sending a post with no params doesn't seem to be allowed
	var requestMethod = 'post';
	if (pars == "") {
		requestMethod = 'get';
	}
	
	var myAjax = new Ajax.Request(
		url, 
		{
			method: requestMethod, 
			parameters: pars, 
			onComplete: ajaxResponse
		});
		
	function ajaxResponse(originalRequest)
	{
		var response=originalRequest.responseText;
		var theStatus = originalRequest.status;
		//alert('Status ->'+theStatus);
		//alert('Object ->'+ObjectID);
		//alert('Object Exitsts ->'+$(ObjectID));
		if(theStatus == 200){
			var s;
			s = response.toUpperCase();
			s = s.substr(0,20); //the redirect is close to front
			var redirectStart = s.search('REDIRECT');
			if(redirectStart != -1){
				// This is a real kludge. Need to  find a more dependable way to do this
				// User is being redirected to a new location, most likely the login page
				if (window == top) {
					window.location = response.substr(redirectStart+8);
				} 
				else {
					// We are in side a frame, pop up to the top
					top.location.href =response.substr(redirectStart+8);
				}
			} else if($(ObjectID)){
					// a target object was specified, otherwise, there is nothing to do
					var obj = $(ObjectID)
					obj.innerHTML=response;
					if ( ! (noEval)){
						response.evalScripts(); //evaluate any scripts in the return
					}
					// When updating fields that require validation, the div id 'completedContain' gets refreshed
					// we don't want to  scroll to completedContain
					if ( ! (noScroll)){
						obj.scrollIntoView(true);
						window.scrollBy(0,-160);
					}

			}
		} else {
			// We were sent something unusual, display in own window
			window.location = response;
		}
	}
}

// Update the Profile incomplete warning
function profileComplete() {
	//find out if the target object exists
	if($('completedContain')){
		ajaxRequest('completedContain','/index.a4d','action=profile.testComplete&ajaxResponse=true','',true,false);
	}
}

// this replaces the target="_blank" deprication issue
// call as: <a href="http://www.foo.com" rel="external">
function externalLinks() { 
	if (!document.getElementsByTagName) return; 
	var anchors = document.getElementsByTagName("a"); 
	for (var i=0; i<anchors.length; i++) { 
		var anchor = anchors[i]; 
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; 
	} 
}
window.onload = externalLinks;


function getOffset(objectID,topORleft) {
	if($(objectID)) {
		alert($(objectID))
		var obj  = $(objectID);
		// thanks to www.quirksmode.org for scroll detection
		var topOffset = 0;
		var leftOffset = 0;
			if (document.documentElement && document.documentElement.scrollTop)
			{	//IE 6
				topOffset = document.documentElement.scrollTop;
				leftOffset = document.documentElement.scrollLeft;
			}
			else if (document.body)
			{	//IE 5
				  topOffset = document.body.scrollTop;
				  leftOffset = document.body.scrollLeft;
			}
			else 
			{
				topOffset = window.pageYOffset;
				leftOffset = window.pageXOffset;
			}
			if(topORleft = 'left') 
			{
				return leftOffset;
			} 
			else 
			{
				return topOffset;
			}
			
	} else { return 0; }
}



// Paint the screen with a translucent div to simulate a modal dialog
function setModal(objectID,modalState) {
	var objectID = "#"+objectID;
	var docHeight = j$(document).height()+"px";
	var docWidth = j$(document).width()+"px";
	j$(objectID).css("height",docHeight).css("width",docWidth);
	if(modalState) {
		// display the div
		j$(objectID).show();
	}
	else {
		//hide the div
		j$(objectID).hide();
	}
}

// Open a new window to view special content

function OpenViewer(openparams,theHeight,theWidth, theWindowName){
	if (theHeight == null) {
		var theHeight = 400;  //Default height
	}
	if (theWidth == null) {
		var theWidth = 750;  //Default width
	}
	if (theWindowName == null) {
		var theWindowName = 'viewer';  //Default window name
	}
	
	theNewWindow=window.open(openparams,theWindowName,"location=yes,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,height=" + theHeight + ",width=" + theWidth)
	theNewWindow.focus();
}

function ShowViewer(openparams){
	OpenViewer(openparams,"500","750")
}

function helpViewer(openparams){
	OpenViewer(openparams,"500","500",'Help');
}

function VideoViewer(openparams){
	OpenViewer(openparams,"650","670");
}

// Show the Review Window
function readreview(entid){
var openparams = "/BrowseW_GetReview?id="+entid;
OpenViewer(openparams,"300","300");
}

function ShowSampleSearch(openparams){
OpenViewer(openparams,"500","800");
}

function ShowSamplePage(openparams){
OpenViewer(openparams,"700","800");
}


// Handle the user clicks in the Regions Multi select objects
function OptionsToList(){
	var regionsListTemp = "";
	var OptionTemp = "";
	for(i=0; i< document.SearchForm.Regions.options.length; i++){
		if(document.SearchForm.Regions.options[i].selected){
		OptionTemp=document.SearchForm.Regions.options[i].text.replace(/\W{3,4}/,"");
			if(regionsListTemp!=""){
			regionsListTemp = regionsListTemp + ", " + OptionTemp;
			}// add to list
			else
			{
				regionsListTemp = OptionTemp;
			} //  first region
		} // if selected
	} //for
	
	if(regionsListTemp==""){ 
		regionsListTemp = "- All Regions -";
	} // no regions selected

	document.SearchForm.RegionList.value=regionsListTemp.replace(/ \(\d+\)/g,"");
}//ListOptions


// check the radio button associated with most recently change member name field
function checktherightone(theone, thetext){
	if(document.getElementById(thetext).value != ""){
	document.getElementById(theone).checked=true
	}
}

// The MacroMedia swap image routines
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

	function scrollTop() {
      	window.scrollTo(0,0);
      }
      
      function checkboxes(checkem,checkboxname){
	      var elements=checkboxname
	      if(elements.length){
		      if(checkem=="all"){
			      for (i=0;i<elements.length;++i){
				      if(elements[i].disabled){
				      }else{
					      elements[i].checked=true
				      }
			      }
		      }else if(checkem=="none"){
			      for (i=0;i<elements.length;++i){
				      if(elements[i].disabled){
				      }else{
					      elements[i].checked=false
				      }
			      }
		      }
	      }else{
		   if(checkem=="all"){
				      if(elements.disabled){
				      }else{
					      elements.checked=true
				      }
		      }else if(checkem=="none"){
				      if(elements.disabled){
				      }else{
					      elements.checked=false
				      }
		      }   
	      }
      }
      function uncheck(uncheck){
	      //$(uncheck).checked=false
			// Avoid conflict between libraries
		if(document.getElementById(uncheck)) {
	      document.getElementById(uncheck).checked=false
		}
      }

// Audio player using native <audio> if available else flash
function audioPlayer(audioFile,resourceID,autoplay,compact) {
/*
	assumes the following markup exists:
	<span id="audio12345" class="audio_player" >
		<span id="playtoggle12345" class="audio_playtoggle"></span>
			<span id="nativeControls12345">
				<span id="gutter12345" class="audio_gutter">
					<span id="loading12345" class="audio_loading"></span>
					<span id="handle12345" class="audio_handle ui-slider-handle"></span>
				</span>
			</span>
		<span id="timeleft12345" class="audio_timeleft"></span>
		<audio id="clip12345" type="audio/mpeg"></audio>
	</span>
	"1234" is the resource ID to make all ids unique when multiple players are included in one page
*/
	var manualSeek = false;
	var loaded = false;
	var flashpath = "/assets/flash/player_mp3_maxi.swf";
	var configpath = "/assets/flash/";
	if(!audioFile) {var audioFile = "";}
	if(!resourceID) {var resourceID = "";}
	if(!compact) {compact = 0;}else{compact = 1;}
	if(!autoplay) {autoplay = 0;}else{autoplay = 1;}
	
	var a = document.createElement('audio');
	if(!!(a.canPlayType && a.canPlayType('audio/mpeg').replace(/no/, ''))) {
		// Can play native
		j$("#clip"+resourceID).attr('src', audioFile);
		if(compact) {
			// Remove the un-needed elements for the compact player
			j$("#nativeControls"+resourceID+", #timeleft"+resourceID).hide();
			j$("#audio"+resourceID).addClass("compactPlayer");
		}
	
		 // add functionality to player
		var audio = j$('#clip'+resourceID).get(0);
		//audio.src = audioFile;
		//audio.load();
		//audio.play();
		var loadingIndicator = j$('#loading'+resourceID);
		var positionIndicator = j$('#handle'+resourceID);
		var timeleft = j$('#timeleft'+resourceID);
   
		if ((audio.buffered != undefined) && (audio.buffered.length != 0) && (!compact)) {
		  j$(audio).bind('progress', function() {
		    var loaded = parseInt(((audio.buffered.end(0) / audio.duration) * 100), 10);
		    loadingIndicator.css({width: loaded + '%'});
		  });
		}
		else {
		  loadingIndicator.remove();
		}

		j$(audio).bind('timeupdate', function() {
		  var rem = parseInt(audio.duration - audio.currentTime, 10),
		  pos = (audio.currentTime / audio.duration) * 95,
		  mins = Math.floor(rem/60,10),
		  secs = rem - mins*60;

		  timeleft.text('-' + mins + ':' + (secs > 9 ? secs : '0' + secs));
		  //timeleft.text(audio.currentTime + '/' +  audio.duration);
		  if (!manualSeek) { 
				positionIndicator.css({left: pos + '%'}); 
			}

		  if ((!loaded) && (!compact)) {
		    loaded = true;
		    j$('#gutter'+resourceID).slider({
		      value: 0,
		      step: 0.01,
		      orientation: "horizontal",
		      min: 0,
		      max: audio.duration,
		      slide: function() {  
		        manualSeek = true;
		      },
		      stop:function(e,ui) {
		        manualSeek = false;         
		        audio.currentTime = ui.value;
		      }
		    });
		  }
		});

		j$(audio).bind('play',function() {
		  j$("#playtoggle"+resourceID).addClass('playing');   
		}).bind('pause ended', function() {
		  j$("#playtoggle"+resourceID).removeClass('playing');    
		});   
   
		j$("#playtoggle"+resourceID).click(function() {     
		  if (audio.paused) { 
			audio.play(); 
		  } 
		  else { audio.pause();
		    manualSeek = false;         
		 }

		});
		// start the audio playing
		if(autoplay) {audio.play()};

	} // plays native
	else if (DetectFlashVer(0, 0, 0)) {
		// use flash
		//j$('#nativeAudio').text("");
		var audioOptions = "";
		
		// insert the player object into the page now so Safari or chrome need never see it
		if(compact){
			j$("#audio"+resourceID).addClass("compactPlayer")
			audioOptions = '&amp;config='+configpath+'MP3playerCompactSettings.txt';
		}
		else {
			audioOptions = '&amp;config='+configpath+'MP3playerSettings.txt';
		}
	
		audioOptions += '&amp;autoplay='+autoplay;
	
		audio = '<object  class="audio_flash_player" id="flashPlayer'+resourceID+'" type="application/x-shockwave-flash" data="'+flashpath+'"><param name="movie" value="'+flashpath+'" /><param name="FlashVars" value="mp3='+audioFile+audioOptions+'" />';
		audio += '</object>';
		j$('#audio'+resourceID).removeClass("audio_player").html(audio);
		if(compact){
			j$("#audio"+resourceID).addClass("compactPlayer")
			j$("#flashPlayer"+resourceID).addClass("compactPlayer");
		}
		
	} // use flash
	else {
		// no suitible player, offer to download
		var noAudioOut = '<p>Sorry, we could not find a suitable player on your device.</p>';
		noAudioOut += '<p>You may wish to try downloading the audio sample by clicking <a href="'+audioFile+'">here</a>.';
		// insert the error into the div that holds all the audio content
		j$('#audio'+resourceID).addClass("audioNone").html(noAudioOut);
	}
} // audioPlayer func

/* 
 * flowplayer.js 3.2.4. The Flowplayer API
 * 
 * Copyright 2009 Flowplayer Oy
 * 
 * This file is part of Flowplayer.
 * Date: 2010-08-25 12:48:46 +0000 (Wed, 25 Aug 2010)
 * Revision: 551 
 */
(function(){function g(o){console.log("$f.fireEvent",[].slice.call(o))}function k(q){if(!q||typeof q!="object"){return q}var o=new q.constructor();for(var p in q){if(q.hasOwnProperty(p)){o[p]=k(q[p])}}return o}function m(t,q){if(!t){return}var o,p=0,r=t.length;if(r===undefined){for(o in t){if(q.call(t[o],o,t[o])===false){break}}}else{for(var s=t[0];p<r&&q.call(s,p,s)!==false;s=t[++p]){}}return t}function c(o){return document.getElementById(o)}function i(q,p,o){if(typeof p!="object"){return q}if(q&&p){m(p,function(r,s){if(!o||typeof s!="function"){q[r]=s}})}return q}function n(s){var q=s.indexOf(".");if(q!=-1){var p=s.slice(0,q)||"*";var o=s.slice(q+1,s.length);var r=[];m(document.getElementsByTagName(p),function(){if(this.className&&this.className.indexOf(o)!=-1){r.push(this)}});return r}}function f(o){o=o||window.event;if(o.preventDefault){o.stopPropagation();o.preventDefault()}else{o.returnValue=false;o.cancelBubble=true}return false}function j(q,o,p){q[o]=q[o]||[];q[o].push(p)}function e(){return"_"+(""+Math.random()).slice(2,10)}var h=function(t,r,s){var q=this,p={},u={};q.index=r;if(typeof t=="string"){t={url:t}}i(this,t,true);m(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var v="on"+this;if(v.indexOf("*")!=-1){v=v.slice(0,v.length-1);var w="onBefore"+v.slice(2);q[w]=function(x){j(u,w,x);return q}}q[v]=function(x){j(u,v,x);return q};if(r==-1){if(q[w]){s[w]=q[w]}if(q[v]){s[v]=q[v]}}});i(this,{onCuepoint:function(x,w){if(arguments.length==1){p.embedded=[null,x];return q}if(typeof x=="number"){x=[x]}var v=e();p[v]=[x,w];if(s.isLoaded()){s._api().fp_addCuepoints(x,r,v)}return q},update:function(w){i(q,w);if(s.isLoaded()){s._api().fp_updateClip(w,r)}var v=s.getConfig();var x=(r==-1)?v.clip:v.playlist[r];i(x,w,true)},_fireEvent:function(v,y,w,A){if(v=="onLoad"){m(p,function(B,C){if(C[0]){s._api().fp_addCuepoints(C[0],r,B)}});return false}A=A||q;if(v=="onCuepoint"){var z=p[y];if(z){return z[1].call(s,A,w)}}if(y&&"onBeforeBegin,onMetaData,onStart,onUpdate,onResume".indexOf(v)!=-1){i(A,y);if(y.metaData){if(!A.duration){A.duration=y.metaData.duration}else{A.fullDuration=y.metaData.duration}}}var x=true;m(u[v],function(){x=this.call(s,A,y,w)});return x}});if(t.onCuepoint){var o=t.onCuepoint;q.onCuepoint.apply(q,typeof o=="function"?[o]:o);delete t.onCuepoint}m(t,function(v,w){if(typeof w=="function"){j(u,v,w);delete t[v]}});if(r==-1){s.onCuepoint=this.onCuepoint}};var l=function(p,r,q,t){var o=this,s={},u=false;if(t){i(s,t)}m(r,function(v,w){if(typeof w=="function"){s[v]=w;delete r[v]}});i(this,{animate:function(y,z,x){if(!y){return o}if(typeof z=="function"){x=z;z=500}if(typeof y=="string"){var w=y;y={};y[w]=z;z=500}if(x){var v=e();s[v]=x}if(z===undefined){z=500}r=q._api().fp_animate(p,y,z,v);return o},css:function(w,x){if(x!==undefined){var v={};v[w]=x;w=v}r=q._api().fp_css(p,w);i(o,r);return o},show:function(){this.display="block";q._api().fp_showPlugin(p);return o},hide:function(){this.display="none";q._api().fp_hidePlugin(p);return o},toggle:function(){this.display=q._api().fp_togglePlugin(p);return o},fadeTo:function(y,x,w){if(typeof x=="function"){w=x;x=500}if(w){var v=e();s[v]=w}this.display=q._api().fp_fadeTo(p,y,x,v);this.opacity=y;return o},fadeIn:function(w,v){return o.fadeTo(1,w,v)},fadeOut:function(w,v){return o.fadeTo(0,w,v)},getName:function(){return p},getPlayer:function(){return q},_fireEvent:function(w,v,x){if(w=="onUpdate"){var z=q._api().fp_getPlugin(p);if(!z){return}i(o,z);delete o.methods;if(!u){m(z.methods,function(){var B=""+this;o[B]=function(){var C=[].slice.call(arguments);var D=q._api().fp_invoke(p,B,C);return D==="undefined"||D===undefined?o:D}});u=true}}var A=s[w];if(A){var y=A.apply(o,v);if(w.slice(0,1)=="_"){delete s[w]}return y}return o}})};function b(q,G,t){var w=this,v=null,D=false,u,s,F=[],y={},x={},E,r,p,C,o,A;i(w,{id:function(){return E},isLoaded:function(){return(v!==null&&v.fp_play!==undefined&&!D)},getParent:function(){return q},hide:function(H){if(H){q.style.height="0px"}if(w.isLoaded()){v.style.height="0px"}return w},show:function(){q.style.height=A+"px";if(w.isLoaded()){v.style.height=o+"px"}return w},isHidden:function(){return w.isLoaded()&&parseInt(v.style.height,10)===0},load:function(J){if(!w.isLoaded()&&w._fireEvent("onBeforeLoad")!==false){var H=function(){u=q.innerHTML;if(u&&!flashembed.isSupported(G.version)){q.innerHTML=""}if(J){J.cached=true;j(x,"onLoad",J)}flashembed(q,G,{config:t})};var I=0;m(a,function(){this.unload(function(K){if(++I==a.length){H()}})})}return w},unload:function(J){if(this.isFullscreen()&&/WebKit/i.test(navigator.userAgent)){if(J){J(false)}return w}if(u.replace(/\s/g,"")!==""){if(w._fireEvent("onBeforeUnload")===false){if(J){J(false)}return w}D=true;try{if(v){v.fp_close();w._fireEvent("onUnload")}}catch(H){}var I=function(){v=null;q.innerHTML=u;D=false;if(J){J(true)}};setTimeout(I,50)}else{if(J){J(false)}}return w},getClip:function(H){if(H===undefined){H=C}return F[H]},getCommonClip:function(){return s},getPlaylist:function(){return F},getPlugin:function(H){var J=y[H];if(!J&&w.isLoaded()){var I=w._api().fp_getPlugin(H);if(I){J=new l(H,I,w);y[H]=J}}return J},getScreen:function(){return w.getPlugin("screen")},getControls:function(){return w.getPlugin("controls")._fireEvent("onUpdate")},getLogo:function(){try{return w.getPlugin("logo")._fireEvent("onUpdate")}catch(H){}},getPlay:function(){return w.getPlugin("play")._fireEvent("onUpdate")},getConfig:function(H){return H?k(t):t},getFlashParams:function(){return G},loadPlugin:function(K,J,M,L){if(typeof M=="function"){L=M;M={}}var I=L?e():"_";w._api().fp_loadPlugin(K,J,M,I);var H={};H[I]=L;var N=new l(K,null,w,H);y[K]=N;return N},getState:function(){return w.isLoaded()?v.fp_getState():-1},play:function(I,H){var J=function(){if(I!==undefined){w._api().fp_play(I,H)}else{w._api().fp_play()}};if(w.isLoaded()){J()}else{if(D){setTimeout(function(){w.play(I,H)},50)}else{w.load(function(){J()})}}return w},getVersion:function(){var I="flowplayer.js 3.2.4";if(w.isLoaded()){var H=v.fp_getVersion();H.push(I);return H}return I},_api:function(){if(!w.isLoaded()){throw"Flowplayer "+w.id()+" not loaded when calling an API method"}return v},setClip:function(H){w.setPlaylist([H]);return w},getIndex:function(){return p},_swfHeight:function(){return v.clientHeight}});m(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,ClipAdd,Fullscreen*,FullscreenExit,Error,MouseOver,MouseOut").split(","),function(){var H="on"+this;if(H.indexOf("*")!=-1){H=H.slice(0,H.length-1);var I="onBefore"+H.slice(2);w[I]=function(J){j(x,I,J);return w}}w[H]=function(J){j(x,H,J);return w}});m(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,toggleFullscreen,reset,close,setPlaylist,addClip,playFeed,setKeyboardShortcutsEnabled,isKeyboardShortcutsEnabled").split(","),function(){var H=this;w[H]=function(J,I){if(!w.isLoaded()){return w}var K=null;if(J!==undefined&&I!==undefined){K=v["fp_"+H](J,I)}else{K=(J===undefined)?v["fp_"+H]():v["fp_"+H](J)}return K==="undefined"||K===undefined?w:K}});w._fireEvent=function(Q){if(typeof Q=="string"){Q=[Q]}var R=Q[0],O=Q[1],M=Q[2],L=Q[3],K=0;if(t.debug){g(Q)}if(!w.isLoaded()&&R=="onLoad"&&O=="player"){v=v||c(r);o=w._swfHeight();m(F,function(){this._fireEvent("onLoad")});m(y,function(S,T){T._fireEvent("onUpdate")});s._fireEvent("onLoad")}if(R=="onLoad"&&O!="player"){return}if(R=="onError"){if(typeof O=="string"||(typeof O=="number"&&typeof M=="number")){O=M;M=L}}if(R=="onContextMenu"){m(t.contextMenu[O],function(S,T){T.call(w)});return}if(R=="onPluginEvent"||R=="onBeforePluginEvent"){var H=O.name||O;var I=y[H];if(I){I._fireEvent("onUpdate",O);return I._fireEvent(M,Q.slice(3))}return}if(R=="onPlaylistReplace"){F=[];var N=0;m(O,function(){F.push(new h(this,N++,w))})}if(R=="onClipAdd"){if(O.isInStream){return}O=new h(O,M,w);F.splice(M,0,O);for(K=M+1;K<F.length;K++){F[K].index++}}var P=true;if(typeof O=="number"&&O<F.length){C=O;var J=F[O];if(J){P=J._fireEvent(R,M,L)}if(!J||P!==false){P=s._fireEvent(R,M,L,J)}}m(x[R],function(){P=this.call(w,O,M);if(this.cached){x[R].splice(K,1)}if(P===false){return false}K++});return P};function B(){if($f(q)){$f(q).getParent().innerHTML="";p=$f(q).getIndex();a[p]=w}else{a.push(w);p=a.length-1}A=parseInt(q.style.height,10)||q.clientHeight;E=q.id||"fp"+e();r=G.id||E+"_api";G.id=r;t.playerId=E;if(typeof t=="string"){t={clip:{url:t}}}if(typeof t.clip=="string"){t.clip={url:t.clip}}t.clip=t.clip||{};if(q.getAttribute("href",2)&&!t.clip.url){t.clip.url=q.getAttribute("href",2)}s=new h(t.clip,-1,w);t.playlist=t.playlist||[t.clip];var I=0;m(t.playlist,function(){var K=this;if(typeof K=="object"&&K.length){K={url:""+K}}m(t.clip,function(L,M){if(M!==undefined&&K[L]===undefined&&typeof M!="function"){K[L]=M}});t.playlist[I]=K;K=new h(K,I,w);F.push(K);I++});m(t,function(K,L){if(typeof L=="function"){if(s[K]){s[K](L)}else{j(x,K,L)}delete t[K]}});m(t.plugins,function(K,L){if(L){y[K]=new l(K,L,w)}});if(!t.plugins||t.plugins.controls===undefined){y.controls=new l("controls",null,w)}y.canvas=new l("canvas",null,w);u=q.innerHTML;function J(L){var K=w.hasiPadSupport&&w.hasiPadSupport();if(/iPad|iPhone|iPod/i.test(navigator.userAgent)&&!/.flv$/i.test(F[0].url)&&!K){return true}if(!w.isLoaded()&&w._fireEvent("onBeforeClick")!==false){w.load()}return f(L)}function H(){if(u.replace(/\s/g,"")!==""){if(q.addEventListener){q.addEventListener("click",J,false)}else{if(q.attachEvent){q.attachEvent("onclick",J)}}}else{if(q.addEventListener){q.addEventListener("click",f,false)}w.load()}}setTimeout(H,0)}if(typeof q=="string"){var z=c(q);if(!z){throw"Flowplayer cannot access element: "+q}q=z;B()}else{B()}}var a=[];function d(o){this.length=o.length;this.each=function(p){m(o,p)};this.size=function(){return o.length}}window.flowplayer=window.$f=function(){var p=null;var o=arguments[0];if(!arguments.length){m(a,function(){if(this.isLoaded()){p=this;return false}});return p||a[0]}if(arguments.length==1){if(typeof o=="number"){return a[o]}else{if(o=="*"){return new d(a)}m(a,function(){if(this.id()==o.id||this.id()==o||this.getParent()==o){p=this;return false}});return p}}if(arguments.length>1){var t=arguments[1],q=(arguments.length==3)?arguments[2]:{};if(typeof t=="string"){t={src:t}}t=i({bgcolor:"#000000",version:[9,0],expressInstall:"http://static.flowplayer.org/swf/expressinstall.swf",cachebusting:true},t);if(typeof o=="string"){if(o.indexOf(".")!=-1){var s=[];m(n(o),function(){s.push(new b(this,k(t),k(q)))});return new d(s)}else{var r=c(o);return new b(r!==null?r:o,t,q)}}else{if(o){return new b(o,t,q)}}}return null};i(window.$f,{fireEvent:function(){var o=[].slice.call(arguments);var q=$f(o[0]);return q?q._fireEvent(o.slice(1)):null},addPlugin:function(o,p){b.prototype[o]=p;return $f},each:m,extend:i});if(typeof jQuery=="function"){jQuery.fn.flowplayer=function(q,p){if(!arguments.length||typeof arguments[0]=="number"){var o=[];this.each(function(){var r=$f(this);if(r){o.push(r)}});return arguments.length?o[arguments[0]]:new d(o)}return this.each(function(){$f(this,k(q),p?k(p):{})})}}})();(function(){var h=document.all,j="http://www.adobe.com/go/getflashplayer",c=typeof jQuery=="function",e=/(\d+)[^\d]+(\d+)[^\d]*(\d*)/,b={width:"100%",height:"100%",id:"_"+(""+Math.random()).slice(9),allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:[3,0],onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function i(m,l){if(l){for(var f in l){if(l.hasOwnProperty(f)){m[f]=l[f]}}}return m}function a(f,n){var m=[];for(var l in f){if(f.hasOwnProperty(l)){m[l]=n(f[l])}}return m}window.flashembed=function(f,m,l){if(typeof f=="string"){f=document.getElementById(f.replace("#",""))}if(!f){return}if(typeof m=="string"){m={src:m}}return new d(f,i(i({},b),m),l)};var g=i(window.flashembed,{conf:b,getVersion:function(){var m,f;try{f=navigator.plugins["Shockwave Flash"].description.slice(16)}catch(o){try{m=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");f=m&&m.GetVariable("$version")}catch(n){try{m=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");f=m&&m.GetVariable("$version")}catch(l){}}}f=e.exec(f);return f?[f[1],f[3]]:[0,0]},asString:function(l){if(l===null||l===undefined){return null}var f=typeof l;if(f=="object"&&l.push){f="array"}switch(f){case"string":l=l.replace(new RegExp('(["\\\\])',"g"),"\\$1");l=l.replace(/^\s?(\d+\.?\d+)%/,"$1pct");return'"'+l+'"';case"array":return"["+a(l,function(o){return g.asString(o)}).join(",")+"]";case"function":return'"function()"';case"object":var m=[];for(var n in l){if(l.hasOwnProperty(n)){m.push('"'+n+'":'+g.asString(l[n]))}}return"{"+m.join(",")+"}"}return String(l).replace(/\s/g," ").replace(/\'/g,'"')},getHTML:function(o,l){o=i({},o);var n='<object width="'+o.width+'" height="'+o.height+'" id="'+o.id+'" name="'+o.id+'"';if(o.cachebusting){o.src+=((o.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(o.w3c||!h){n+=' data="'+o.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(o.w3c||h){n+='<param name="movie" value="'+o.src+'" />'}o.width=o.height=o.id=o.w3c=o.src=null;o.onFail=o.version=o.expressInstall=null;for(var m in o){if(o[m]){n+='<param name="'+m+'" value="'+o[m]+'" />'}}var p="";if(l){for(var f in l){if(l[f]){var q=l[f];p+=f+"="+(/function|object/.test(typeof q)?g.asString(q):q)+"&"}}p=p.slice(0,-1);n+='<param name="flashvars" value=\''+p+"' />"}n+="</object>";return n},isSupported:function(f){return k[0]>f[0]||k[0]==f[0]&&k[1]>=f[1]}});var k=g.getVersion();function d(f,n,m){if(g.isSupported(n.version)){f.innerHTML=g.getHTML(n,m)}else{if(n.expressInstall&&g.isSupported([6,65])){f.innerHTML=g.getHTML(i(n,{src:n.expressInstall}),{MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title})}else{if(!f.innerHTML.replace(/\s/g,"")){f.innerHTML="<h2>Flash version "+n.version+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(f.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='"+j+"'>here</a></p>");if(f.tagName=="A"){f.onclick=function(){location.href=j}}}if(n.onFail){var l=n.onFail.call(this);if(typeof l=="string"){f.innerHTML=l}}}}if(h){window[n.id]=document.getElementById(n.id)}i(this,{getRoot:function(){return f},getOptions:function(){return n},getConf:function(){return m},getApi:function(){return f.firstChild}})}if(c){jQuery.tools=jQuery.tools||{version:"3.2.4"};jQuery.tools.flashembed={conf:b};jQuery.fn.flashembed=function(l,f){return this.each(function(){$(this).data("flashembed",flashembed(this,l,f))})}}})();

function flowplayerStandard(where,what,autoplay) {
	// insert the standard flowplayer flash object into where to play what
	// where is the id of element to contain the movie
	// what is the url of the movie to play
	flowplayer(where, "/assets/flash/flowplayer-3.2.5.swf", {clip: {	url: what ,autoPlay: autoplay },plugins: {controls: {	url: "/assets/flash/flowplayer.controls-3.2.3.swf",	opacity: 0.95,time: false,mute: false,fullscreen: true,tooltips: {buttons: true,fullscreen: "Enter fullscreen mode"	}}}});
}

function videoPlayer (where,what,autoplay,hasFlash,hasH264,hasYouTube,hasVimeo,hasOgg,hasQuickTime) {
	// where is the id of element to contain the movie
	// what is the url of the movie to play
	if(!autoplay){var autoplay = false};
	if(!hasFlash){var hasFlash = false};
	if(!hasH264){var hasH264 = false};
	if(!hasYouTube){var hasYouTube = false};
	if(!hasVimeo){var hasVimeo = false};
	if(!hasOgg){var hasOgg = false};
	if(!hasQuickTime){var hasQuickTime = false};
	
	/* Where is now only the file name without an extension
	    we will append a supported extension here, so the file name must exist as such
		Supported extensions are either .flv for flash or .mp4 for h.264 encoded video
		Remote video such as YouTube and Vimeo don't have an extension, of course
	*/
	// detect that browser can handle available video formats
	// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
	var clientPlaysFlash = DetectFlashVer(0, 0, 0);
	//var clientPlaysFlash = detectPlugin("Shockwave","Flash");
	var clientPlaysQuickTime = detectPlugin("QuickTime")
	//alert('PlaysFlash = '+clientPlaysFlash+' and hasFlash = '+hasFlash);
	var a = document.createElement('video');
	var clientPlaysH264 = (!!(a.canPlayType && a.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"').replace(/no/, '')));
	var clientPlaysOgg = (!!(a.canPlayType && a.canPlayType('video/ogg; codecs="theora, vorbis"').replace(/no/, '')));

	if(hasYouTube) {
		//alert("playing Youtube...")
		// iOS devices can play YouTube by some magic
		// insert the Youtube object
		j$('#'+where).html('<object class="videoBoxERC" ><param name="movie" value="http://www.youtube.com/v/'+what+'?fs=1&amp;hl=en_US&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="never"></param><embed src="http://www.youtube.com/v/'+what+'?fs=1&amp;hl=en_US&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="never" allowfullscreen="true" class="videoBoxERC" ></embed></object>');
	}
	else if(hasVimeo) {
		var out = '<iframe class="videoBoxERC" src="http://player.vimeo.com/video/'+what+'" frameborder="0"></iframe>';
		j$('#'+where).html(out);
	}
	else if (((clientPlaysH264) && (hasH264)) || ((clientPlaysOgg) && (hasOgg))) {
		//alert("playing h264...")
		var out = '<video  class="videoBoxERC" controls="controls"';
		if(autoplay){out += ' autoplay="autoplay" ';}
		out += ' >';
		if (hasH264) {out += '<source src="'+what+'.mp4" type="video/mp4; codecs=\'mp4v.20.8, mp4a.40.2\'" >';}
		if (hasOgg) {out += '<source src="'+what+'.ogv" type="video/ogg; codecs=\'theora, vorbis\'" >';}
		out += "</video>";
		j$('#'+where).html(out)
	} // can play native
	else if ((clientPlaysFlash) && (hasFlash)) {	
		// use flowPlayer for flash
		flowplayerStandard(where,what+'.flv',autoplay)
	} // can play flash
	else if  (((clientPlaysQuickTime) && (hasH264)) || ((clientPlaysQuickTime) && (hasQuickTime))) {
		// Firefox can't play mp4 directly, unless the user has quick time, so use that...
		var ext = ".mov";
		if(!hasQuickTime) {ext = ".mp4";}
		var out = '<object class="videoBoxERC" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab">'
		out += '<param name="src" value="'+what+ext+'" >'
		if(autoplay) {out += '<param name="autoplay" value="true">'}
		out += '<param name="controller" value="true"><param name="loop" value="false">'
		out += '<embed class="videoBoxERC" src="'+what+ext+'" '
		if(autoplay) {out += 'autoplay="true"'}
		out += 'controller="true" loop="false" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>'
		j$('#'+where).html(out);
	}
	else {
		// insert a placehoder because no content types match
		var noVideoOut = ''; //'<div class="videoNotPlayedERC" >'
		noVideoOut += '<p>Sorry, we could not find a suitable player for this video on your device.</p>';
		noVideoOut += '<p>This video is formated for a';
		if(hasFlash) {
			noVideoOut += ' Flash';
			if((hasH264)) {
				noVideoOut += ' or MP4';
			}
			if((hasOgg)) {
				noVideoOut += ' or Ogg/Theora';
			}
		}
		else if (hasH264){
			noVideoOut += ' MP4';
			if((hasOgg)) {
				noVideoOut += ' or Ogg/Theora';
			}
		}
		else if((hasOgg)) {
			noVideoOut += 'n Ogg/Theora';
		}
		noVideoOut += ' player.</p></div>';
		
		// insert the error into the div that holds all the video content
		j$('#videoContainERC').html(noVideoOut);
	} 
} // videoPlayer func

// plugin detection from Apple
// call as detectPlugin("QuickTime"{,plugin name...{,plugin name...}})
// plugin names are "QuickTime", "Media Player", '"Shockwave", "Flash"' (test both)
function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = detectPlugin.arguments;
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
	var pluginsArrayLength = navigator.plugins.length;
	// for each plugin...
	for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    // loop through all desired names and check each against the current plugin name
	    var numFound = 0;
	    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
		// if desired plugin name is found in either plugin name or description
		if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) || 
		    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    // this name was found
		    numFound++;
		}   
	    }
	    // now that we have checked all the required names against this one plugin,
	    // if the number we found matches the total number provided then we were successful
	    if(numFound == daPlugins.length) {
		pluginFound = true;
		// if we've found the plugin, we can stop looking through at the rest of the plugins
		break;
	    }
	}
    }
    return pluginFound;
} // detectPlugin

// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
			//alert("flashVer="+flashVer);
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
/* end Adobe flash detection functions */

