 var flickrapikey = 'd731de0386df046dd761e777e5d0aaca';
var siteurl = 'http://www.themastersofphotography.com/';
var firstImageID = 0;
var currentImageID = 0;
var previousScrollLeft = 0;
var galleryTimeout;
var currentLimit = 40;
var currentSort = 'mostRecent';
var currentView = 'gallery';
var currentSortLinkId = '';
var currentViewLinkId = '';
var nextPage = 0;
var retrylimit = 5;
var tries = 0;
var myCookies = new Object();
var votedSubmissions = new Array();
var mapMarkers = new Array();
var mapDragging = false;
var arraytmp;
// Globally accessible version of the user's ID
var guid;

// Quick cookie setter
function setCookie(c_name,value,expiredays){
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + expiredays );
	document.cookie = c_name + "=" + escape( value ) + ( (expiredays==null) ? "" : ( ";expires="+exdate.toUTCString() ) )+";path=/";
}

function popCookies() {
// Pop cookies
var pairStrings = document.cookie.split( ';' );
for( var key in pairStrings ){
    var parts = $.trim( pairStrings[key] ).split( '=' );
    myCookies[parts[0]] = parts[1];
}
}
popCookies();

// Pop user id from cookie for from server
function popUIDAndVotes(){
	if( undefined == myCookies['mop_uid'] ){
		$.post( siteurl, { 'cmd':'MCACreateUser', 'nosurround':'true' }, 	
			function( data ){ 
				setCookie( 'mop_uid', data, 9999 );
				afterUIDFetched( data );
			} );
	}else{
		afterUIDFetched( myCookies['mop_uid'] );
	}
}

function afterUIDFetched( uid ){
	guid = uid;
	$('input#userID').val( uid );

	if( undefined == myCookies['mop_votelist_cache'] ){
			$.post( siteurl, { 'cmd':'MCAGetVotedPhotoListForUser', 'userID':uid, 'nosurround':'true' }, 	
				function( data ){ 
					setCookie( 'mop_votelist_cache', data, 9999 );
					afterVoteListFetched( data );
				} );
	}else{
		afterVoteListFetched( myCookies['mop_votelist_cache'] );
	}
}

function afterVoteListFetched( rawVoteList ){

	rawVoteList = unescape( rawVoteList );
	if( rawVoteList != 'NONE' ){
		votedSubmissions = rawVoteList.split(',');
	}
	markVotes();
}

function markVotes(){
	for( var key in votedSubmissions ){
		markVoted( votedSubmissions[key] );
	}
}

function markVoted( submissionID ){
	$( '.vote_'+submissionID ).addClass( 'voted' );
	$( '.vote_'+submissionID ).children().first().html( "<br><br>vote<br>counted" );
	$( '.vote_'+submissionID ).children().first().unbind( 'onclick' );
	$( '.vote_'+submissionID ).children().first().attr( 'onclick', 'return false;' );
	$( '.vote_'+submissionID ).children().first().bind( 'click', function(){ return false; } );
}

var voteCallbackWrap = function(submissionID) {
    return function(data) {
	if( data != 'OK' ){
		$( '.vote_'+submissionID ).addClass( 'votefailed' );
		return;
	}
	votedSubmissions.push( submissionID );
	setCookie( 'mop_votelist_cache', votedSubmissions.join(','), 9999 );
	markVoted( submissionID );
	//Add one to the votecount immediately:
	$('.vote_'+submissionID).prev().children(0).html( ( parseInt( $('.vote_'+submissionID).prev().children(0).html() , 10 ) + 1 ) )
    };
};

function vote( submissionID ){
	$.post( siteurl, {'cmd':'MCARecordVote', 'nosurround':'true', 'userID':guid, 'submissionID':submissionID }, voteCallbackWrap( submissionID ) ); 
}




$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}

function loadScript(src) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = src;
  document.body.appendChild(script);
}

function appendScriptBlock(contents) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  if ( script.canHaveChildren == false ) { //IE
   script.text = contents;
  } else {
   script.appendChild(document.createTextNode(contents));
  }
  document.body.appendChild(script);
}

function verifyAge() {
        if ( $.urlParam('agecheck') === '1' ) {
         if (myCookies['mop_uid'] === undefined) {
          //this condition should never get hit - mop_uid should always be set by this point
          $.post( siteurl, 
                { 'cmd':'MCACreateUser', 
                  'nosurround':'true' 
                }, 	
                function( data ){ 
                        setCookie( 'mop_uid', data, 9999 ); 
                        location.reload;	
                }
          );
         } else if ( $.urlParam('muid') == hex_md5(myCookies['mop_uid']) ) {
          setCookie('mop_age_verify','1');
         } else {
          ageVerification.createOverlay();
         }
        } else if ( $.urlParam('agecheck') === '0' ) {
         ageVerification.createOverlay();
        } else {
         location.href = 'http://www.blog.themacallan.com/mopageverify.php?uid='+myCookies['mop_uid'];
        }
        return false;
}

  //******************************//
 //* initialisation begins here *//
//******************************//

