
// Constructor
PoB = function ()
{
	// Define some defaults
	this.page = 1;
	this.pageSize = 15; // Number of thumbnails on a gallery page
	this.columns = 5; // Number of thumbnail columns
	this.image = 1;
	
	this.dev = false; // Set to true to use dev area paths, false for live server paths
	
	// Define image locations
	if (this.dev) this.imageDir = 'http://ifl-cpstest.wc.bbc.co.uk/results/realmedia/arts/apictureofbritain/';
	// else this.imageDir = 'http://downloads.bbc.co.uk/rmhttp/arts/apictureofbritain/images/gallery/';
	else this.imageDir = '/arts/apictureofbritain/images/gallery/';
	
	this.stackSize = 20; // The number of screens to hold in memory - should be at least double the paginationSize value
	this.paginationSize = 5; // The number of pages to show either side of current page in paginated navigation

	this.debug = false; // Toggle various debug notices
	
	// Define container elements
	this.pageTitle		 = document.getElementById('pageTitle');
	this.pageTitleBg	 = document.getElementById('pageTitleBg');
	this.galleryCrumb	 = document.getElementById('galleryCrumb');
	this.searchDiv  	 = document.getElementById('search');
	this.galleryDiv 	 = document.getElementById('gallery');
	this.slidesDiv  	 = document.getElementById('slides');
	this.slidesTopNavDiv = document.getElementById('slidesTopNav');
	this.l2rDiv			 = document.getElementById('l2r');
	this.l2rFormDiv		 = document.getElementById('l2r_form');
	this.l2rResultsDiv	 = document.getElementById('l2r_results');
	this.debugDiv		 = document.getElementById('debug');
}

// To set the screen that is displayed
PoB.prototype.changeMode = function (mode)
{
	switch (mode)
	{
		case 'search':
			delete this.pageStack;
			this.page = 1;
			this.pageTitle.innerHTML = 'SEARCH THE GALLERY';
			this.pageTitleBg.className = 'boxHSite';
			this.galleryCrumb.innerHTML = '';
			this.searchDiv.style.display = 'block';
			this.galleryDiv.style.display = 'none';
			this.slidesDiv.style.display = 'none';
			this.slidesTopNavDiv.style.display = 'none';
			this.l2rDiv.style.display = 'none';
			break;
		case 'gallery':
			this.drawGallery();
			this.pageTitleBg.className = 'boxHSite';
			this._getPageTitle(mode);
			this.searchDiv.style.display = 'none';
			this.galleryDiv.style.display = 'block';
			this.slidesDiv.style.display = 'none';
			this.slidesTopNavDiv.style.display = 'none';
			this.l2rDiv.style.display = 'none';
			break;
		case 'slides':
			this._getPageTitle(mode);
			this.searchDiv.style.display = 'none';
			this.galleryDiv.style.display = 'none';
			this.slidesDiv.style.display = 'block';
			this.slidesTopNavDiv.style.display = 'block';
			this.l2rDiv.style.display = 'block';
			break;
		default:
			alert('ERROR: Bad mode');
			this._getPageTitle('default');
			break;
	}
}

// To grab the page titles from the datastructure
PoB.prototype._getPageTitle = function (mode)
{
	var t = this.pageStack[this.page];
	var a,b,c;
	
	// If in gallery screen, grab it from the search parameters
	if (mode == 'gallery')
	{
		a = ((typeof(t.cgiparam.val_2_1)=='undefined')?'':t.cgiparam.val_2_1);
		b = ((typeof(t.cgiparam.val_1_1)=='undefined')?'':t.cgiparam.val_1_1);
		//c = ((typeof(t.cgiparam.val_3_1)=='undefined')?'':t.cgiparam.val_3_1);
		if (b != '' && typeof(t.RECORD[0]) != 'undefined') this.pageTitleBg.className += ' bg_COL' + t.RECORD[0].COMP_THEME_WWW;
	}
	else if (mode == 'slides')  // If in the slideshow screen, grab it from the image data
	{
		a = t.RECORD[this.image].COMP_REGION;
		b = t.RECORD[this.image].COMP_THEME;
		//c = t.RECORD[this.image].PERSON_REAL_NAME;
	}
	else // For all other modes, use a generic title
	{
		a = '';
		b = '';
		//c = '';
	}
	// Now write it to the title container
	var sep = ((a != '' && b != '')?' : ':'');
	//var sep2 = ((c != '' && a != '')?' : ':'');
	
	var titleStr = a + sep + b;
	
	this.pageTitle.innerHTML = titleStr.toUpperCase() + '&nbsp;';
	this.galleryCrumb.innerHTML = titleStr;
}


