// The code below contains functions that run active content. The functions
// assemble an OBJECT/EMBED tag string, and then perform a document.write of 
// this string in the calling html document.
//   AC_RunFlContent() - build tags to display Flash content.
//   AC_RunFlContentX() - build XHTML formatted tags to display Flash content.
//   AC_RunSWContent() - build tags to display Shockwave content.
//   AC_RunSWContentX()  - build XHTML formatted tags to display Shockwave content.
//
// To call one of these functions, pass all the attributes and values that you would 
// otherwise specify for the object, param, and embed tags in the following form:
//   AC_RunFlContent(
//     "attrName1", "attrValue1"
//     "attrName2", "attrValue2"
//     ...
//     "attrNamen", "attrValuen"
//   )
//
// When passing in the src or movie attributes, do not include the file extension.
// Note, these functions use default values for several standard tag attributes, 
// including classid, codebase, pluginsPage, and mimeType, depending on the function
// you call. So, you should not pass in values for these attributes. If you require
// an alternate values for these attributes, you'll need to modify the default values 
// used in the 'Run' function implementations below. However, you may pass in an
// alternate version for the codebase value, as in AC_RunFlContent("codebase","6,0,0,0",...).
// Note that you should only pass in the version string rather than the full
// codebase URL.
//
// You must include  for these functions to work.

function AC_RunFlContent()
{
  // First, look for a "movie" and "src" params, and if either exists, add a ".swf" to the end
  // if it doesn't already have one (this function will only run swf files)
  AC_AddExtension(arguments, "movie", ".swf");
  AC_AddExtension(arguments, "src", ".swf");

  // Build the codebase value. If user passed in a version for the codebase, add the version
  // to the base codebase url. Otherwise, use the default version.
  var codebase = AC_GetCodebase
                 (  "http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version="
                  , "7,0,0,0", arguments 
                 );
	
  AC_GenerateObj
  (  "AC_RunFlContent()", false, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   , codebase
   , "http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
   , "application/x-shockwave-flash", arguments
  );
}

function AC_RunFlContentX()
{
  // First, look for a "movie" and "src" params, and if either exists, add a ".swf" to the end
  // if it doesn't already have one (this function will only run swf files)
  AC_AddExtension(arguments, "movie", ".swf");
  AC_AddExtension(arguments, "src", ".swf");

  // Build the codebase value. If user passed in a version for the codebase, add the version
  // to the base codebase url. Otherwise, use the default version.
  var codebase = AC_GetCodebase
                 (  "http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version="
                  , "7,0,0,0", arguments 
                 );
	
  AC_GenerateObj
  (  "AC_RunFlContentX()", true, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   , codebase
   , "http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
   , "application/x-shockwave-flash", arguments
  );	
}

function AC_RunSWContent()
{
  // First, look for a "src" param, and if it exists, add a ".dcr" to the end
  // if it doesn't already have one (this function will only run dcr files)
  AC_AddExtension(arguments, "src", ".dcr");

  // Build the codebase value. If user passed in a version for the codebase, add the version
  // to the base codebase url. Otherwise, use the default version.
  var codebase = AC_GetCodebase
                 (  "http://fpdownload.macromedia.com/pub/shockwave/cabs/director/sw.cab#version="
                  , "8,5,0,0", arguments 
                 );
	
  AC_GenerateObj
  (  "AC_RunSWContent()", false, "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
   , codebase
   , "http://www.macromedia.com/shockwave/download/", null, arguments
  );
}
	
function AC_RunSWContentX()
{
  // First, look for a "src" param, and if it exists, add a ".dcr" to the end
  // if it doesn't already have one (this function will only run dcr files)
  AC_AddExtension(arguments, "src", ".dcr");

  // Build the codebase value. If user passed in a version for the codebase, add the version
  // to the base codebase url. Otherwise, use the default version.
  var codebase = AC_GetCodebase
                 (  "http://fpdownload.macromedia.com/pub/shockwave/cabs/director/sw.cab#version="
                  , "8,5,0,0", arguments 
                 );
	
  AC_GenerateObj
  (  "AC_RunSWContentX()", true, "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
   , codebase
   , "http://www.macromedia.com/shockwave/download/", null, arguments
  );
}
	


// Implements AC_GenerateObj() function. This is a generic function used to generate
// object/embed/param tags. It is used by higher level api functions.

/************** LOCALIZABLE GLOBAL VARIABLES ****************/

