/* START SHOW FLASH VIDEO */

function showVideoOld(id) {
var aVideo = new SWFObject("/atwone/flv/flvplayer.swf","single","320","240","7"); 
aVideo.addParam("allowfullscreen","true");
aVideo.addVariable("file","/atwone/flv/"+id+".flv");
aVideo.addVariable("autostart",true);
aVideo.write("playerPanel");
}

// Flowplayer configuration (less buttons and wicked background color) 
var playerConfig = { 
   /*controlBarBackgroundColor: '0x99cddc', */
   initialScale:'scale', 
   showMenu:false, 
   showVolumeSlider:true, 
   showMuteVolumeButton:false, 
   showFullScreenButton:true, 
   controlBarGloss:'high' 
} 
  
var flowplayer = null;  


function setUpVideoPlayer() { 

   // variable that holds the player API. it is initially null 
    
   /************* THE PLAYLIST ***************/ 

   // loop all links within DIV#playlist and customize their onClick event  
   var links = document.getElementById("playlist").getElementsByTagName("a");  
    
   for (var i = 0; i < links.length; i++) { 
       /* Special case if an mp3 
             1) Remove the 'flv' extension
             2) Change the url from /atwone/flv/file.mp3 to /atwone/pod/file.mp3
          */  
          var url = links[i].getAttribute("href");
         var extention = url.substr(url.length -3);      
         if ("mp3.flv" == url.substr(url.length - "mp3.flv".length)){
               url = url.substr(0, url.length - ".flv".length);
               url = "/atwone/pod" + url.substr(url.lastIndexOf('/'));
               links[i].setAttribute("href", url);
         }

      links[i].onclick = function() {  
         var href = this.getAttribute("href"); 
          
        if ("mp3" == href .substr(href .length - "mp3".length)){
               var image = this.getAttribute("name");   /* Thumbnail location is stored in the name */
               playerConfig.playList = [ { url: href , overlay: image}] ;
                playerConfig.videoFile = null ;  
        }
        else{
                  playerConfig.videoFile = href ;
        }
        
         if (flowplayer == null) { 
            flowplayer = flashembed("player",  
               {src:"/atwone/static/FlowPlayerDark.swf", bgcolor:'#6F7485'},  
               {config: playerConfig} 
            );  
             
         } else {     
            flowplayer.setConfig(playerConfig);  
         } 
         // disable link's default behaviour 
         return false;  
      }      
   } 
   // when clicks on the player it triggers our first playlist entry 
   document.getElementById("player").onclick = function()  { 
      links[0].onclick(); 
   } 
    /*  
        If you want your video to start when your  
        page loads then uncomment next line  
    */    
     document.getElementById("player").onclick(); 
}

/* Called when page loads*/
function playFirstMediaFile(){
    
    /* Automatically play media file if user hasn't already selected one before the page loaded */
   if (!flowplayer){
         var playlist = document.getElementById("playlist");
         if (playlist){
              var links = playlist.getElementsByTagName("a");
              if (links && links.length >= 1){
                   document.getElementById("player").onclick = function()  { 
                        links[0].onclick(); 
                   } 
                   /*  
                    If you want your video to start when your  
                    page loads then uncomment next line  
                    */    
                    document.getElementById("player").onclick(); 
              }
         }
   }

}

function playMedia(link){
        var href = link.getAttribute("href"); 
      
        var splashImage = "";
        if (getFileExtension(href) == "mp3"){
               splashImage = link.getAttribute("thumb");   /* Thumbnail location is stored in the name */            
        }
        
        embedFlashVideo("player", href, "", splashImage, 305, 255, true);
          
         // disable link's default behaviour 
         return false;  
}



/* /END SHOW FLASH VIDEO */