// Stuff to execute when the search form is submitted
PoB.prototype.doSubmit = function (form)
{
	// Serve the low version to Opera and Safari as it has buggy support for
	// XMLHTTPRequest so it's easiest to ignore it
	var agt = navigator.userAgent.toLowerCase();
	if ((agt.indexOf("opera")!=-1)) return true;
	if ((agt.indexOf("safari")!=-1)) return true;
	
	// Only proceed if we can support XMLHTTPRequest
	if (bbcjs.http.supported) 
	{
		this.queryUrl = form.action + '?' + bbcjs.lib.string.obj2string(bbcjs.forms.form2object(form)) + '&OutputFormat=Javascript::Anon' + '&pagesize=' + this.pageSize + '&page=';
		//delete this.pageStack[1];
		this.pageStack = new Object();
		this._updateStack();
		return false;
	}
	else return true;
}

// Manages the stack of screens we're keeping a hold of
PoB.prototype._updateStack = function ()
{
	// Define the range of pages we want to deal with
	var b = this.page - parseInt(this.stackSize / 2);
	var f = this.page + parseInt(this.stackSize / 2);
	var i;
	
	// Remove redundant items from stack
	for (i in this.pageStack)
	{
		if (i < b || i > f)
		{
			delete this.pageStack[i];
		}
	}
	
	// Add new items to stack
	var str = '';
	for (i = b; i <= f; i++)
	{
		if (i > 0)
		{
			if (typeof(this.pageStack[i]) == 'undefined')
			{
				this.lastUrl = this.queryUrl + i;
				getData(this.lastUrl);
			}
			str += i + "&nbsp;&nbsp;&nbsp;";
		}
		if (this.pageStack[i] && this.pageStack[i].RECORD)
		{
			//alert('maxPageNum: '+i)
			this.pageStackMax = i;
		}
	}
	
	// Set flag to indicate stack has been modified
	this.rebuildSlideShowData = true;
	
	// DEBUG: Write out what we have in the stack
	if (this.debug) document.getElementById('stack').innerHTML = str;
}

// Update the page number depending upon which direction we want to go in
// Also triggers HTML generation and stack management
PoB.prototype.navigateGalleries = function (dir, step)
{
	// Work out what the next page number should be
	var x;
	if (dir == 'prev')
	{
		x = this.page - step; 
	}
	else if (dir == 'next')
	{
		x = this.page + step; 
	}
	else alert('Navigation error');

	// Check the user isn't out-running us
	if (typeof(this.pageStack[x]) != 'object') 
	{
		alert('Please wait for a moment...');
		return;
	}
	else // All seems good. Update the page number and draw gallery out
	{
		this.page = x;
		this.drawGallery();
		this._updateStack();
	}
}