var MSG_EvenArgs = 'The %s function requires an even number of arguments.'
                 + '\nArguments should be in the form "atttributeName","attributeValue",...';
var MSG_SrcRequired = "The %s function requires that a movie src be passed in as one of the arguments.";

/******************** END LOCALIZABLE **********************/

// Finds a parameter with the name paramName, and checks to see if it has the 
// passed extension. If it doesn't have it, this function adds the extension.
function AC_AddExtension(args, paramName, extension)
{
  var currArg, paramVal, queryStr, endStr;
  for (var i=0; i < args.length; i=i+2){
    currArg = args[i].toLowerCase();    
    if (currArg == paramName.toLowerCase() && args.length > i+1) {
      paramVal = args[i+1];
      queryStr = "";

      // Pull off the query string if it exists.
      var indQueryStr = args[i+1].indexOf('?');
      if (indQueryStr != -1){
        paramVal = args[i+1].substring(0, indQueryStr);
        queryStr = args[i+1].substr(indQueryStr);
      }

      endStr = "";
      if (paramVal.length > extension.length)
        endStr = paramVal.substr(paramVal.length - extension.length);
      if (endStr.toLowerCase() != extension.toLowerCase()) {
        // Extension doesn't exist, add it
        args[i+1] = paramVal + extension + queryStr;
      }
    }
  }
}

// Builds the codebase value to use. If the 'codebase' parameter is found in the args,
// uses its value as the version for the baseURL. If 'codebase' is not found in the args,
// uses the defaultVersion.
function AC_GetCodebase(baseURL, defaultVersion, args)
{
  var codebase = baseURL + defaultVersion;
  for (var i=0; i < args.length; i=i+2) {
    currArg = args[i].toLowerCase();    
    if (currArg == "codebase" && args.length > i+1) {
      if (args[i+1].indexOf("http://") == 0) {
        // User passed in a full codebase, so use it.
        codebase = args[i+1];
      }
      else {
        codebase = baseURL + args[i+1];
      }
    }
  }
	
  return codebase;	
}

// Substitutes values for %s in a string.
// Usage: AC_sprintf("The %s function requires %s arguments.","foo()","4");
function AC_sprintf(str){
  for (var i=1; i < arguments.length; i++){
    str = str.replace(/%s/,arguments[i]);
  }
  return str;
}
		
// Checks that args, the argument list to check, has an even number of 
// arguments. Alerts the user if an odd number of arguments is found.
function AC_checkArgs(args,callingFn){
  var retVal = true;
  // If number of arguments isn't even, show a warning and return false.
  if (parseFloat(args.length/2) != parseInt(args.length/2)){
    alert(sprintf(MSG_EvenArgs,callingFn));
    retVal = false;
  }
  return retVal;
}
	