$(document).ready(function() { 

 $.ajaxSetup ({
     // Disable caching of AJAX responses
     cache: false
 });

 if ( undefined == myCookies['mop_age_verify'] ) {
        //if no uid cookie then first visit to MoP so create uid
        if ( undefined == myCookies['mop_uid'] ) {
                $.post( siteurl, 
                        { 'cmd':'MCACreateUser', 
                          'nosurround':'true' 
                        }, 	
                        function( data ){ 
                                setCookie( 'mop_uid', data, 9999 ); 
                                popCookies();
                                verifyAge();	
                        }
                );
        } else {
                verifyAge();
        }
 }

	//$('#container').hide();
	
	//select box replacement:
	if ( jQuery().sb ) {
	       $('select').removeClass('thin').sb( {
//	        ddCtx: function() { return $(this).closest("form"); },
         fixedWidth: false
	       } );
	}
	
	//fixes
	$('input[value="next"]').css('background-position','42px 0');
	$('input[value="next"]').css('padding-bottom','1px');
	$('#breadcrumb span a').last().css('color','#fff');
	$('.mop input[type="submit"]').val('Submit');
	
	if ( $.urlParam('McacompetitionformHandler0') == 'MCAEnterCompetitionPage4' ) {
	 $('a.go_to_gallery').before('<div id="fb-root"></div>');
	}
	
	if ( $.urlParam('cmd') == 'SubmissionDetail' ) {
        $('.imagedetail_right_2').hide();
		//loadScript('http://www.themastersofphotography.com/fancybox.js/s19/');
		$('h2').addClass('small').css('margin-top', '20px');
		$('h5').addClass('tradegothic');
		$('#main a:first').remove();
		$('h2:first').before('<a onclick="javascript:history.go( -1 );return false;" href="#" class="back">back</a>');
		$('h2').last().addClass('image_detail_title').css( { 'width':'100%','clear':'right' } );
		$('h6').filter(':first').before('<h5 class="tradegothic">About the image</h5>');
//		$('.imagedetail_right').append('<hr><a class="reportphoto" href="#">Report photo</a><span class="sharewidgets tradegothic">Share this:<a rel="external" title="Share on Facebook" href="http://www.facebook.com/sharer.php?u=' + window.location.href + '&t=The%20Macallan%20Masters%20of%20Photography"><img src="http://www.themastersofphotography.com/agile_assets/2/facebookblack.png"></a><a rel="external" href="http://twitter.com/home?status=Currently reading ' + window.location.href + '" title="Share on Twitter"><img src="http://www.themastersofphotography.com/agile_assets/2/twitterblack.png"></a></span><hr>');
		$('.imagedetail_right').append('<hr><span class="sharewidgets"><span class="st_sharethis" st_url="' + location.href + '" st_title="The Macallan Masters of Photography Competition 2010" displayText="ShareThis"></span></span><hr>');

//		loadScript("http://w.sharethis.com/button/buttons.js");
		appendScriptBlock("stLight.options({publisher:'8c73f7d9-15ef-4fc4-a477-bcf5a7b4f133'});");
		$('.imagedetail_right_2 h5').addClass('tradegothic');
		$('.imagedetail_left_2 hr').addClass('thin');
		$('.imagedetail_left_2 hr').last().removeClass('thin');
		$('textarea').after('<div style="width:100%;clear:both;"></div>');
		$('label[for$="ptIn"]').css( { 'clear' : 'none', 'margin-bottom' : '20px', 'padding' : '3px 0 0 8px', 'width' : '350px'} );
//		$('#login').css( { 'background-image' : 'url("http://www.themastersofphotography.com/agile_assets/2/bigfbbutton.png")', 'width' : '192px', 'height' : '39px' } );
		$('#twitter_login').after('<div id="fb-root"></div>');
		//$('.imagedetail_left a').click( function () { $.openDOMWindow( { 'width': 1057, 'height': 784, 'windowSourceURL':this.href, 'windowSource':'iframe' } );return false; } );
// fancybox
 	if (jQuery().fancybox) {
	 	$('.imagedetail_left a').fancybox({
		 	'titleShow' : true, 
    'overlayShow' : true,
    'overlayColor' : '#000'
	 	});
 	}
		$('.imagedetail_left').append( $('#previous_submission').addClass('arrow back') );
		$('.imagedetail_left').append( $('#next_submission').addClass('arrow forward') );
		
		//twitter login
		twttr.anywhere(
		 function (T) {
		  $("#twitter_login").bind("click", function () {
		   T.signIn(); 
		   T.bind("authComplete", function (e,user) {
		    twitterAuthComplete(user); 
		   } );
		  }); 
		  
		  if ( T.isConnected() ) {
		   twitterAuthComplete(T.currentUser);
		  } else {
		   $('#twitter_login').show('fast');
		  }
		 }
		);

		// add report photo form
		var reportPhoto = '<div style="display:none;">';
		reportPhoto += '<form id="reportphotoform" class="mop platinumprints" method="POST" action="">';
		reportPhoto += '<input type="hidden" name="cmd" value="SubmitFormToMail">';
		reportPhoto += '<input type="hidden" name="groupID" value="2">';
		reportPhoto += '<input type="hidden" name="photoID" value="' + $.urlParam('id') + '"';
		reportPhoto += '<label for="name">Your name:</label>';
		reportPhoto += '<input id="name" name="name" type="text" class="thin required">';
		reportPhoto += '<label for="email">Your email address:</label>';
		reportPhoto += '<input id="email" name="email" type="text" class="thin required email">';
		reportPhoto += '<label for="message">Please tell us why you are reporting this photo:</label>';
		reportPhoto += '<textarea style="width:99%;" name="message" class="thin required"></textarea>';
		reportPhoto += '<hr><input type="submit" value="submit">';
		reportPhoto += '</form></div>';
/*		$('body').append(reportPhoto);

		if (jQuery().fancybox) {
 		$('a#reportphoto').fancybox({
	   'scrolling'		: 'no',
	   'titleShow'		: false,
	   'onClosed'		: function() { $("#reportphotoform").hide(); }
   });
  }
*/  
    $('div.vote').remove();
	}

	(function(){
	  // if firefox 3.5+, hide content till load (or 5 seconds) to prevent FOUT
	  var d = document, e = d.documentElement, s = d.createElement('style');
	  if (e.style.MozTransform === ''){ // gecko 1.9.1 inference
	    s.textContent = 'body{visibility:hidden}';
	    e.firstChild.appendChild(s);
	    function f(){ s.parentNode && s.parentNode.removeChild(s); $('#container').fadeIn(500) }
	    addEventListener('load',f,false);
	    setTimeout(f,5000); 
	  } else {
	  	setTimeout( f, 1000 );
	  }
	})();
	
	// form validation
	if (jQuery().validate) {
	  $('form.competition').validate();
	  $('form.platinumprints').validate();
	  $('form.comment').validate();
	}
	
	//character limit
	$('form.competition textarea').before('<div id="textcounter"></div>').limit( { id_result : 'textcounter' } );
	$('input#title').before('<div id="titlecounter"></div>').limit( { id_result : 'titlecounter', limit: 28 } );

 if ( $('#file').length ) {

        var swfLoaded = function () {
         $('#file').remove();
        };
        //replace the file upload with swfupload
        $('#file').after('<span class="right" id="swfuploadbutton"></span><br><br>');
        $('#photopreview').after('<span id="uploadprogress"></span>');
        var swfu = new SWFUpload( {
          upload_url : siteurl,
          post_params : { "cmd" : "MCAFlashUploadHandler", "PHPSESSID" : myCookies['agile'], 'nosurround' : 'true' },
          flash_url : "http://www.themastersofphotography.com/agile_assets/10/swfupload.swf",
          flash9_url : "http://www.themastersofphotography.com/agile_assets/10/swfupload_fp9.swf",
          button_image_url : "http://www.themastersofphotography.com/agile_assets/2/browsebutton.1.png",
          button_placeholder_id : "swfuploadbutton",
          button_width : 79,
          button_height : 19,
          file_size_limit : "2 MB",
          file_dialog_complete_handler : filedialogComplete,
          file_queue_error_handler : queueErrorHandler,
          upload_start_handler : fileuploadStart,
          upload_progress_handler : fileuploadProgress,
          upload_success_handler : fileuploadComplete,
          upload_complete_handler: fileuploadFinished,
          upload_error_handler : fileuploadError,
          swfupload_loaded_handler: swfLoaded,
          file_post_name : "upload",
          file_types : "*.jpg;*.jpeg",
          file_types_description : "Photos",
          file_upload_limit : 6,
          prevent_swf_caching : false,
          debug : false
        } );

 }

	if ( document.getElementById('fb-root') ) {
	  loadScript('http://static.ak.fbcdn.net/connect/en_US/core.js?'+Math.floor(Math.random()*500) );

	setTimeout( "initFB()", 2000); //Fixes a weird error with IE8 and Chrome
	}

	if ( document.getElementById('gmap') ) {
		setTimeout( "loadScript('http://maps.google.com/maps/api/js?sensor=false&callback=initMap')", 4000);
	}
	
	if ( document.getElementById('flickr') ) {
		//$('p:contains("Flickr")').html('<p>Enter your Flickr username and click on the Flickr button to select an image from your public photostream.</p>').after('<input type="text" id="flickruser" name="flickruser"><input type="hidden" id="flickruid" name="flickruid"><button id="flickr" type="button">Flickr</button><div id="flickrphotos" style="display:none;"></div>');

		$('#flickr').bind('click', function () { 
			if ( document.getElementById('flickruser').value ) {
				loadScript('http://www.flickr.com/services/rest/?method=flickr.people.findByEmail&jsoncallback=getFlickrPhotos&find_email=' + document.getElementById('flickruser').value + '&format=json&api_key=' + flickrapikey );
			}
		});
		$('#flickruser').css( {'width':'200px','vertical-align':'middle'} ).bind("click", function(e) {
				$('#flickruser').animate({background:0},'slow');
		});
		$('#flickruser').bind("blur", function(e) {
		  if (document.getElementById('flickruser').value == '') {
		    $('#flickruser').css('background-image', "url('http://www.themastersofphotography.com/agile_assets/2/flickrhint.png')");
		  }
		});
		$('#flickruser').bind("keypress", function(e) {
		  var code=e.charCode || e.keyCode;
		  if (code==13 &&  document.getElementById('flickruser').value ) {
			loadScript('http://www.flickr.com/services/rest/?method=flickr.people.findByEmail&jsoncallback=getFlickrPhotos&find_email=' + document.getElementById('flickruser').value + '&format=json&api_key=' + flickrapikey );
			return false;
		  }
		});
		
	}

	// hide add another image form
	if ( 
	    ( $('.sub_preview_small_container').length > 0 ) && 
	    ( $.urlParam('editKey') === 0 ) && 
	    ( $.urlParam('McacompetitionformHandler0') != 'MCAEnterCompetitionPage4' ) 
	   ) {
		$('.submission_form_box_type_0').hide().nextAll().hide();
		$('.submission_form_box_type_0').before('<p class="addmore">Remember, you can enter up to five photos. Do you want to enter another photo now?<a id="enteranother" href="#">Enter another</a></p>');
		$('#enteranother').bind('click', function () { 
			$('.submission_form_box_type_0').show('fast').nextAll().show('fast'); 
			setTimeout( "loadScript('http://maps.google.com/maps/api/js?sensor=false&callback=initMap')", 2000);
			//loadScript('http://static.ak.fbcdn.net/connect/en_US/core.js?'+Math.floor(Math.random()*500) );
			//$('#login').show(); //for IE8 :-(
			$('#enteranother').parent().remove(); 
			return false; 
		} );
	}
	
	if ( document.getElementById('galleryview') ) {
		// get top ten (most votes) list of images and draw them in the #topten div
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostVotes: '1', limit: '20' }, function(data) { currentLimit = 20; drawGallery(data,'#topten','TT'); } );
		// get default (most recent) list of images and draw them in the #galleryview div
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '40' }, function(data) { currentLimit = 40; drawGallery(data,'#galleryview','',1); } );
		//wireup the links
		wireUpGalleryLinks();
		currentSortLinkId = '#mostrecent';
		currentViewLinkId = '#viewgallery';
		
		// check anchor for back button handling
		var current_anchor = null;
		if (current_anchor != document.location.hash)
     {
          current_anchor = document.location.hash;
          switch (current_anchor) {
                case '#viewmap':
                  setTimeout("$('#viewmap').trigger('click')",2000);
                break;
                case '#viewslideshow':
                  setTimeout("$('#viewslideshow').trigger('click')",1000);
                break;
                case '#mostvotes':
                  $('#mostvotes').trigger('click');
                break;
                case '#mostcomments':
                  $('#mostcomments').trigger('click');
                break;
                case '#viewgallery':
                //default page view
                break;
                case '#mostrecent':
                //default page view
                break;
          }
     }
     
	}
	
	if ( document.getElementById('homecarousel') ) {
		// get home carousel images and draw them in #homecarousel
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', homepagePicks: '1', limit: '20' }, function(data) { drawCarousel( data, '#homecarousel' ); } );
//		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '30' }, function(data) { drawCarousel( data, '#homecarousel' ); } );
	}
	
 //$('a[rel="external"]').attr('target','_blank');
 $('a[rel="external"]').click(function(){ window.open($(this).attr('href')); return false; });
 
 $('#menu_mid__sid_1 a').html("<br>Home");

 } );
  //****************************//
 //* initialisation ends here *//