// To generate the HTML for the gallery screen
PoB.prototype.drawGallery = function ()
{
	var str = '';
	var imageDirSub;
	
	if (this.pageStack[this.page].total_hits == 0)
	{
		str += '<br /><br /><br />';
		str += '<p>Your search returned no results.</p>';
		str += '<p>Please <a href="javascript:void(0)" onclick="myPoB.changeMode(\'search\');">search again</a>';
		str += 'or you can <a href="/arts/apictureofbritain/competition.shtml">submit your own photo</a>.</p>';
		str += ''
	}
	else
	{
		str += '<p>Click on an image to view it full size or start a new <a href="javascript:void(0)" onclick="myPoB.changeMode(\'search\');">search</a>.</p>';
		var pageNav = this._drawGalleryNavigation();
		
		str += pageNav;
		
		// Draw out images
		str += '<br /><table border="0" cellpadding="0" cellspacing="0"><tr>';
		for (var i in this.pageStack[this.page].RECORD)
		{
			var j = this.pageStack[this.page].RECORD[i];
			
			if (this.dev) imageDirSub = '';
			else imageDirSub = '/' + j.COMP_REGION_WWW + '/' + j.COMP_THEME_WWW + '/' + j.IMAGE_DIR_NUM;
		
			str += '<td class="gallery" align="center" valign="middle">'; 
			str += '<a href="javascript:void(0)" onclick="myPoB.image='+i+'; myPoB.drawSlideShow();">';
			str += '<img src="'+ this.imageDir + imageDirSub +'/tn/' + j.IMAGE_ROOTNAME + '_tn.jpg" alt="" height="'+j.IMAGE_TN_HEIGHT_PX+'" width="'+j.IMAGE_TN_WIDTH_PX+'" />';
			str += '</a>';
			str += '</td>';
	
			if ((parseInt(i)+1)%this.columns == 0) str += '</tr><tr><td colspan="5">&nbsp;<br /><br /></td></tr><tr>';
			else str += '</td><td width="33">&nbsp;';
		}
		str += '</tr></table>';
		
		str += pageNav;
	}

	// Now write out all the HTML we have generated
	this.galleryDiv.innerHTML = str;
}


// To generate the HTML for the gallery page navigation links
PoB.prototype._drawGalleryNavigation = function ()
{
	var str = '<table border="0" cellspacing="0" width="100%"><tr>';
	if (this.page > 1)
	{
		str += '<td width="25%"><div class="navHolder"><a href="javascript:void(0)" onclick="myPoB.navigateGalleries(\'prev\', 1);" class="btnWhite">Previous&nbsp;Page</a></div></td>';
	}
	else str += '<td width="25%"></td>';
	//str += '<td align="center">Page ' + this.page + ' of ' + this.pageStack[this.page].pages_total + '</td>';
	str += '<td align="center" class="pagination">Page&nbsp;&nbsp;';

	var dir, step;
	
	for (var i=(this.page-this.paginationSize);i<=(this.page+this.paginationSize);i++)
	{
		if (i <= this.pageStack[this.page].pages_total && i > 0)
		{
			if (i == this.page)
			{
				str += '<strong>'+i+'</strong>&nbsp;&nbsp;&nbsp;' ;
			}
			else
			{
				dir = (i > this.page)?'next':'prev';
				step = (i > this.page)?i-this.page:this.page-i;
				str += '<a href="javascript:void(0)" onclick="myPoB.navigateGalleries(\''+dir+'\', '+step+');" class="pagination">'+i+'</a>&nbsp;&nbsp;&nbsp;' ;
			}
		}
	}
		


	str += '</td>';
	if (this.page < this.pageStack[this.page].pages_total)
	{
		str += '<td width="25%" align="right"><div class="navHolder"><a href="javascript:void(0)" onclick="myPoB.navigateGalleries(\'next\', 1);" class="btnWhite">Next&nbsp;Page</a></div></td>';
	}
	else str += '<td width="25%"></td>';
	
	str += '</tr></table>';
	return str;
}


