
/**
  *  
  *  NOTES
  *  The file marquee.jpg appears initially on the homepage (820x260 px) 
  *  The pixel dimensions for the image files are 260x500 (height x width) OR 260x240 (height x width).  You must use these dimensions!!
  *  
  *  For the slideshow to work properly:
  *  The slideshow image files must reside in the /images/slideshow directory and they must have a .jpg extension
  *
  *  LICENSE TERMS
  *  The javascript code is the intellectual property of bruce olson (beolson@mindspring.com).  You may not modify it, copy it, or share it with anyone.
  *
  *  Things to do:
  *  write a syntax checker utility that checks whether or not the scenes have been contructed properly in wordpress
  *  
*/


var 
	IMAGE_FILES=0  //number of image files. 
	
	pidx= -1  //index for the active image/caption tuplet.  Initialized to -1 to indicate a "start" state
	side=true   //points to the active image frame position true=right false=left
	playtimerID=0  // used to turnoff slideshow interval
	slide_image = new Image()
	state="NONE"  // can be NONE, INITIALIZE, RESET, PLAY, STOP
	step=1 // indicates what step we are at in the current state
	isFirstSlide=null
	wp_info=null  // holds the JSON result containing slideshow details

	seen_billboard=false
	stop_the_slideshow=false
	
	marqueeImageFirst = new Image()
	marqueeImageSecond = new Image()
	bannerImage = new Image()
	slideShowImage = new Image()

	slideLoadingTimer = null
	
	PATH_MY_IMAGES = 'http://elcvienna.org/bg/images/'
	marqueeImageSecond.src = PATH_MY_IMAGES+'marquee.jpg'


function stillLoading () {
if (marqueeImageSecond.complete) {
	clearInterval(loadingTimer)
	initialize()
	}
}

function slideLoading () {
if (slideShowImage.complete) {
	clearInterval(slideLoadingTimer)
	resume_task()
	}
}  // slideLoading()



function initialize () {  
// get config data from Wordpress database
var str, re


$.ajax({
			type: "GET",
			url: "http://elcvienna.org/bg/get_wp_info.php",
			dataType: "text",
			async: false,
			success: function(data) {
				re =/(\r\n)/g
				str=data.replace(re, "&crlf")  // remove cr/lf from string before doing eval.  Need to replace them later!
				wp_info = eval("(" + str + ")")
			} // success
}) //ajax

$('#topic').empty()
$('#topic').append('<h1>'+wp_info.info.message+'</h1>')

IMAGE_FILES=wp_info.info.slide.length

state="RESET"
step=1
setTimeout('reset_stage()',3000)

}  // end initialize()


// this function manages the timing of asynchronous tasks
function resume_task () {
//alert("state=" + state + " step =" + step)
	switch (state) {
		case "NONE" :
			break;
		case "INITIALIZE" :
			initialize();
			break;
		case "RESET" :
			reset_stage()
			break;
		case "PLAY" :
			playScene(pidx)
			break;
		case "STOP" :
			break;
		default:
	}
}


/*  resets the homepage to the start state after initialization or after stopping the slideshow*/
function reset_stage() {
	
switch (step) {
	
	case 1:  // clear everything
		step=3
		$('#pictureContainer').hide()
		$('#theCaption').hide()
		$('#marquee_frame').fadeOut('slow', function () {resume_task()})
		break;
		
	case 3 :  // next, show the collage picture and the message of the day then wait a few seconds
		step=4
		$('#marqueePicture').css('width','0')					   
		$('#marqueePicture').css('background','url('+PATH_MY_IMAGES+'marquee.jpg) no-repeat center')
		$('#marquee_frame').show()
		$('#marqueePicture').animate({
			width: "820px"}, 2000, function () {
								// show the message of the day and wait a few seconds
								if (!seen_billboard) $('#topic').slideDown('slow',function () {setTimeout('resume_task()', 2000)})
								else {
									step=5
									resume_task()
									}
								})
		break
		
	case 4:  // fadeoout messageof the day if there is one
		step=5
		if (!seen_billboard) 
			$('#topic').slideUp('slow',function () {resume_task()})
		else resume_task()
		break
		
	case 5:  // initialize variables and re-enable the slideshow buttons
		seen_billboard=true
		side=true   // side points to orientation of the displaying image  true=right false=left   --  we initialize using right side
		pidx=-1		// the index to the image array is initialized at -1
		stop_the_slideshow=false
		$('.play-stop_button').show()
		state="NONE"
	
	}  // end switch
	
} //end reset_stage()