//****************************//

function twitterAuthComplete(user) {
        var currentUser;
        var userName;
        var screenName;
        var emailAddress;
        var userId;

        currentUser = user;
        userName = currentUser.data('name');
        screenName = currentUser.data('screen_name');
        userId = currentUser.data('id');
        emailAddress = screenName + '@twitter.com';
        $('#twitter_login').after('<button id="twitter_disconnect">Sign out of Twitter</button>');
        $('#twitter_login').hide('fast');
        $('#twitter_disconnect').bind('click', function() { twttr.anywhere.signOut(); $('#twitter_login').show('fast'); $('#twitter_disconnect').remove(); } );
        $('#firstName').val(userName);
        $('#email').val(emailAddress);
        $('#twitterID').val(userId);
}
function queueErrorHandler(file, errorCode) {
    if (errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
        alert("This file is larger than 2MB.\nPlease ensure that your photo isn't more than 2 megabytes and does not exceed 2048 pixels in width or height.");
    }
}
function fileuploadComplete(file, server_data, receivedResponse) {
                if( server_data.indexOf( 'ERROR' ) == -1 ){
                        // Success
                        $('#photopreview').attr('src', server_data );
                }else{
                        // Show error
                }
}
function fileuploadFinished(file) {
         $('#uploadprogress').text('Uploaded: ' + file.name).removeClass('error');
}
function filedialogComplete(numFilesSelected, numFilesQueued) {
 try {
  this.startUpload();
 } catch (ex) {
  this.debug(ex);
 }
}
function fileuploadStart(file) {
        $('#uploadprogress').text('upload started');
}
function fileuploadError(file, errorCode, message) {
	try {
	 $('#uploadprogress').addClass('error').text('Upload error. Please ensure your image file does not exceed the file size limit.');
//			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
	} catch (ex) {
        this.debug(ex);
    }
}
function fileuploadProgress(file, bytesLoaded, bytesTotal) {
 try {
   var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        $('#uploadprogress').text('Please wait while uploading... ' + percent + '% complete');
 } catch (ex) {
  this.debug(ex);
 }
}


function wireUpGalleryLinks() {
	var target = '#galleryview';

	$('#mostrecent').bind('click', function () {
		removeGalleryPages();
		$('#gallerytitle').text("All entries"); 
		toggleGalleryLinks('#mostrecent'); 
		toggleViewLinks('#viewgallery'); 
		$('#gallerymap').remove();
		$('.gallery').show('fast');
		$('.morephotos').show();
		nextPage = 0;
		$(target).animate({opacity:0},'fast'); 
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '40' }, function(data) { drawGallery(data,target,'',1); } ); 
		currentSort = 'mostRecent';
		window.location.hash = '#mostrecent';
		return false;
	} );
	$('#mostvotes').bind('click', function () {
		removeGalleryPages();
		$('#gallerytitle').text("Most votes"); 
		toggleGalleryLinks('#mostvotes'); 
		toggleViewLinks('#viewgallery'); 
		$('#gallerymap').remove();
//		$('.gallery:last').show();
//		$('.gallery:first').hide('fast');
		$('.morephotos').show();
		nextPage = 0;
		$(target).animate({opacity:0},'fast'); 
		$.get(siteurl+'the-masterclass-gallery/s17/', { nosurround: 'true', cmd: 'MCAPhotoList', mostVotes: '1', limit: '40' }, function(data) { drawGallery(data,target); } ); 
		currentSort = 'mostVotes';
		window.location.hash = '#mostvotes';
		return false;
	} );
	$('#mostcomments').bind('click', function () {
		removeGalleryPages();
		$('#gallerytitle').text("Most comments"); 
		toggleGalleryLinks('#mostcomments'); 
		toggleViewLinks('#viewgallery'); 
		$('#gallerymap').remove();
//		$('.gallery:last').show();
//		$('.gallery:first').hide('fast');
		$('.morephotos').show();
		nextPage = 0;
		$(target).animate({opacity:0},'fast'); 
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostComments: '1', limit: '40' }, function(data) { drawGallery(data,target); } ); 
		currentSort = 'mostComments';
		window.location.hash = '#mostcomments';
		return false;
	} );
	
	$('#viewgallery').bind('click', function () {
		toggleViewLinks('#viewgallery'); 
		removeGalleryPages();
		$('#gallerymap').remove();
		$('.gallery').show();
		$('.morephotos').show();
		nextPage = 0;
		$(target).animate({opacity:0},'fast'); 
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '40' }, function(data) { currentLimit = 40; drawGallery(data,'#galleryview','',1); } );
		currentView = 'gallery';
		window.location.hash = '#viewgallery';
		return false;
	} );		
	
	$('#viewslideshow').bind('click', function () {
		toggleViewLinks('#viewslideshow'); 
		removeGalleryPages();
		$('#gallerymap').remove();
		$('.gallery').show();
		$('.morephotos').show();
		nextPage = 0;
		//$(target).animate({opacity:0},'fast'); 
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '66' }, function(data) {
		      currentLimit = 66;
		      arraytmp = jQuery.parseJSON(data.replace(/(\r\n|\r|\n)/g, "<br />") );
		      $("#container").after('<div id="pleasewait" style="position:fixed;top:0;left:0;height:100%;width:100%;z-index:1000;background-color:#333;opacity:0;"><h2 style="border-bottom:0;margin: 25% auto;text-align:center;" class="tradegothic">Loading photos, please wait...</h2></div>');
		      $('#pleasewait').animate({opacity:0.8},'fast');
		      getAllPhotos();
  } );
		
		currentView = 'slideshow';
		window.location.hash = '#viewslideshow';
		return false;
	} );		

	$('#viewmap').bind('click', function () {
		toggleViewLinks('#viewmap'); 
		removeGalleryPages();
		$('.gallery').hide();
		$('.morephotos').after('<div id="gallerymap"></div>');
		$('.morephotos').hide();
		// load gmaps javascript, calling initGalleryMap when loaded, which calls drawMap
		loadScript('http://maps.google.com/maps/api/js?sensor=false&callback=initGalleryMap'); 
		//loadScript('http://www.themastersofphotography.com/markerclusterer.js/s32/');
		nextPage = 0;
		$(target).animate({opacity:0},'fast'); 
		currentView = 'map';
		window.location.hash = '#viewmap';
		return false;
	} );		
	
	//link next page button
	$('.morephotos a').bind('click', function () {
		nextPage++;
		$('.morephotos').animate({opacity:0},'fast');
		//$(target).animate({opacity:0},'fast');
		var nextPageID = 'galpage' + nextPage;
		$(target).parent().append('<div id="' + nextPageID + '" class="extrapage"></div>');
		switch (currentSort) {
			case 'mostRecent':
			$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '40', page: nextPage }, function(data) { 
				drawGallery(data,'#' + nextPageID);
				fadeInMorePhotos();
			 } );
			break;
			case 'mostVotes':
			$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostVotes: '1', limit: '40', page: nextPage }, function(data) { 
				drawGallery(data,'#' + nextPageID); 
				fadeInMorePhotos(); } );
			break;
			case 'mostComments':
			$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostComments: '1', limit: '40', page: nextPage }, function(data) { 
				drawGallery(data,'#' + nextPageID); 
				fadeInMorePhotos(); } );
			break;
		}
		return false;
	} );
}