// To generate the HTML for the slideshow screen
PoB.prototype.drawSlideShow = function ()
{
	var imageDirSub;
	if (this.image == this.pageSize) 
	{
		this.page++
		j = this.pageStack[this.page].RECORD[0]; 
		this.image = 0;
	}
	else if (this.image == -1)
	{
		this.page--;
		j = this.pageStack[this.page].RECORD[this.pageSize-1];
		this.image = this.pageSize-1;
	}
	else 
	{
		var j = this.pageStack[this.page].RECORD[this.image];
	}

	var str = '';
	var str2 = '';
	
	if (this.dev) imageDirSub = '';
	else imageDirSub = '/' + j.COMP_REGION_WWW + '/' + j.COMP_THEME_WWW + '/' + j.IMAGE_DIR_NUM;
		
	str += '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>';
	
	str += '<td valign="top" width="25%"><br />';
	if (this.image > 0 || this.page > 1 ) str += '<a href="javascript:void(0)" onclick="myPoB.image='+(this.image-1)+'; myPoB.drawSlideShow();" class="btnWhite">Previous&nbsp;Photo</a>';
	str += '</td>';
	
	str += '<td align="center" width="50%"><br />';
	str += '	<a href="javascript:void(0)" onclick="myPoB.changeMode(\'gallery\');" class="btnWhite">Return&nbsp;to&nbsp;Selection</a><br /><br />';
	str += '</td>';

	str += '<td align="right" valign="top" width="25%"><br />';
	if (!(this.image == this.pageStack[this.page].RECORD.length-1 && this.page == this.pageStack[this.page].pages_total)) str += '<a href="javascript:void(0)" onclick="myPoB.image='+(this.image+1)+'; myPoB.drawSlideShow();" class="btnWhite">Next&nbsp;Photo<!-- ('+this.image+'|'+this.page+'|'+this.pageStack[this.page].pages_total+') --></a>';
	str += '</td>';
	str += '</tr></table>';
	
	str2 += '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>';
	str2 += '<td width="100" rowspan="2">&nbsp;</td>';
	str2 += '<td width="50%" valign="middle" align="center" class="slides"><img src="/f/t.gif" width="450" height="1" hspace="0" vspace="0" alt="" border="0" /><br />';
	str2 += '	<img src="' + this.imageDir + imageDirSub + '/web/' + j.IMAGE_ROOTNAME + '_web.jpg" height="' + j.IMAGE_WWW_HEIGHT_PX + '" width="' + j.IMAGE_WWW_WIDTH_PX + '" alt="" />';
	str2 += '</td>';
	str2 += '<td width="100" rowspan="2">&nbsp;</td>';
	str2 += '</tr><tr><td><br /><strong>'+((j.PERSON_REAL_NAME)?j.PERSON_REAL_NAME.toUpperCase():'')+'</strong><br />Camera:&nbsp;<strong>'+j.IMAGE_CAMERA_TYPE+'</strong>';
	str2 += '<br /><br /><strong class="fg_COL'+j.COMP_THEME_WWW+'">'+((j.IMAGE_CAPTION)?j.IMAGE_CAPTION.toUpperCase():'')+'</strong><br />'+j.IMAGE_DESCRIPTION+'<br /><br />';
	
	
	str2 += '<!-- Promos -->';
	str2 += '<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">';
	str2 += '<tr>';
	str2 += '	<td><div class="ratePromo"><strong>BE INSPIRED</strong><br /><a href="/arts/apictureofbritain/inspiration/">From the Tate and top photographers</a></div></td>';
	str2 += '	<td>&nbsp;&nbsp;&nbsp;</td>';
	str2 += '	<td><div class="ratePromo"><strong>HOW TO TAKE GOOD PHOTOS</strong><br /><a href="/arts/apictureofbritain/how_to/">Find out how to take better photos</a></div></td>';
	str2 += '</tr>';
	str2 += '</table><br />';
	str2 += '<!-- End promos -->';
	
	
	str2 += '</td></tr>';
	str2 += '</table>';
	
	str2 += '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>';
	str2 += '<td width="25%"><br />'; 
	str2 += '	<a href="javascript:void(0)" onclick="myPoB.changeMode(\'gallery\');" class="btnWhite">Return&nbsp;to&nbsp;Selection</a><br /><br />';
	str2 += '</td>';	
	str2 += '<td align="center"><div class="navHolder"><a href="/arts/apictureofbritain/feedback_pop_up.shtml?'+j.IMAGE_ID+'" onclick="popWin.open(\'/arts/apictureofbritain/feedback_pop_up.shtml?'+j.IMAGE_ID+'\');return false;" target="_blank" class="btnWhite">Contact Us</a></div></td>';
	str2 += '<td align="center"><div class="navHolder"><a href="/arts/apictureofbritain/send_to_a_friend_pop_up.shtml?'+j.IMAGE_ID+'" onclick="popWin.open(\'/arts/apictureofbritain/send_to_a_friend_pop_up.shtml?'+j.IMAGE_ID+'\');return false;" target="_blank" class="btnWhite">Send to a Friend</a></div></td>';
	str2 += '<td align="right" width="25%"><br /><a href="#top" class="btnWhite">Rate Photo</a><br /><br /></td>';
	str2 += '</tr></table>';
	
	this.pageTitleBg.className = 'boxHSite bg_COL'+j.COMP_THEME_WWW;
	this.slidesTopNavDiv.innerHTML = str;
	this.slidesDiv.innerHTML = str2;
	
	// Set this image ID in the log2results form
	this.l2rFormDiv.style.display = 'block';
	this.l2rResultsDiv.style.display = 'none';
	document.forms.l2r_rating.l2r_image_id.value = j.IMAGE_ID;
	//document.getElementById('l2r_image_id_label').innerHTML = j.IMAGE_ID;
	//document.getElementById('l2r_image_id_label1').innerHTML = j.IMAGE_ID;
	//alert(typeof(j.AVERAGE_RATING));
	if (typeof(j.AVERAGE_RATING)!='undefined' && j.AVERAGE_RATING != '') 
	{
		document.getElementById('l2r_image_average_rating').innerHTML = ', the current average is&nbsp;&nbsp;<strong>'+ (Math.round(j.AVERAGE_RATING * 10)/10) +'</strong>';
	}
	
	
	
	// Now make sure the slideshow screen is visible
	this.changeMode('slides');
}