function newsQuery(cat,yr) {
  document.getElementById('newsContent').innerHTML='<img src="/atwone/static/ajaxWheel.gif" width="16" height="16" align="top">';
  var params = new Hash();
  params.set('category', cat);
  params.set('year', yr);

  new Ajax.Request('/atwone/static/news_query.cgi', {
  method: 'post',
  parameters: params,
  onSuccess: function(response) {
        if (response.status == 200 && response.statusText == 'OK') {
         document.getElementById('newsContent').innerHTML=response.responseText;
        if (cat!='') {
         document.getElementById('breadCrumbTitle').innerHTML='News » '+cat;
        } else {
         document.getElementById('breadCrumbTitle').innerHTML='News » '+yr;
        }
        } else {
         document.getElementById('newsContent').innerHTML=response.responseText;
        }
  },
  onFailure: function(response) {
         document.getElementById('newsContent').innerHTML=response.responseText;
  },
  onComplete: function(response) {
         document.getElementById('newsContent').innerHTML=response.responseText;
  }
});

}

function libraryQuery() {	
 var limg='<img src="/atwone/static/ajaxWheel.gif" width="16" height="16" align="top" />';
  jQuery("#libraryContent").html(limg);
  var str="";
	str += "q=" + document.lQuery.elements["Q"].value + "&";
	str += "dg=" + document.lQuery.elements["DG"].options[document.lQuery.elements["DG"].selectedIndex].value + "&";
	str	+= "ec=" + document.lQuery.elements["EC"].options[document.lQuery.elements["EC"].selectedIndex].value + "&";
	str += "pr=" + document.lQuery.elements["PR"].options[document.lQuery.elements["PR"].selectedIndex].value + "&";
	str += "s=" + document.lQuery.elements["S"].options[document.lQuery.elements["S"].selectedIndex].value + "&";
	str += "cj=" + document.lQuery.elements["CJ"].options[document.lQuery.elements["CJ"].selectedIndex].value + "&";
	str += parseInt(Math.round(9999 * Math.random()));
	str = str.replace(/ /gi, "%20");
	str = "/visage/static/library_query.cgi?" + str;
        jQuery("#libraryContent").load(str);
}





function highlightTab(pageName, complete) {
  var menu = document.getElementById("menu");
  var items = menu.getElementsByTagName("a");
  for (var i =0; i < items.length; i++) { 
    var a = items[i];
    var href = a.href;
        if (href.lastIndexOf(pageName) == (href.length - pageName.length)) {
          a.className = "selected";
        }
   }
}


function old_libraryQuery() {
/*
  var code='<img src="/atwone/static/ajaxWheel.gif" width="16" height="16" align="top" />';
  jQuery("#libraryContent").html(code);
alert(0);
  var libraryDiv = $('libraryContent');
  libraryDiv.innerHTML='<img src="/atwone/static/ajaxWheel.gif" width="16" height="16" align="top" />';
  var params = new Hash();
alert(1);
  params.set('q', document.lQuery.elements["Q"].value);
  params.set('dg', document.lQuery.elements["DG"].options[document.lQuery.elements["DG"].selectedIndex].value);
  params.set('ec', document.lQuery.elements["EC"].options[document.lQuery.elements["EC"].selectedIndex].value);
  params.set('pr', document.lQuery.elements["PR"].options[document.lQuery.elements["PR"].selectedIndex].value);
alert(2);
  params.set('s', document.lQuery.elements["S"].options[document.lQuery.elements["S"].selectedIndex].value);
  params.set('cj', document.lQuery.elements["CJ"].options[document.lQuery.elements["CJ"].selectedIndex].value);


  new Ajax.Request('/atwone/static/library_query.cgi', {
  method: 'post',
  parameters: params,
  onSuccess: function(response) {
        if (response.status == 200 && response.statusText == 'OK') {
         librayrDiv.innerHTML=response.responseText;
        } else {
         librayrDiv.innerHTML=response.responseText;
        }
  },
  onFailure: function(response) {
         librayrDiv.innerHTML=response.responseText;
  },
  onComplete: function(response) {
         librayrDiv.innerHTML=response.responseText;
  }
});
*/
}