function getAllPhotos() {
//AF 31/1/11 - for slideshow
        var tmpHolder;
//        if (arraytmp.length % currentLimit == 0 || true == true) { //AF testing
		              nextPage++;
		              $.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: '66', page: nextPage }, function(moredata) {
		                      tmpHolder = jQuery.parseJSON(moredata.replace(/(\r\n|\r|\n)/g, "<br />") );
		                      if (tmpHolder != null) {
		                              arraytmp = arraytmp.concat(tmpHolder);
		                              if (nextPage < 3) { //AF 31/1/11 - added arbitrary limit for photos - is too slow otherwise
        		                              getAllPhotos();
        		                      } else {
        		                      		      drawSlideshow(arraytmp); 
        		                      		      $("#pleasewait").remove();
                		                      $('a[href="#imgdetail'+firstImageID+'"]').trigger('click');
        		                      }
		                      } else { //AF 31/1/11 - previous code to catch end of entire photo list
		                      		      drawSlideshow(arraytmp); 
		                      		      $("#pleasewait").remove();
        		                      $('a[href="#imgdetail'+firstImageID+'"]').trigger('click');
		                      }
		              } );
//		      }
}

function removeGalleryPages() {
	$('.extrapage').remove();
}

function fadeInMorePhotos() {
	$('.morephotos').animate({opacity:1},'fast');
}