// Handler is executed by returning HTTP requests
PoB.prototype.LocalHandler = function(pob)
{
	this.onLoad = function (r)
	{
		progressBar('off');
		//alert(r.agent.responseText);
		eval(r.agent.responseText);
		pob.pageStack[script_output.page] = script_output;
		
		// Redirect to gallery page if this is page 1
		if (script_output.page == 1) pob.changeMode('gallery');
		
		// Preload images
		var j = pob.pageStack[script_output.page].RECORD;
		for (var i in j)
		{
			j[i].bigImage = new Image();
			j[i].bigImage.src = pob.imageDir + '/web/' + j[i].IMAGE_ROOTNAME + '_web.jpg';
			j[i].thumbImage = new Image();
			j[i].thumbImage.src = pob.imageDir + '/tn/' + j[i].IMAGE_ROOTNAME + '_tn.jpg';
		}
		
		// DEBUG: Dump the stack object contents into obj2list();
		if (pob.debug) pob.debugDiv.innerHTML = bbcjs.obj2list(pob.pageStack, 'pageStack');
	}
	this.onError = function (r)
	{
		alert('HTTP Error: ' + r.agent.statusText);
	}
}
PoB.prototype.LocalHandler.prototype = new bbcjs.http.Handler();


// ########### Log2Results ###############

// On load handler for asynchronous requests
PoB.prototype.L2RLocalHandler = function (pob)
{
	this.onLoad = function (r)
	{
		progressBar('off');
		pob.l2rFormDiv.style.display = 'none';
		pob.l2rResultsDiv.style.display = 'block';
		document.forms.l2r_rating.l2r_submit.disabled = false;
	}
	this.onError = function (r)
	{
		alert('HTTP Error: ' + r.agent.statusText);
	}	
}
PoB.prototype.L2RLocalHandler.prototype = new bbcjs.http.Handler();


