/* *
 * greyvegas.js -- javascript library for greyvegs.net
 * Copyright (C) 2008 -2011 LYNOC dev. 
 */


// -------------- global variables -----------------
var currentGallery = '';
var galleryJsonString='';
var galJsonObj;
var imageIndex = 0;
// this will be built dynamically after retrieving the JSON;
var galleryInfo = '';

var activeMenuLink       = '';
var activeMenuContent    = '';
var activeSubmenuLink    = '';
var activeSubmenuContent = '';

var coverImageDir = "images/frontPage/";

function updatePublicationsSubmenu( divId, linkId )
{
	if( linkId == activeSubmenuLink ){// (don't  clear publications menu before checking flags)
		clearPublicationsSubmenu();
		
	}else{ 
		clearPublicationsSubmenu();
		displayElements( divId, linkId );
		
		document.getElementById('publicationsDisplayable').style.display = 'block';
		activeSubmenuLink    = linkId;
		activeSubmenuContent = divId;
	}
}


function updateMenuDisplay( divId, linkId )
{
	clearPublicationsSubmenu();
	
	if( linkId == activeMenuLink ){// (don't  clear menu before checking flags)
		clearActiveMenu();
		
	}else{
		clearActiveMenu();
		displayElements( divId, linkId );
		
		activeMenuLink    = linkId;
		activeMenuContent = divId;
	}
}


function clearPublicationsSubmenu(){
	clearElements( activeSubmenuContent, activeSubmenuLink );
	activeSubmenuLink = '';
	activeSubmenuContent = '';
	document.getElementById('publicationsDisplayable').style.display = 'none';
}


function clearActiveMenu(){
	clearElements( activeMenuContent, activeMenuLink );
	activeMenuContent = '';
	activeMenuLink = '';
}


function clearElements( divId, linkId ){
	var link  = document.getElementById( linkId );
	var div   = document.getElementById( divId );
	
	if(link != null ) link.className = "links";
	if(div  != null ) div.style.display = 'none';
	
	shrinkBar();
}


function displayElements( divId, linkId ){
	var link = document.getElementById( linkId );
	var div  = document.getElementById( divId );
	
	if(link != null ) link.className = "selected";
	if(div  != null ) div.style.display = 'block';
}



function setHeight( targetDivId ){
	var availableSpace = screen.height;
	// set height of scrollable region
    //                              contentPanel.top  main.top   browser menu height??
	var height = availableSpace - ( 207         +         150      + 60 );// need to figure out a better way of doing this
	document.getElementById(targetDivId).style.height = height +"px";
	
}

// decreases news/publication title bar width
function shrinkBar(){
	document.getElementById('extendableBar').className = 'fixedBar';
}

// increases news/publication title bar width
function stretchBar(){
	document.getElementById('extendableBar').className = 'stretchedBar';
}


//Manages the hiding/showing of news content. 
function manageNews(){
	
	setHeight('newsDisplayable');
	updateMenuDisplay( 'newsDisplayable' , 'newsLink');
	
	if( document.getElementById('newsDisplayable').style.display == 'block'){
		stretchBar();
	}
	
}


// Manages the showing/hiding of the publications list. If clicked twice,
// it will hide any publications that were previously active
function managePublications(){
	updateMenuDisplay('publist','publicationsLink');
}



// Shows publication content associated with publication name in content panel
function showPublication( publicationId, linkId ){
	setHeight( 'publicationsDisplayable' );
	updatePublicationsSubmenu( publicationId, linkId )
	
	if( document.getElementById('publicationsDisplayable').style.display == 'block'){
		stretchBar();
	}
}


function showPublicationImage( targetDiv, imageUrl ){
	var node = document.getElementById( targetDiv );
	var imageTag = node.getElementsByTagName("img")[0];
	imageTag.setAttribute('src', imageUrl);
}



function selectRandomImage(){
	// http://www.javascriptkit.com/javatutors/randomnum.shtml
	var randomNumber = Math.round( (Math.random()*14)+1 ); // generate a random number between 1 and 15
	var pictureDisplay = document.getElementById("picturedisplay");
	pictureDisplay.getElementsByTagName("img")[0].src = coverImageDir+"image"+randomNumber+"_over.jpg";//start with blue wash image
	var imagePreload = new Image();
	imagePreload.src = coverImageDir+"image"+randomNumber+".jpg"; // preload the non blue wash image
	
}





// the two functions below turn the image and main link blue... and the other reverts it

function turnBlue(){
	document.getElementById('indextitle').style.color="#000000";// Change greyvegas text colour
	
	// Should replace current cover image with a blue washed image with 
	var pictureDisplay = document.getElementById("picturedisplay");
	var imageTag = pictureDisplay.getElementsByTagName("img")[0];
	var imageName = imageTag.src.split(".jpg")[0];
	imageTag.src = imageName + "_over.jpg";
}


function turnBack(){
	document.getElementById('indextitle').style.color="#000000";

	// Should replace current blue washed cover image with original image (no blue wash) 
	var pictureDisplay = document.getElementById("picturedisplay");
	var imageTag = pictureDisplay.getElementsByTagName("img")[0];
	var imageName = imageTag.src.split("_over.jpg")[0];
	imageTag.src = imageName + ".jpg";
}