function isTopic () {  // looks to see if there is a topic entry that precedes the display of the scene
var found=false
if (wp_info.info.slide[pidx].topic.length>2) {
	found=true
	$('#topic').empty()
	$('#topic').append('<h1>'+wp_info.info.slide[pidx].topic.substring(2)+'</h1>')
	}
return found
}


function play_slideshow() {
if (state == "NONE") //		play((pidx+1) % IMAGE_FILES)
  if (pidx+1 == IMAGE_FILES) stop_slideshow()  //last slide just played
  else {
		  state="PLAY"
		  step=1
		  $('#playButton').hide()
		  playScene(pidx+1)
		  //disable the scene buttons while the slideshow is playing
//		  $('#scene_buttons').hide()
		  if (!stop_the_slideshow) playtimerID=setTimeout("play_slideshow()", 12000)
		  }
else playtimerID=setTimeout("play_slideshow()", 1000)
}  // end play_slideshow


function stop_slideshow() {
stop_the_slideshow=true
clearTimeout(playtimerID)
$('#scene_buttons').show()
$('#scene_caption').show()
if (state == "NONE") {
	state="RESET"
	step=1
	reset_stage()
	}
// current slide is finished
}


function playScene(scene) {  //displays the requested scene
//alert("state=" + state + " step =" + step+ "pidx= "+pidx +" scene= " + scene)
if (stop_the_slideshow) {
	state="RESET"
	step=1
	reset_stage()
	}	
	else 
	  switch (step) {
		  
		  case 1 : // preload the image
		  		step = 2
				if (pidx < 0) isFirstSlide = true
				else isFirstSlide = false
				pidx=scene  //set global array pointer to requested image
		  		slideShowImage.src = PATH_MY_IMAGES+'slideshow/'+ wp_info.info.slide[scene].imagefilename + '.jpg'
				slideLoadingTimer = setInterval('slideLoading()',500)
				break
				
		  case 2 :  // fadeout the current picture
			step=3
			
			if (isFirstSlide) {  //fade out the marquee if this is the first call from slideshow
				$('#marquee_frame').fadeOut(function () {
					 			  	$('#picture').css('background','url('+PATH_MY_IMAGES+'slideshow/'+ wp_info.info.slide[scene].imagefilename + '.jpg) no-repeat center')					   

									resume_task()
									})
				}
				
			else {
				$('#pictureContainer').fadeOut('fast', function () {
											 			  $('#picture').css('background','url('+PATH_MY_IMAGES+'slideshow/'+ wp_info.info.slide[scene].imagefilename + '.jpg) no-repeat center')					   
														 })
				$('#theCaption').fadeOut('fast',function () {resume_task()})
			  }

			break
				  
 
		  case 3 :  // slide across a topic if there is one
			  if (isTopic()) {
				  step=4
				  $('#topic').slideDown(function () {setTimeout('resume_task()', 1500)})
				  }
			  else {
				  step=5
				  resume_task()
				  }
			  break
				  
		  case 4 :  // fadeout the topic if there is one
			  step=5
			  $('#topic').slideUp(function () {resume_task()})
			  break
			  
		  case 5 :  // display the new picture and caption
			  side=!side   // now switch sides for displaying the image and caption

				// get the caption that goes with this picture
				caption_string=wp_info.info.slide[pidx].caption
				re = /(&crlf)/g
				caption_string=caption_string.replace(re, "\r\n")
		  
			  if (side) {
				  $('#pictureContainer').css('float','right')
				  $('#theCaption').css('float','right')
				  }
			  else {
				  $('#pictureContainer').css('float','left')
				  $('#theCaption').css('float','left')
				  }
			  
			  $('#picture').css('width','0')
			  $('#pictureContainer').show()
			  
			  
			  $('#picture').animate({
				  width: "500px"}, 2000, function () {
											$('#theCaption').empty()
											$('#theCaption').append('<p>'+caption_string+'</p>') //insert corresponding caption
					  						$('#theCaption').fadeIn()}
											)

			  state="NONE"
			  
		  }

}  //end function playScene()

function play_one_scene(s) {  //called when the user clicks on one of the scene buttons
state="PLAY"
step=1
playScene(s)
}
	


/**   The following code deals with the visitor form dialog box that pops up when the
 *     slideshow "play" button is pressed.
 *
 * This object, Cookie, is simply a mechanism to allow for easier access of the
 * document.cookie object for the page. It contains the following methods:
 * - set(p_name, p_value, p_expires)
 * - get(p_name)
 * - erase(p_name)
 * - accept( )
 */