function highlightTab(pageName, complete) {
  var menu = document.getElementById("menu");
  var items = menu.getElementsByTagName("a");
  for (var i =0; i < items.length; i++) { 
    var a = items[i];
    var href = a.href;
        if (href.lastIndexOf(pageName) == (href.length - pageName.length)) {
          a.className = "selected";
        }
   }
}

function highlightTabFromGetParam() {
    var qmarkPos = window.location.href.lastIndexOf("?");
    if (qmarkPos == -1) return;
    var param = window.location.href.slice(qmarkPos);
    highlightTab(param);
}

function getFileExtension(file){
        var dotPos = -1;
        if (-1 != (dotPos = file.lastIndexOf("."))){
            return file.substring(dotPos + 1); 
        }
        return "";
    }

/*
  In order to play uploaded Flash files (i.e. Flash videos that haven't been converted from mpef, mov etc.) you need 
  to make a few changes to the way flashembed is used (as well as updating Flow Player to the latest version).
  1) Remove 'videoFile' and 'autoPlay' attributes as they are ignored.
  2) Specify the video in a playlist
  
  ffmpeg can not create a 'splash' image for an uploaded Flash file (it just creates an image 0 bytes in size). This causes
  a problem as flowplayer displayes an error message. So, as a workaround, we will let the user specify a thumbnail 
  which can be used as the splash image. 
 */ 
 function embedFlashVideo(divLocation, mediaFile, splashImage, thumbnail, width, height, autoplay, thumbnailDir){
    /* Initialise variables if not set */
    if (!width){
        width = 320;
    }
    if (!height){
        height = 240;
    }
    if (autoplay == undefined){
        autoplay = true;
    }
    if (!splashImage){
        splashImage = "";
    }
    if (!thumbnail){
        thumbnail = "";
    }
    if (!thumbnailDir){
          thumbnailDir = "/pics_orig/";
    }
        
    var pl = [];    //Create an array to store the playlist details
    var i = 0;
    
    var isAudio = getFileExtension(mediaFile) == "mp3";
    var isVideo = !isVideo;
    
    /*
      Display a splash image if an image is available and either
        1) file is audio, or
        2) file is video and autoplay is set to false (i.e. show 'splash' image)        
     */    
    /*
     Playlist object will end up looking like this:     
     playlist: ['spash_image.jpg', {url: movie.mpg.flv, autoplay: true/false}]
    */
    
     if (thumbnail != "" || splashImage != ""){
        if (isAudio || (isVideo && !autoplay)){
             
            /* 
                Don't display the image if using an uploaded flash file and no thumnail has been set. Using the
                default corrupted image created by ffmpeg causes an error so, in this case, we're better off not using an image/
             */
            if (!(mediaFile.lastIndexOf(".flv.flv") != -1 && thumbnail == "")){
                pl[i] = thumbnail != "" ? thumbnailDir + thumbnail : splashImage;      //thumbnail takes precedence
                i++;
            }
        }       
     }
     
    
    pl[i] = new Object;
    pl[i].url = mediaFile;
    pl[i].autoPlay = autoplay;
    
    flashembed(divLocation, 
        { src:"/atwone/static/flowplayer-3.0.3.swf", width:width, height:height, bgcolor:'#ffffff' }, 
        {config: 
            { playlist: pl,
              initialScale: 'scale', useNativeFullScreen: true,showMenu : false,showFullScreenButton : true,loop : false }
        } 
    );
 }


/**Google Analytics functionality for PDFs**/
/*BRETTD(15/07/09): added for cs: 134300 - Adds Google Analytics to pdf links on the site.*/

function GAPDFInit() {
var pdflinks = document.getElementsByTagName("a");
	for (var x=0; x < pdflinks.length; x++) {
		if (pdflinks[x].href.match(".pdf")) {
		var startpos = pdflinks[x].href.lastIndexOf("/");
		var startpos = startpos + 1;
		var returnedurl = pdflinks[x].href.slice(startpos);
		pdflinks[x].setAttribute("onClick","javascript: pageTracker._trackPageview('/downloads/"+ returnedurl +"');");
		}
	} 
}