// -------------------------------------------------
// this sets the gallery name and submits the hidden form in main.html, which redirects to gallery.html
// gallery.html then runs getUrlParam() on load up to load the relevant gallery images
function goToGallery(galleryName){
	currentGallery = galleryName;	
	document.getElementById('galname').value = galleryName;
	document.input.submit();	
}

// -------------------------------------------------
function setCurrentGallery(galleryName){
	currentGallery = galleryName;		
}

// -------------------------------------------------
function getCurrentGallery(){
	return currentGallery;
}

// -------------------------------------------------
function moveToNextImage(){	

	document.getElementById('picturedisplay').innerHTML =
	 '<a href = \'#\' onclick=\'moveToNextImage();\'><img src=\'galleries/'+currentGallery+'/'+galleryInfo[imageIndex].file+'\' border=0/></a>'+
	 "<br/><p><small>"+galleryInfo[imageIndex].name+" &#169;<br/>"
	+(imageIndex+1)+" of "+galleryInfo.length+"</small></p>";  

	imageIndex++;
	
	if (imageIndex >= galleryInfo.length) {
		imageIndex = 0;
	}
	else
	{
		var delay = function() { preloadNextImage(imageIndex, currentGallery); };
		setTimeout(delay, 700);
	}
}
function preloadNextImage(num, currentGallery){
	var tmp = new Image();
	tmp.src = 'galleries/'+currentGallery+'/'+galleryInfo[num].file;
}

// -------------------------------------------------

function initGalleryPage(){
	getUrlParam('galleryName'); 
	ajaxGetGalleryInfo(); 
	// need to call moveToNextImage after a time to give the ajax call above enough time to be  
	// in the ready state and populate the necessary variables
	// setTimeout('moveToNextImage()', 700);
}
// -------------------------------------------------
// to get specified parameter in the URL after a GET
function getUrlParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else{
	setCurrentGallery(results[1]);
    return results[1];	
  }	
}




// -------------------------------------------------
// an ajax call to get the contents of the gallery.json file and create an object with it
function ajaxGetGalleryInfo()
{
  var xmlHttp = buildXmlHttpRequest();
  // --- function that is run when file recieved ----
  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
      {
      	galleryJsonString = xmlHttp.responseText;    
      	createGalleryObject();      
      }
  }
  //------------------------
  xmlHttp.open("GET","galleries/gallery.json",true);
  xmlHttp.send(null);
  
}

// -------------------------------------------------
// function to create a JSON object representing gallery info using the string returned from the ajax call
function createGalleryObject()
{
	galJsonObj = eval('(' + galleryJsonString + ')');
	// now the variable galleryInfo is used to retrieve the gallery specific info from the json file 
	eval('galleryInfo=galJsonObj.'+getCurrentGallery()+';');
	moveToNextImage();
}

// -------------------------------------------------
// an ajax call to get the contents of the news.div file and display in it's div in main.html
function ajaxBuildNews()
{
  var xmlHttp = buildXmlHttpRequest();
  // --- function that is run when file recieved ----
  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
      {
      var news = xmlHttp.responseText;      
      document.getElementById('newsDisplayable').innerHTML = news;
      }
  }
  //------------------------
  xmlHttp.open("GET","news.div",true);
  xmlHttp.send(null);
  
}

// -------------------------------------------------
// an ajax call to get the contents of the publications.div file and display in it's div in main.html
function ajaxBuildPublications()
{
  var xmlHttp = buildXmlHttpRequest();
  // --- function that is run when file recieved ----
  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
      {
      var pub = xmlHttp.responseText;      
      document.getElementById('publicationsDisplayable').innerHTML = pub;
      }
  }
  //------------------------
  xmlHttp.open("GET","publications.div",true);
  xmlHttp.send(null);  
}


// -------------------------------------------------
/*
 * Extract taken from: http://www.webdeveloper.com/forum/archive/index.php/t-147342.html
 * 
 * While your page is ran locally via the file:// protocol, IE7's native XMLHttpRequest is powerless 
 * even to a file in the same directory, yet, in the same situation, ActiveX would be able to serve IE7 normally.
 * The reason is because IE7's XMLHttpRequest object is limited to the web.Hence your "access denied in IE7"
 * error since IE7 in your code is being served via XMLHttpRequest rather than ActiveX.
 * 
 * Firefox's XMLHttpRequest object, on the other hand, allows both local requests as well as requests
 * on the web.
*/
function buildXmlHttpRequest()
{  
  var xmlhttp=false;
  // Pre-process commands, do not remove commented code
  /* running locally on IE5.5, IE6, IE7 */ ; /*@cc_on
  if(location.protocol=="file:"){
    if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
    if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;}
  } ; @cc_off @*/

  /* IE7, Firefox, Safari, Opera... */
  if(!xmlhttp)try{ xmlhttp=new XMLHttpRequest(); }catch(e){xmlhttp=false;}
  
  /* IE6 */
  if(typeof ActiveXObject != "undefined"){
    if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
    if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;}
  }

  /* IceBrowser */
  if(!xmlhttp)try{ xmlhttp=createRequest(); }catch(e){xmlhttp=false;}
 
 return xmlhttp;
}