var Cookie = {
	/**
	 * This method, set, creates a cookie with the name equal to /p_name/ with a
	 * value of /p_value/ that expires at the specified /p_expires/ should it
	 * exist, returning whether the cookie was created or not.
	 *
	 * @member Cookie
	 * @param {String} p_name The name for the cookie to be set.
	 * @param {String} p_value The value for the cookie to be set.
	 * @param {Float} p_expires The time before the cookie to be set expires.
	 * @return Returns whether the cookie was set or not.
	 * @type Boolean
	 */
	set: function(p_name, p_value, p_expires) {
		/* The expires string for the cookie */
		var expires = '';

		/* Was an expires time sent to the method? */
		if (p_expires != undefined) {
			/* Get a base time for the expiration date */
			var expirationDate = new Date( );

			/* Set the expiration to one day times the passed /p_expires/ value */
			expirationDate.setTime(expirationDate.getTime( ) + (86400000 * parseFloat(p_expires)));
			/* Create the expires string for the cookie */
			expires = '; expires=' + expirationDate.toGMTString( );
		}
		return (document.cookie = escape(p_name) + '=' + escape(p_value || '') + expires);
	},
	/**
	 * This method, get, returns the cookie with a name equal to the passed /p_name/
	 * variable if one exists.
	 *
	 * @member Cookie
	 * @param {String} p_name The name for the cookie to return.
	 * @return Returns the cookie data if it exists or /null/ otherwise.
	 * @type String
	 */
	get: function(p_name) {
		/* Get the matching cookie */
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(p_name) + '=([^;\\s]*)'));

		return (cookie ? unescape(cookie[2]) : null);
	},
	/**
	 * This method, erase, removes the cookie with the passed /p_name/ variable from
	 * the document. It returns the erased cookie (i.e., null if erase succeeded,
	 * the cookie otherwise).
	 *
	 * @member Cookie
	 * @param {String} p_name The name for the cookie to erase.
	 * @return Returns the cookie after it is erased.
	 * @type Boolean | String
	 */
	erase: function(p_name) {
		/* Get the cookie with the passed /p_name/ variable */
		var cookie = Cookie.get(p_name) || true;

		/*
		 * Set the cookie with the passed /p_name/ variable to an empty string, and
		 * make it expire
		 */
		Cookie.set(p_name, '', -1);
		return (cookie);
	},
	/**
	 * This method, accept, tests to see if the browser accepts cookies and returns
	 * the results of this test.
	 *
	 * @member Cookie
	 * @return Returns whether the browser accepts cookies or not.
	 * @type Boolean
	 */
	accept: function( ) {
		/* Can the test be accomplished using the browser's built-in members? */
		if (typeof navigator.cookieEnabled == 'boolean')
			return (navigator.cookieEnabled);
		/* Attempt to set and erase a cookie and return the results */
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};

function show_form () {
document.getElementById("myForm").reset()
//document.getElementById('visitor_form_box').style.visibility="visible"

//play_slideshow()

if (Cookie.get("visited") == null) 
	$('#visitor_form_box').show()
else {
	play_slideshow()
	}

}  // show_form()



/* This function takes the input from the user form and mails it to the default address
*/
function mail_form () {
var i, vname, vemail, vmessage, vtype, responseData, xmlString

vtype='none'

// if user clicks a visitory type radial then get the value of that radial button
$("#myFormContainer p input[name=visitor_type]:checked").each(function () { vtype=$(this).attr('value')})

vname=$('#myFormContainer input[name=visitor_name]').attr('value')
vemail=$("#myFormContainer input[name=email]").attr('value')
vmessage=$("#myFormContainer textarea[name=message]").attr('value')

responseData = vname.length+vemail.length+vmessage.length


xmlString='<myForm>'
xmlString += '<name>'+vname+'</name>'
xmlString += '<type>'+vtype+'</type>'
xmlString += '<email>'+vemail+'</email>'
xmlString += '<comments>'+vmessage+'</comments>'
xmlString += '</myForm>'

// check to see if any useful information was provided and if so, call the server side function to create an email

if (responseData>0) {

		$.ajax({
			type: "POST",
			url: "http://elcvienna.org/bg/emailContactForm.php",
			data: 'tXML='+xmlString,
			dataType: "text",
			async: true,
			processData: false
		}) //ajax	


}


// create a cookie called /visited/ so that the form doesn't show next time
Cookie.set("visited", "yes", 365)

//now hide the form
$('#visitor_form_box').hide()

//log the event
$.ajax({
	type: "POST",
	url: "http://elcvienna.org/bg/log_play.php",
	data: 'tXML='+xmlString,
	dataType: "text",
	async: true,
	processData: false
}) //ajax	



//resume the slideshow
setTimeout("play_slideshow()",500)

}