/*BRETTD(27/07/09) : Added for cs : 133996 to add caption to all images with the class '.captionedpicture'. 
Takes css from image and adds it to surrounding div (#piccontainer) to replicate current styling of page.*/


function addCaptions() {

if (jQuery) {

 $(document).ready(function(){
 
 $("img.captionedpicture").each(function() {
 
 $(this).wrap("<div id='piccontainer'></div>");
 $(this).after("<p class='gallerycaption'></p>"); 
 var alttag = $(this).attr("alt");
 if (alttag =="") {
 var alttag = $(this).attr("title");
 }

 $(this).next().text(alttag);
 
 var theHeight = $(this).height();
 var theWidth = $(this).width();
 var theFloat = $(this).css("float");
 //var theBg = $(this).css("backgroundColor");
 //var theMargin = $(this).css("margin");
 //var thePadding = $(this).css("padding");
 
 //var capHeight = $(this).next().height();
 var divHeight = theHeight + 50;
 
 var cssObj = {
 'height' : divHeight,
 'width' : theWidth,
 'float' : theFloat
 }
 
 $(this).parent().css(cssObj);
 
 });
 });
}
}

/* Used to display videos on the sharing experience (Communicating Equality) page */
function playVideo(url){
      embedFlashVideo("player", url, 
 {width: 240, height: 180, autoplay: true });
 
  
         return false;  
}

/*
 * Centre is optional
 */
function openPopup(url, width, height, centre){
	/*
	Notes:
	(assuming this function is called from the onclick in a <a> tag.
	
	return true/false... 
		- false stops execution, pop up is shown but contents of href not
		- true carries on with execution so href is shown
	*/

	/* Parameters not supplied, return true. */
	if (url == null || width == null || height == null){
		return true;
	}
	
	var options = "toolbar=no, location=yes, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=" + width + ", height=" + height;
	
	if (centre){
		//Centre the window
		var w = 800, h = 600;
		if (screen && screen.availWidth && screen.availHeight){
			w = screen.availWidth;
			h = screen.availHeight;
		}
		var leftPos = (w-width)/2;
		var topPos = (h-height)/2;
		options +=  ",left=" + leftPos + ",top=" + topPos;
	}

	var popup = window.open(url,"_blank", options);
	
	if(popup==null || typeof(popup)=="undefined"){
		alert("Popup window has been blocked. \nPlease enable popups for this web site or disable your popup blocker.");		
		return true;
	}
	
	//Everything went ok, show popup
	return false;
}


function resizeIFrame(frame) {
  //find the height of the internal page
  var the_height = frame.contentWindow.document.body.scrollHeight;

  //change the height of the iframe
 frame.height = the_height;
}

function processPosts(p, maxPosts){
        if (maxPosts == undefined){
             maxPosts = 5;
        }

	var html = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>";
//Add table header
html += "<tr>" + 
		    "<th align=\"left\">Subject</th>" +
    		"<th align=\"left\">Written By</th>" +
		    "<th align=\"left\">Posted</th>" + 
		"</tr>";


	for (var x = 0; x < p.posts.length && x < maxPosts; x++){
		var current = p.posts[x];
		
		var authorURL = "";
                /* Just show author's name. User can contact author by clicking on link to forum */
		/*if (current.email == ""){
			authorURL = current.author;
		}
		else{
			authorURL = "<a href=\"mailto:" + current.email + "\">" + current.author + "</a>";
		}*/
		
		html += 
		"<tr class=\"" + (x % 2 == 0 ? "even" : "odd") + "\">" +
			"<td>" + "<a href=\"" + current.url + "\">" + current.subject + "</a></td>" + 
			"<td nowrap=\"nowrap\">" + current.author + "</td>" + 
			"<td nowrap=\"nowrap\">" + current.lastpost +"</td>" +
		"</tr>";
		
	}
	
	html += "</tbody></table>";

	document.getElementById('posts').innerHTML = html;
}