function AC_GenerateObj(callingFn, useXHTML, classid, codebase, pluginsPage, mimeType, args){

  if (!AC_checkArgs(args,callingFn)){
    return;
  }

  // Initialize variables
  var tagStr = '';
  var currArg = '';
  var closer = (useXHTML) ? '/>' : '>';
  var srcFound = false;
  var embedStr = '<embed';
  var paramStr = '';
  var embedNameAttr = '';
  var objStr = '<object classid="' + classid + '" codebase="' + codebase + '"';

  // Spin through all the argument pairs, assigning attributes and values to the object,
  // param, and embed tags as appropriate.
  for (var i=0; i < args.length; i=i+2){
    currArg = args[i].toLowerCase();    

    if (currArg == "src"){
      if (callingFn.indexOf("RunSW") != -1){
        paramStr += '<param name="' + args[i] + '" value="' + args[i+1] + '"' + closer + '\n';
        embedStr += ' ' + args[i] + '="' + args[i+1] + '"';
        srcFound = true;
      }
      else if (!srcFound){
        paramStr += '<param name="movie" value="' + args[i+1] + '"' + closer + '\n'; 
        embedStr += ' ' + args[i] + '="' + args[i+1] + '"';
        srcFound = true;
      }
    }
    else if (currArg == "movie"){
      if (!srcFound){
        paramStr += '<param name="' + args[i] + '" value="' + args[i+1] + '"' + closer + '\n'; 
        embedStr += ' src="' + args[i+1] + '"';
        srcFound = true;
      }
    }
    else if (   currArg == "width" 
              || currArg == "height" 
              || currArg == "align" 
              || currArg == "vspace" 
              || currArg == "hspace" 
              || currArg == "class" 
              || currArg == "title" 
              || currArg == "accesskey" 
              || currArg == "tabindex"){
      objStr += ' ' + args[i] + '="' + args[i+1] + '"';
      embedStr += ' ' + args[i] + '="' + args[i+1] + '"';
    }
    else if (currArg == "id"){
      objStr += ' ' + args[i] + '="' + args[i+1] + '"';
      // Only add the name attribute to the embed tag if a name attribute 
      // isn't already there. This is what Dreamweaver does if the user
      // enters a name for a movie in the PI: it adds id to the object
      // tag, and name to the embed tag.
      if (embedNameAttr == "")
        embedNameAttr = ' name="' + args[i+1] + '"';
    }
    else if (currArg == "name"){
      objStr += ' ' + args[i] + '="' + args[i+1] + '"';
      // Replace the current embed tag name attribute with the one passed in.
      embedNameAttr = ' ' + args[i] + '="' + args[i+1] + '"';
    }    
    else if (currArg == "codebase"){
      // The codebase parameter has already been handled, so ignore it. 
    }    
    // This is an attribute we don't know about. Assume that we should add it to the 
    // param and embed strings.
    else{
      paramStr += '<param name="' + args[i] + '" value="' + args[i+1] + '"' + closer + '\n'; 
      embedStr += ' ' + args[i] + '="' + args[i+1] + '"';
    }
  }

  // Tell the user that a movie/src is required, if one was not passed in.
  if (!srcFound){
    alert(AC_sprintf(MSG_SrcRequired,callingFn));
    return;
  }

  if (embedNameAttr)
    embedStr += embedNameAttr;	
  if (pluginsPage)
    embedStr += ' pluginspage="' + pluginsPage + '"';
  if (mimeType)
    embedStr += ' type="' + mimeType + '"';
    
  // Close off the object and embed strings
  objStr += '>\n';
  embedStr += '></embed>\n'; 

  // Assemble the three tag strings into a single string.
  tagStr = objStr + paramStr + embedStr + "</object>\n"; 

  document.write(tagStr);
}


//** Slider script- Dynamic Drive DHTML code
//** Modified: 2006-10-30 by Alex Sampson

////Ajax related settings
var csbustcachevar=0 //bust potential caching of external pages after initial Ajax request? (1=yes, 0=no)
var csloadstatustext="<img src='/images/layout/loading.gif' /> Requesting content..." //HTML to indicate Ajax page is being fetched
var csexternalfiles=[] //External .css or .js files to load to style the external content(s), if any. Separate multiple files with comma ie: ["cat.css", dog.js"]

////NO NEED TO EDIT BELOW////////////////////////
var enablepersist=false
var slidernodes=new Object() //Object array to store references to each content slider's DIV containers (<div class="slide">)
var csloadedobjects="" //Variable to store file names of .js/.css files already loaded (if Ajax is used)

function ContentSlider(sliderid, autorun) {
	var slider=document.getElementById(sliderid)
	slidernodes[sliderid]=[] //Array to store references to this content slider's DIV containers (<div class="slide">)
	ContentSlider.loadobjects(csexternalfiles) //Load external .js and .css files, if any
		var alldivs=slider.getElementsByTagName("div")
		for (var i=0; i<alldivs.length; i++){
			if (alldivs[i].className=="slide"){
				slidernodes[sliderid].push(alldivs[i]) //add this DIV reference to array
				if (typeof alldivs[i].getAttribute("rel")=="string") //If get this DIV's content via Ajax (rel attr contains path to external page)
					ContentSlider.ajaxpage(alldivs[i].getAttribute("rel"), alldivs[i])
			}
		}
	ContentSlider.buildpagination(sliderid)
		var loadfirstcontent=true
		if (enablepersist && getCookie(sliderid)!=""){ //if enablepersist is true and cookie contains corresponding value for slider
			var cookieval=slider1getCookie(sliderid).split(":") //process cookie value ([sliderid, int_pagenumber (div content to jump to)]
			if (document.getElementById(cookieval[0])!=null && typeof slidernodes[sliderid][cookieval[1]]!="undefined"){ //check cookie value for validity
				ContentSlider.turnpage(cookieval[0], parseInt(cookieval[1])) //restore content slider's last shown DIV
				loadfirstcontent=false
			}
		}
		if (loadfirstcontent==true) //if enablepersist is false, or cookie value doesn't contain valid value for some reason (ie: user modified the structure of the HTML)
			ContentSlider.turnpage(sliderid, 0) //Display first DIV within slider
			if (typeof autorun=="number" && autorun>0) //if autorun parameter (int_miliseconds) is defined, fire auto run sequence
				window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorun)}, autorun)
}