function initGalleryMap() {
	var latLng = new google.maps.LatLng(33.0, 17.0);
	$('#gallerymap').css( { 'width' : '950px', 'height' : '600px' } );
	var map = new google.maps.Map(document.getElementById('gallerymap'), {
		zoom: 2,
		center: latLng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	
	var photoLimit = 10;
	var returnedData;
/*	switch (currentSort) {
		case 'mostRecent':
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostRecent: '1', limit: 75 }, function(data) { drawMap(data,map); } ); 
		break;
		case 'mostVotes':
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostVotes: '1', limit: 75 }, function(data) { drawMap(data,map); } ); 
		break;
		case 'mostComments':
		$.get(siteurl, { nosurround: 'true', cmd: 'MCAPhotoList', mostComments: '1', limit: 75 }, function(data) { drawMap(data,map); } ); 
		break;
	}
*/

	var listener = google.maps.event.addListener(map, 'zoom_changed', function(){
  mapMoved(map,photoLimit);
 });
	var listener = google.maps.event.addListener(map, 'dragend', function(){
  mapMoved(map,photoLimit);
//      google.maps.event.removeListener(listener);
 });
 mapMoved(map,photoLimit);
}

function mapMoved(map,photoLimit) {
	 showMapLoadingMessage();
  clearMarkers();
  var bounds = map.getBounds();
  if (bounds === undefined ) { bounds = new google.maps.LatLngBounds( new google.maps.LatLng(-180,-90), new google.maps.LatLng(180,90) ); }
	 var minLat = ( bounds.getSouthWest().lat() < bounds.getNorthEast().lat() ) ? bounds.getSouthWest().lat() : -180;
	 var maxLat = ( bounds.getSouthWest().lat() > bounds.getNorthEast().lat() ) ? 180 : bounds.getNorthEast().lat();
	 var minLong = ( bounds.getSouthWest().lng() < bounds.getNorthEast().lng() ) ? bounds.getSouthWest().lng() : -90;
	 var maxLong = ( bounds.getSouthWest().lng() > bounds.getNorthEast().lng() ) ? 90 : bounds.getNorthEast().lng();
	 var sqMinLat; var sqMaxLat; var sqMinLon; var sqMaxLon;
	 var rowCount = 4;
	 var colCount = 6;
	 //split map into six squares and draw each one
	 for (var row=0;row<rowCount;row++) {
	       for (var col=0;col<colCount;col++) {
	               sqMinLat = minLat + ( ( maxLat - minLat ) / colCount ) * ( col );
	               sqMaxLat = minLat + ( ( maxLat - minLat ) / colCount ) * ( col + 1 );
	               sqMinLon = minLong + ( ( maxLong - minLong ) / rowCount ) * ( row );
	               sqMaxLon = minLong + ( ( maxLong - minLong ) / rowCount ) * ( row + 1 );
	               
                $.get(siteurl, 
        		      { nosurround: 'true', 
        		      cmd: 'MCAPhotoList', 
        		      byLatLong: 'true', 
        		      latMin: sqMinLat.toFixed(6), 
        		      latMax: sqMaxLat.toFixed(6), 
        		      longMin: sqMinLon.toFixed(6), 
        		      longMax: sqMaxLon.toFixed(6), 
        		      limit: photoLimit }, 
        		      function(data) { 
        		              hideMapLoadingMessage();
        		              drawMap(data,map); 
        		      } ); 
        	               
	       }
	 }
}

function showMapLoadingMessage() {
        $('#gallerymap').append('<div id="maploading" style="opacity:0;position:absolute;width:950px;height:600px;z-index:10;background-color:grey;"><p style="font-size:1.5em;margin:25% auto;text-align:center;">Loading photos...</p></div>');
        $('#maploading').animate({opacity:0.8},'fast');
}
function hideMapLoadingMessage() {
        $('#maploading').animate({opacity:0},'fast');
        $('#maploading').remove();
}
function drawMap(data,map) {
	//var mgr = new MarkerManager(map);
	var maphtml = '';
	var photos = jQuery.parseJSON(data.replace(/(\r\n|\r|\n)/g, "<br />") );
	var shadow = new google.maps.MarkerImage('http://www.themastersofphotography.com/agile_assets/2/map-shadow.png',
	       new google.maps.Size(48, 55),
        new google.maps.Point(0,0),
        new google.maps.Point(24, 55)
 );
 if (photos) {
	for (var i=0;i<photos.length;i++) {
	 var photo = photos[i];
		var marker = new google.maps.Marker();
		var customicon = new google.maps.MarkerImage(photo[3],
        null,
        new google.maps.Point(0,0),
        new google.maps.Point(16, 49),
        new google.maps.Size(32 ,38)
  );
  if ( photo[15] != 0 && photo[16] != 0 ) {
 		var latLng = new google.maps.LatLng(photo[15], photo[16]);
	  
	 	marker = new google.maps.Marker({
		 	position: latLng,
	 		title: photo[7],
 			shadow: shadow,
	 		map: map,
	 		icon: customicon
	 	});
	 	mapMarkers.push(marker);
	 	bindMarkerClick(marker,map,'?cmd=SubmissionDetail&id=' + photo[0]);
	 }
	}
	}
}
function clearMarkers() {
        if (mapMarkers) {
                for (i in mapMarkers) {
                        mapMarkers[i].setMap(null);
                }
                mapMarkers.length = 0;
        }
}
function bindMarkerClick(marker,map,url) {
		google.maps.event.addListener(marker, 'click', function(o) {
			window.location = url;
		});
}

function drawCarousel(data,target) {
	var carouselhtml = '';
	var captionhtml = '';
	var photos = jQuery.parseJSON(data.replace(/(\r\n|\r|\n)/g, "<br />") );
	//shuffle it up a bit
	photos.sort(function() {return 0.5 - Math.random()});
	carouselhtml += '<div class="wrapper">';
	carouselhtml += '  <ul>';
	for (var i=0;i<photos.length;i++) {
		var photo = photos[i];
		carouselhtml += '    <li>';
		carouselhtml += '      <div class="imagewrap">';
		carouselhtml += '        <a id="img' + photo[0] + '" href="?cmd=SubmissionDetail&id=' + photo[0] + '">';
		carouselhtml += '          <img src="' + photo[17] + '">';
		carouselhtml += '        </a>';
		carouselhtml += '      </div>';
		carouselhtml += '      <div class="caption" class="left">';
		carouselhtml += '        <div class="left">';
		carouselhtml += '          <h5>' + photo[7] + '</h5>';
		carouselhtml += '          <p>By ' + photo[8] + ' ' + photo[9] + '</p>';
		carouselhtml += '        </div>';
		carouselhtml += '        <div class="right">';
		carouselhtml += '          <div class="comment icon left"><a href="?cmd=SubmissionDetail&id=' + photo[0] + '"><p> </p>' + photo[2] + '</a></div>';
		carouselhtml += '          <div class="votecount icon left"><p>' + photo[1] + '</p>votes</div>';
//		carouselhtml += '          <div class="yellow vote icon left vote_' + photo[0] + '"><a href="#" onclick="vote( '+photo[0]+' ); return false;"><p> </p>vote</a></div>';
		carouselhtml += '        </div>';
		carouselhtml += '      </div>';
		carouselhtml += '    </li>';
	}
	carouselhtml += '  </ul>';
	carouselhtml += '</div>';
	
	$(target).html(carouselhtml).fadeIn('fast');
	
	popUIDAndVotes();
	
	$('#container').show(); //try to fix IE
	$('.carousel').carousel();
	$('.caption').css('padding','0px');$('.caption').css('padding','5px'); // try to fix chrome
	galleryTimeout = setTimeout( "carouselSlideshow()", 5000);
}

function carouselSlideshow() {
 clearTimeout(galleryTimeout);
	$('a.forward').click();
	galleryTimeout = setTimeout( "carouselSlideshow()", 4000);
}

function toggleGalleryLinks(clickedLinkId) {
	$(currentSortLinkId ).removeClass('selected');
	$(clickedLinkId).addClass('selected');
	currentSortLinkId = clickedLinkId;
}

function toggleViewLinks(clickedLinkId) {
	$(currentViewLinkId).removeClass('selected');
	$(clickedLinkId).addClass('selected');
	currentViewLinkId = clickedLinkId;
}

function galleryCaptionLinks() {
	if (jQuery().fancybox) {
		$('a[rel="lightbox"]').fancybox({
		 'padding' : 5,
   'autoDimensions' : false,
   'autoScale' : false,
   'changeSpeed' : 0,
   'changeFade' : 0,
   'speedIn' : 100,
   'speedOut' : 100,
   'width' : 596,
   'height' : 600,
//   'transitionIn' : 'none',
//   'transitionOut' : 'none',
			'titleShow' : true, 
			'titlePosition' : 'inside',
   'overlayShow' : true,
   'overlayColor' : '#000',
   'showNavArrows' : true,
   'cyclic' : true,
			'titleFormat': galleryCaption,
			'onComplete' : function () { 
			     $('#fancybox-content').css( { 'width': '596px;', 'height': '520px', 'padding': '0', 'border-bottom': '0' } ); 
			     $('#fancybox-title').css( { 'margin':'0' } );
			     //if ( currentImageID == -1 ) {
			      $('.carousel').carousel(); 
			     //}
			     currentImageID = Math.ceil( ( $('ul li div a').index( $('ul li div a.selectedthumb') ) + 1 ) / 8 ); // 8 items visible per page
			     $('#lightboxcarousel').trigger('gotoinstant', currentImageID );
			     galleryCaptionLinks();
//			     galleryTimeout = setTimeout("$.fancybox.next();",4000);
   },
   'onStart' : function () {
        clearTimeout(galleryTimeout);
        $('li.cloned').remove();
        $('li.empty').remove();
        $('ul li div a').removeClass('selectedthumb');
   }
		});
	}
}
function galleryCaption(title, currentArray, currentIndex, currentOpts) {
 var caption = '<div class="gallerycaption">';
 caption += title + '</div>';
 caption += '<div id="lightboxcarousel" class="carousel"><div class="wrapper"><ul>';
 for (var i=0;i<currentArray.length;i++) {
  caption += '<li><div class="imagewrap">';
  if ( $(currentArray[currentIndex]) == $(currentArray[i]) ) {
   caption += '' + $('<div>').html( $(currentArray[i]).clone().addClass('selectedthumb') ).html() + '</div></li>';
  } else {
   caption += '' + $('<div>').html( $(currentArray[i]).clone() ).html() + '</div></li>';
  }
 }
 caption += '</ul></div></div>';
 return caption;
}

//AF 31/1/11 - this function changed to accept the photo array instead of parsing the data
function drawSlideshow(photos) {
	var carouselhtml = '';
	var lightboxhtml = '';
	//var photos = jQuery.parseJSON(data.replace(/(\r\n|\r|\n)/g, "<br />") );
	
 	//open carousel wrapper
	carouselhtml += '  <div id="lightboxcarousel" class="wrapper">';
	carouselhtml += '   <ul>';

 for (var i=0;i<photos.length;i++) {
        var photo = photos[i];
    	   if (i == 0) { firstImageID = photo[0] }
        lightboxhtml += galleryOverlayHTML(photo);
        carouselhtml += galleryCarouselHTML(photo);
 }
 
 	//close carousel wrapper
	carouselhtml += '   </ul>';
	carouselhtml += '  </div>';

 $('#hiddencontent').append(lightboxhtml);
 $('#hiddencontent').append(carouselhtml);

 if (jQuery().fancybox) {
        $('a[rel="lightbox"]').fancybox({
        'padding' : 6,
        'autoDimensions' : false,
        'changeSpeed' : 0,
        'changeFade' : 0,
        'speedIn' : 100,
        'speedOut' : 100,
        'transitionIn' : 'none',
        'transitionOut' : 'none',
        'width' : 758,
        'height' : 510,
//        'titleShow' : false, 
//        'titlePosition' : 'inside',
        'overlayShow' : true,
        'overlayColor' : '#000',
        'showNavArrows' : false,
        'cyclic' : false,
        'titleFormat' : formatTitle,
        'onComplete' : function () {
                        appendCarousel();
                        $('#lightboxcarousel').trigger('gotoinstant', 1 );
                        //$('#lightboxcarousel').show('fast');
                        //galleryTimeout = setTimeout("$.fancybox.next();",5000);
				             },
			     'onClosed' : function () {
			                     $('#viewgallery').trigger('click');
			             },
			     'onStart' : function () {
			                     //clearTimeout(galleryTimeout);
			                     $('#lightboxcarousel').hide();
                        //previousScrollLeft = $('#lightboxcarousel').scrollLeft();
			             }
        });
 }
 
 popUIDAndVotes();
 
}

function formatTitle(title, currentArray, currentIndex, currentOpts) {
       	 //use array and index to select correct item in carousel
       	 // currentarray is the <a rel="lightbox"> elements
       	 $('#lightboxcarousel').show();
       	 $('li.cloned').remove();
       	 $(currentArray).removeClass('selectedthumb');
       	 $(currentArray[currentIndex]).addClass('selectedthumb');
       	 if ( currentIndex == 0 ) {
       	  currentImageID = 1;
       	 } else {
       	  currentImageID = Math.ceil( ( $('ul li div a').index( $('ul li div a.selectedthumb') ) + 1 ) / 11 ); // 11 items visible per page
       	 }
}

function appendCarousel() {
        $('#fancybox-content .lightboxcarousel').append( $('#lightboxcarousel') );
        $('li.cloned').remove();
        $('a.arrow').remove();
        $('#fancybox-content .lightboxcarousel').carousel();
        $('#lightboxcarousel').trigger('gotoinstant', currentImageID );
        //$('#lightboxcarousel').scrollLeft(previousScrollLeft);
        // Rebind forward and back buttons
//        $('a.back').unbind('click').click(function () {
//            return $('#lightboxcarousel').trigger('goto', currentImageID - (1/4) );                
//       });
        
//        $('a.forward').unbind('click').click(function () {
//            return $('#lightboxcarousel').trigger('goto', currentImageID + (1/4) );
//        });
        // Rebind lightbox
        $('a[rel="lightbox"]').fancybox({
        'padding' : 6,
        'autoDimensions' : false,
        'changeSpeed' : 0,
        'changeFade' : 0,
        'speedIn' : 100,
        'speedOut' : 100,
        'width' : 758,
        'height' : 510,
//        'titleShow' : false, 
//        'titlePosition' : 'inside',
        'overlayShow' : true,
        'overlayColor' : '#000',
        'showNavArrows' : false,
        'cyclic' : false,
        'titleFormat' : formatTitle,
        'onComplete' : function () {
                        appendCarousel();
                        //$('#lightboxcarousel').show('fast');
                        //galleryTimeout = setTimeout("$.fancybox.next();",5000);
				             },
			     'onClosed' : function () {
			                     $('#viewgallery').trigger('click');
			             },
			     'onStart' : function () {
			                     $('#hiddencontent').append( $('#lightboxcarousel') );
			                     clearTimeout(galleryTimeout);
                        //previousScrollLeft = $('#lightboxcarousel').scrollLeft();
			             }
        });
}

function drawGallery(data,target,idprefix,randomise) {
	if ( idprefix === undefined ) { idprefix = ''; }
	if ( randomise === undefined ) { randomise = 0; }
	
	var lightboxhtml = '';
	var carouselhtml = '';
	var galleryhtml = '<div class="galleryitems left">';
//	var photos = jQuery.parseJSON(data.replace(/(\r\n|\r|\n)/g, "<br />").replace(/,,/,",0,").replace(/,\]/,",0]") );
	var photos = jQuery.parseJSON(data.replace(/(\r\n|\r|\n)/g, "<br />") );

	if (photos === null) {return;}
	if ( randomise == 1 ) { photos.sort(function() {return 0.5 - Math.random()}); }
	//open carousel wrapper
	carouselhtml += '  <div id="lightboxcarousel" class="wrapper">';
	carouselhtml += '   <ul>';
	for (var i=0;i<photos.length;i++) {
	   var photo = photos[i];
	   galleryhtml += '<div class="galleryitem left">';
	   galleryhtml += '  <div class="galleryimage';
	   if (i>0 && ( ((i+1)%5==0) || (i+1)==photos.length ) ) { galleryhtml += ' last'; }
	   galleryhtml += '">';
	   //galleryhtml += '  <a rel="lightbox" href="#' + idprefix + 'imgdetail' + photo[0] + '" id="' + idprefix + 'img' + photo[0] + '">';
	   galleryhtml += '  <a title="' + photo[7] + '" href="?cmd=SubmissionDetail&id=' + photo[0] + '">';
	   galleryhtml += '  <img src="' + photo[4] + '">';
	   galleryhtml += '  </a>';
	   galleryhtml += '  </div>';
	   galleryhtml += '  <div class="galleryfooter';
	   if (i>0 && ( ((i+1)%5==0) || (i+1)==photos.length ) ) { galleryhtml += ' last'; }
	   galleryhtml += '">';
	   galleryhtml += '  <span class="imagecomments"><a href="?cmd=SubmissionDetail&id=' + photo[0] + '"><img alt="Comments" src="http://www.themastersofphotography.com/agile_assets/2/commenticon.png"></a>' + photo[2] + '</span>';
	   galleryhtml += '  <span class="imagevotes">' + photo[1] + '<a href="?cmd=SubmissionDetail&id=' + photo[0] + '"><img alt="Votes" src="http://www.themastersofphotography.com/agile_assets/2/voteicon.1.png"></a></span>';
	   galleryhtml += '  </div>';
	   galleryhtml += '</div>';
	   //lightboxhtml += galleryOverlayHTML(photo,idprefix);
	   //if ( idprefix == '' ) {
	   //    carouselhtml += galleryCarouselHTML(photo,idprefix);
	   //}
	}
	galleryhtml +='</div>';

	//close carousel wrapper
	carouselhtml += '   </ul>';
	carouselhtml += '  </div>';

	$(target).html(galleryhtml).animate({opacity:1},'fast');
	
	// don't do this for the top ten 
	if ( idprefix == '' ) {

	popUIDAndVotes();
	
	if ( photos.length < currentLimit) { $('.morephotos').hide(); }
	
	}

}

function wireupImageLink(imgid,imgdetailid) {
	var options = { windowSourceID: imgdetailid };
	$(imgid).bind('click', function () {
		$.openDOMWindow( options ); 
		return false;
	} );
}

function galleryOverlayHTML(photo,idprefix) {
	if ( idprefix === undefined ) { idprefix = ''; }
	var output = '';
	output += '<div class="lightboxcontainer" id="' + idprefix + 'imgdetail' + photo[0] + '">';
	output += '  <div class="lightbox left">';
	output += '  <a href="?cmd=SubmissionDetail&id=' + photo[0] + '"><img src="' + photo[6] + '"></a>';
	output += '  </div>';
	output += '  <div class="lightbox right">';
//	output += '    <div class="close left">';
//	output += '      <a href="#" class="right tradegothic" onclick="return false;">Close</a>';
//	output += '    </div>';
	output += '    <div class="imagedetail left">';
	output += '      <h5>' + photo[7] + '</h5>';
	output += '      <span>By ' + photo[8] + ' ' + photo[9];
	output += '      </span>';
	output += '      <span>| Uploaded: ' + photo[10] + '</span>';
	output += '      <hr>';
	output += '      <h6>Where</h6>';
	output += '      <p>' + photo[11] + '</p>';
	output += '      <h6>When</h6>';
	output += '      <p>' + photo[13] + '</p>';
	output += '      <h6>Why is it special?</h6>';
	output += '      <p class="userdescription">' + photo[14] + '</p>';
	output += '    </div>';
	output += '    <div class="left comment icon"><a href="?cmd=SubmissionDetail&id=' + photo[0] + '"><p> </p>' + photo[2] + '</a></div>';
	output += '    <div class="left votecount icon"><p>' + photo[1] + '</p>votes</div>';
//	output += '    <div class="left vote icon vote_' + photo[0] + '"><a href="#" onclick="vote( '+photo[0]+' );return false;"><p> </p>vote</a></div>';
	output += '  </div>';
	output += '  <div class="lightboxcarousel">';
	
	output += '  </div>';
	output += '</div>';
	return output;
}

function galleryCarouselHTML(photo,idprefix) {
	if ( idprefix === undefined ) { idprefix = ''; }
	var output = '';

	output += '  <li>';
	output += '  <div class="imagewrap">';
	output += '    <a href="#' + idprefix + 'imgdetail' + photo[0] + '" rel="lightbox" title="' + photo[7] + '">';
	output += '<img id="' + idprefix + 'imgthumb' + photo[0] + '" src="' + photo[3] + '">';
	output += '  </a>';
	output += '  </div>';
	output += '  </li>';

	return output;
}

function getFlickrPhotos(o) {
	if (o.user === undefined) {
		$('#flickruser').addClass('error').before('<p id="flickrerror" class="error">Email address not found on Flickr. Check you\'ve entered the correct email address for your Flickr account.</a>.</p>');
	} else {
		$('#flickruser').removeClass('error');
		$('#flickrerror').remove();
		document.getElementById('flickruid').value = o.user.id;
		loadScript('http://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&jsoncallback=showFlickrPhotos&user_id=' + o.user.id + '&per_page=12&format=json&api_key=' + flickrapikey );
	}
}

function showFlickrPhotos(o) {
	var flickrphotos = '';
	var photourl = '';
	var itemcount = 12;
	var page = o.photos.page;

	for (var i=0;i<o.photos.photo.length;i++) {
		photourl = 'http://farm' + o.photos.photo[i].farm;
		photourl += '.static.flickr.com/' + o.photos.photo[i].server;
		photourl += '/' + o.photos.photo[i].id;
		photourl += '_' + o.photos.photo[i].secret;
		//photourl += '_m.jpg';
		flickrphotos += '<img src="' + photourl + '_s.jpg" title="' + photourl + '_b.jpg" onclick="$(\'#photopreview\').css(\'width\',\'304px\'); document.getElementById(\'photourl\').value = this.title; document.getElementById(\'photopreview\').src = this.title;">';
	}
	var nextbutton = '';
	var prevbutton = '';

	if (o.photos.photo.length == itemcount) { nextbutton = '<a class="right" id="nextflickr" href="#flickruser">Next page</a>'; }
	if (page > 1) { prevbutton = '<a id="prevflickr" href="#flickruser">Previous page</a>'; }
		
	$('#flickrphotos').html(flickrphotos + '<div class="paging">' + prevbutton + nextbutton + '</div>').show().animate({opacity:1},'slow');
	$('#nextflickr').bind('click', function() {
		$('#flickrphotos').animate({opacity:0},'fast');
		loadScript('http://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&jsoncallback=showFlickrPhotos&user_id=' + document.getElementById('flickruid').value + '&page=' + (parseInt(page) + 1) + '&per_page=12&format=json&api_key=' + flickrapikey ); return 0;
	  });
	$('#prevflickr').bind('click', function() {
		$('#flickrphotos').animate({opacity:0},'fast');
		loadScript('http://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&jsoncallback=showFlickrPhotos&user_id=' + document.getElementById('flickruid').value + '&page=' + (parseInt(page) - 1) + '&per_page=12&format=json&api_key=' + flickrapikey ); return 0;
	  });
}

function initFB() {
  if (window.FB === undefined) {
	if (tries >= retrylimit) {
		$('#fberror').hide('fast').remove();
		$('#login').before('<p id="fberror" class="error">Sorry - there was a problem connecting to Facebook.</p>');		
	} else {
		tries++;
		$('#fberror').hide('fast').remove();
	  	loadScript('http://static.ak.fbcdn.net/connect/en_US/core.js?'+Math.floor(Math.random()*5000) );
		setTimeout("initFB()",5000);
		if (tries > 1) {
		  $('#login').before('<p id="fberror" class="error">There is a problem communicating with Facebook at this moment. Retrying...</p>');
		}
	}
  } else {
  	$('#fberror').remove();
	FB.init({ apiKey: '108426669224943' });
	// fetch the status on load
	FB.getLoginStatus(handleSessionResponse);
	
	$('#login').bind('click', function() {
		FB.login(handleSessionResponse, {perms:'user_photos,publish_stream,email'} ); return 0;
	});
	
	$('#logout').bind('click', function() {
		FB.logout(handleSessionResponse);
	});
	
	$('#disconnect').bind('click', function() {
		FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
		  clearDisplay();
		});
	});
  }
}
// no user, clear display
function clearDisplay() {
	$('#fbphotos').hide('fast');
	$('#disconnect').hide('fast');
	$('#login').show('fast');
}

// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
	// if we dont have a session, just hide the user info
	if (!response.session) {
	  clearDisplay();
	  return;
	}
	// if we have a session, query for the user's profile picture and name
	$('#login').hide('fast');
	$('#disconnect').show('fast');
	
	// choose what to do now depending on current page
	if ( $.urlParam('cmd') == 'SubmissionDetail' ) { //comment form
	  FB.api( { method: 'fql.query', query: 'SELECT name, email FROM user WHERE uid = ' + FB.getSession().uid }, function(response) { $('#firstName').val(response[0].name); $('#email').val(response[0].email); } );
 } else if ( $.urlParam('McacompetitionformHandler0') == 'MCAEnterCompetitionPage4' ) {
     var postbody = "I've just entered The Macallan Masters of Photography Masterclass Competition.  Enter now to win the ultimate journey of Scotland or Nikon camera equipment. Winners will be judged by Albert Watson.";
     var link = 'http://www.themastersofphotography.com/the-masterclass/s8/';
     var linkName = 'The Macallan Masters of Photography Masterclass Competition';
     var linkDescription = 'The Macallan Masters of Photography Masterclass Competition 2010.';
     var picture = 'http://www.themastersofphotography.com/agile_assets/2/aweditionbg.1.jpg';
     FB.api('/me/feed', 'post', { message: postbody, link: link, name: linkName, picture: picture, description: linkDescription }, function(response) {
     if (!response || response.error) {
       //alert('Error occured');
     }
   });

	} else {  // competition form
	  getAlbums(0);
	}
}