ContentSlider.buildpagination=function(sliderid){
	
	var paginatediv=document.getElementById("paginate-"+sliderid) //reference corresponding pagination DIV for slider
	var pcontent=""
	pcontent+='<p class="numbers">'
	for (var i=0; i<slidernodes[sliderid].length; i++) //For each DIV within slider, generate a pagination link
		pcontent+='<a href="#" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', '+i+'); return false\">'+(i+1)+'</a>'
		pcontent+=' of '+slidernodes[sliderid].length+' </p>'
		pcontent+='<p class="nav"><a class="previous" href="#" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\'))); return false\">Previous</a> '
		pcontent+='<a class="next" href="#" onClick=\"ContentSlider.turnpage(\''+sliderid+'\', parseInt(this.getAttribute(\'rel\'))); return false\">Next</a> </p>'

	paginatediv.innerHTML=pcontent
	paginatediv.onclick=function(){ //cancel auto run sequence (if defined) when user clicks on pagination DIV
		if (typeof window[sliderid+"timer"]!="undefined")
		clearTimeout(window[sliderid+"timer"])
	}
	
}


ContentSlider.turnpage=function(sliderid, thepage){
	
	var paginatelinks=document.getElementById("paginate-"+sliderid).getElementsByTagName("a") //gather pagination links
	for (var i=0; i<slidernodes[sliderid].length; i++){ //For each DIV within slider
		paginatelinks[i].className="" //empty corresponding pagination link's class name
		slidernodes[sliderid][i].style.display="none" //hide DIV
	}
	paginatelinks[thepage].className="selected" //for selected DIV, set corresponding pagination link's class name
	slidernodes[sliderid][thepage].style.display="block" //show selected DIV
	
	//Set "Previous" pagination link's "rel" attribute to the next DIV number to show
	thepreviouspage=(thepage<paginatelinks.length-2)? thepage-1 : 0
	if (thepreviouspage>-1)
		paginatelinks[paginatelinks.length-2].setAttribute("rel", thepreviouspage)
	else	
		paginatelinks[paginatelinks.length-2].setAttribute("rel", slidernodes[sliderid].length-1)
	
	//Set "Next" pagination link's "rel" attribute to the next DIV number to show
	thenextpage=(thepage<paginatelinks.length-1)? thepage+1 : 0
	if (thenextpage<slidernodes[sliderid].length)
		paginatelinks[paginatelinks.length-1].setAttribute("rel", thenextpage)
	else	
		paginatelinks[paginatelinks.length-1].setAttribute("rel", 0)

	if (enablepersist)
		setCookie(sliderid, sliderid+":"+thepage)
}


ContentSlider.autoturnpage=function(sliderid, autorunperiod){
	var paginatelinks=document.getElementById("paginate-"+sliderid).getElementsByTagName("a") //Get pagination links
	var nextpagenumber=parseInt(paginatelinks[paginatelinks.length-1].getAttribute("rel")) //Get page number of next DIV to show
	ContentSlider.turnpage(sliderid, nextpagenumber) //Show that DIV
	window[sliderid+"timer"]=setTimeout(function(){ContentSlider.autoturnpage(sliderid, autorunperiod)}, autorunperiod)
}

function getCookie(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
	return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

function setCookie(name, value){
	document.cookie = name+"="+value
}

////////////////Ajax Related functions //////////////////////////////////

ContentSlider.ajaxpage=function(url, thediv){
var page_request = false
var bustcacheparameter=""
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
thediv.innerHTML=csloadstatustext
page_request.onreadystatechange=function(){
ContentSlider.loadpage(page_request, thediv)
}
if (csbustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

ContentSlider.loadpage=function(page_request, thediv){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
thediv.innerHTML=page_request.responseText
}

ContentSlider.loadobjects=function(externalfiles){ //function to load external .js and .css files. Parameter accepts a list of external files to load (array)
for (var i=0; i<externalfiles.length; i++){
var file=externalfiles[i]
var fileref=""
if (csloadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
csloadedobjects+=file+" " //Remember this object as being already added to page
}
}
}