function getAlbums(limit) {
  	var itemcount = 12;
  	
	FB.api(
	  {
		method: 'fql.query',
		query: 'SELECT pid, aid, src_small, caption FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner=' + FB.getSession().uid + ') AND pid IN (SELECT cover_pid FROM album WHERE owner=' + FB.getSession().uid + ') ORDER BY created DESC LIMIT ' + limit + ',' + itemcount
	  },
	  function(response) {
		//var user = response[0];
		var fbphotos = '<p>Select album:</p>';
		for (var i=0;i<response.length;i++) {
			fbphotos += '<img src="' + response[i].src_small + '" title="' + response[i].aid + '" onclick="getPhotos(0,this.title);">';
		}
		var nextbutton = '';
		var prevbutton = '';

		if (response.length == itemcount) { nextbutton = '<a class="right" id="nextbutton" href="#progress">Next page</a>'; }
		if (limit > 1) { prevbutton = '<a id="prevbutton" href="#progress">Previous page</a>'; }

		$('#fbphotos').html(fbphotos + '<div class="paging">' + prevbutton + nextbutton + '</div>').show().animate({opacity:1},'slow');
		$('#nextbutton').bind('click', function() {
			$('#fbphotos').animate({opacity:0},'fast');
			getAlbums(parseInt(limit,10) + itemcount); return 0;
		  });
		$('#prevbutton').bind('click', function() {
			$('#fbphotos').animate({opacity:0},'fast');
			getAlbums(parseInt(limit,10) - itemcount); return 0;
		  });
		}
	);
}

function getPhotos(limit,aid) {
  	//var limit = 1;
  	var itemcount = 12;
  	
	FB.api(
	  {
		method: 'fql.query',
		query: 'SELECT pid, src_small, src_big, caption FROM photo WHERE aid = "' + aid + '" ORDER BY created DESC LIMIT ' + limit + ',' + itemcount
	  },
	  function(response) {
		var user = response[0];
		var fbphotos = '<p><a href="#progress" onclick="getAlbums(0);">Click to select a different album</a></p>';
		for (var i=0;i<response.length;i++) {
			fbphotos += '<img src="' + response[i].src_small + '" title="' + response[i].src_big + '" id="imgid' + response[i].pid + '" onclick="$(\'#photopreview\').css(\'width\',\'304px\'); document.getElementById(\'photourl\').value = this.title; document.getElementById(\'photopreview\').src = this.title;">';
		}
		var nextbutton = '';
		var prevbutton = '';

		if (response.length == itemcount) { nextbutton = '<a class="right" id="nextbutton" href="#progress">Next page</a>'; }
		if (limit > 1) { prevbutton = '<a id="prevbutton" href="#progress">Previous page</a>'; }

		$('#fbphotos').html(fbphotos + '<div class="paging">' + prevbutton + nextbutton + '</div>').show().animate({opacity:1},'slow');
		$('#nextbutton').bind('click', function() {
			$('#fbphotos').animate({opacity:0},'fast');
			getPhotos(parseInt(limit,10) + itemcount, aid); return 0;
		  });
		$('#prevbutton').bind('click', function() {
			$('#fbphotos').animate({opacity:0},'fast');
			getPhotos(parseInt(limit,10) - itemcount, aid); return 0;
		  });
		}
	);
  }

function initMap() {
//  $('#gmap').hide();
  if ( document.getElementById('lat').value && document.getElementById('long').value ) {
  	if ( ( parseInt( document.getElementById('lat').value, 10) == 0 && parseInt( document.getElementById('long').value, 10) == 0 ) ) {
  		var latLng = new google.maps.LatLng(33.0, 17.0);
  	} else {
	  	var latLng = new google.maps.LatLng(document.getElementById('lat').value, document.getElementById('long').value);
	}
  } else {
  	var latLng = new google.maps.LatLng(33.0, 17.0);
  }
  var map = new google.maps.Map(document.getElementById('gmap'), {
	zoom: 1,
	center: latLng,
	mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker = new google.maps.Marker();
  var customicon = new google.maps.MarkerImage('http://google-maps-icons.googlecode.com/files/photo.png');
  
  if ( !( parseInt( document.getElementById('lat').value, 10) == 0 && parseInt( document.getElementById('long').value, 10) == 0 ) ) {
	  marker = new google.maps.Marker({
			position: latLng,
			title: 'Location',
			map: map,
			icon: customicon,
			draggable: true
		  });
	google.maps.event.addListener(marker, 'dragend', function(o) {
		document.getElementById('lat').value = o.latLng.lat() ;
		document.getElementById('long').value = o.latLng.lng() ;
		});
//	wireupMarkerDoubleClick(marker, map, customicon);
   wireupMapClick(marker, map, customicon);
  } else {
  	wireupMapClick(marker, map, customicon);
  }
  // Update current position info.
  //updateMarkerPosition(latLng);
  //geocodePosition(latLng);
  
  $('#location').bind('change', function () { codeAddress(map); });
  //$('#gmap').fadeIn('fast');
}

function wireupMapClick(marker, map, customicon) {
  google.maps.event.addListener(map, 'click', function(o) {
   marker.setMap(null);
	  marker = new google.maps.Marker({
		position: o.latLng,
		title: 'Location',
		map: map,
		icon: customicon,
		draggable: true
	  });
	  
	  //updateMarkerStatus([ o.latLng.lat(), o.latLng.lng() ].join(', '));
	  document.getElementById('lat').value = o.latLng.lat() ;
	  document.getElementById('long').value = o.latLng.lng() ;
	  
	  google.maps.event.addListener(marker, 'dragend', function(o) {
		//updateMarkerStatus([ o.latLng.lat(), o.latLng.lng() ].join(', '));
		document.getElementById('lat').value = o.latLng.lat() ;
		document.getElementById('long').value = o.latLng.lng() ;
		//document.getElementById('mapZoom').value = o.latLng. ;
		//geocodePosition(marker.getPosition());
	  });
//	wireupMarkerDoubleClick(marker, map, customicon);
  });
}

function wireupMarkerDoubleClick(marker, map, customicon) {
	google.maps.event.addListener(marker, 'dblclick', function(o) {
		marker.setMap(null);
	  	google.maps.event.addListenerOnce(map, 'click', function(o) {
		  var marker = new google.maps.Marker({
			position: o.latLng,
			title: 'Location',
			map: map,
			icon: customicon,
			draggable: true
		  });
		document.getElementById('lat').value = o.latLng.lat() ;
		document.getElementById('long').value = o.latLng.lng() ;
		google.maps.event.addListener(marker, 'dragend', function(o) {
			document.getElementById('lat').value = o.latLng.lat() ;
			document.getElementById('long').value = o.latLng.lng() ;
		});
		wireupMarkerDoubleClick(marker, map, customicon);
	    });
	});
}

function codeAddress(map) {
	var geocoder = new google.maps.Geocoder();
	var address = document.getElementById("location").value;
	geocoder.geocode( { 'address': address}, function(results, status) {
	if (status == google.maps.GeocoderStatus.OK) {
		map.setCenter(results[0].geometry.location);
		map.setZoom(8);
	} else {
		//alert("Geocode was not successful for the following reason: " + status);
	}
	});
}

function updateMarkerStatus(str) {
  document.getElementById('markerlocation').innerHTML = str;
}

jQuery.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({opacity: 'toggle'}, speed, easing, callback);
};

(function($){
    $.fn.limit  = function(options) {
        var defaults = {
        limit: 500,
        id_result: false,
        alertClass: 'error'
        }
        var options = $.extend(defaults,  options);
        return this.each(function() {
            var characters = options.limit;
            if(options.id_result != false)
            {
                $("#"+options.id_result).append("You have <strong>"+  characters+"</strong> characters remaining");
            }
            $(this).keyup(function(){
                if($(this).val().length > characters){
                    $(this).val($(this).val().substr(0, characters));
                }
                if(options.id_result != false)
                {
                    var remaining =  characters - $(this).val().length;
                    $("#"+options.id_result).html("You have <strong>"+  remaining+"</strong> characters remaining");
                    if(remaining <= 10)
                    {
                        $("#"+options.id_result).addClass(options.alertClass);
                    }
                    else
                    {
                        $("#"+options.id_result).removeClass(options.alertClass);
                    }
                }
            });
        });
    };
})(jQuery);

jQuery.fn.carousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            

        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
        //    $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 800, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 
                currentPage = page;
            });                
            return false;
        }
        // 5. instant goto function
        function gotoPageInstant(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 0, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 
                currentPage = page;
            });                 
            return false;
        }
        
        $wrapper.after('<a class="arrow back"><</a><a class="arrow forward">></a>');
        
        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function () {
            return gotoPage(currentPage - 1);
        });
        $('a.forward', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
        $(this).bind('gotoinstant', function (event, page) {
            gotoPageInstant(page);
        });
    });
};











/* */












