$.fn.extend({ nextPlease: function () {

   return this.each(function() {

	   $(this).css('cursor','pointer')

			.click(function(e){

           	var hw = ($(this).width())/2;
            var th = $(this);
            offset = th.offset();
				var x = e.pageX - offset.left;
				var y = e.pageY - offset.top;
      		if(x>=hw) {

  		      	next = $('#nextphoto').val();

					//window.location.hash = next;
               loadPhoto(next);

      		} else {

         		prev = $('#prevphoto').val();
					//window.location.hash = prev;
               loadPhoto(prev);

      		}
			});
		})

                },

                tagPerson: function () {
                	  return this.each(function() {
                         $(this).css({cursor:'crosshair'});

					  			 $(this).click(function(e){

                                 var th = $(this);
                                 offset = th.offset();
                                 position = th.position();
	                              photox = e.pageX - offset.left;
	                              photoy = e.pageY - offset.top;
                                 $('#list-people').show();
                                 $('#person-marker-box').show().css({top:photoy-35+'px',left:position.left+photox-35+'px'});
                                 $('#findperson').val('').focus();
                                 $('#returned-people').html('');
					  			});
                   });
                },
                scrollTo: function () {

                   return this.each(function() {
	                   var off = $(this).offset();
	                   $('html,body').animate({scrollTop : off.top-10 }, 500 );

                   });
                }
 	});



jQuery.fn.center = function () {

    this.css("top", ( $(window).height() - this.outerHeight() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft() + "px");
    return this;

}



$(document).ready(function(){

   $(window).resize( function () {

         wH = $(window).height();
			pW = (wH/513)*657-25;
         if(pW>1024){pW=1024;}
	      $("#single-photo > img").css({'width':pW+'px'});

         if(pW>557) {
				$('#photo-overlay').css({'width':pW+20+'px'});
         } else {
				$('#photo-overlay').css('width','577px');
			}

   });


	$(".show-photo-box img").nextPlease();

        $(document).bind('keydown.gallery', function(e) {

           if (e.keyCode == 37) {

              e.preventDefault();
              // Do left arrow stuff
              prev = $('#prevphoto').val();
              loadPhoto(prev);

           } else if (e.keyCode == 39) {

              e.preventDefault();
              // Do right arrow stuff
              next = $('#nextphoto').val();
              loadPhoto(next);

           } else if (e.keyCode == 27) {

              e.preventDefault();
              // Do Esc stuff
              closeOverlay();
           }
       });


       $('.pthumb a, .vthumb a, .gthumb a, .title-it a').each(	function() {$(this).hover(

       	function(e) {
           tit = $(this).attr('title');
           $(this).attr('title','');
           $('#titlelerinner').children('span').html(tit);
           $(this).append($('#titleler'));
           var tw = $(this).children('img').outerWidth();
           var th = $(this).children('img').outerHeight();
           $('#titleler').show()
			  var titw = $('#titlelerinner').outerWidth();
           $('#titleler').css({ left:(tw/2)-(titw/2)+'px',top:th-7+'px'});
           $('#tit-arrow').css({ left:(titw/2)-7+'px'});

	      },
       	function(e) {
         	$('#titleler').hide();
            $(this).attr('title',tit);
         });

       });

       $('.vthumb').hover(

       	function(e) {
         	$(this).find('img:nth-child(1)').hide();
         	$(this).find('img:nth-child(2)').show();

         },
       	function(e) {
         	$(this).find('img:nth-child(1)').show();
         	$(this).find('img:nth-child(2)').hide();
         });


       $('#titleler').hover(
       		function(e) {
       			$(this).show();
            },
            function(e) {
            	$(this).hide();
       		}
       );


       $('.vthumb a').click(function(e) {
				e.preventDefault();
            var vlink = $(this).attr('href');
            var vid = vlink.split('vimeo.com/');
            vid = vid[1];
            var iframesrc = 'http://player.vimeo.com/video/'+vid+'?title=0&byline=0&portrait=0&api=1';
            $('#vimeo').attr('src',iframesrc);
            $('#video-title').html(tit);
            window.location = '#'+vid;
            $('html, body').animate({scrollTop:'65'}, 500);

       });

       $('.gpthumb > a').click(function(e) {
				e.preventDefault();
				var pId = $(this).attr('id');
            loadPhoto(pId);

       });

	//activateShowPerson();

	//activateAlreadyTagged();



});



function activateShowPerson() {

		 $('.showperson').each(function() {

            		$(this).hover(function(e) {

                            cont = $(this).html();

                            cood = $(this).attr('id');

                            cood = cood.split('-');

                            $('#person-name').html(cont);

                            var relplace = $('#single-photo img').width();

                            relplace = (657-relplace)/2;

			    var namewidth = $('#person-name').outerWidth();

                            var leftcood = relplace + parseInt(cood[1])-35;

                            var topcood = 10+ parseInt(cood[2])-35;

                            $('#list-people').hide();

                            $('#person-marker-box').css({left:leftcood+'px',top:topcood+'px'}).show();

                         },

                         function() {

                            $('#person-marker-box').hide();



                         });

            	    });

          }



          function activateAlreadyTagged() {



	            $('.already-tagged').each(function() {

//            		  var cx = parseInt($(this).css('left'));

//                          var relplace = $('#single-photo img').width();

//                          relplace = (657-relplace )/2;

//                        $(this).css('left',cx+relplace +'px');

            		$(this).hover(function(e) {

                            var child = $(this).children(':first');

                            var ow = $(child).outerWidth();

                            var newx = (60-parseInt(ow))/2;


                            $(child).css('left',newx+'px').show();

                         },

                         function() {

                            $(this).children(':first').hide();



                         });

            	    });

          }



         function startTagging() {

         	$('#tagging-on').show().scrollTo();

                 $('.show-photo-box img').unbind('click').tagPerson();

         }

         function endTagging() {

         	$('#tagging-on, #person-marker-box, #list-people').hide();

         	$('.show-photo-box img').unbind('click').nextPlease();

         }



         function taggablePersonSearch(q) {

         	$.getJSON( 'http://www.educateforlife.org.uk/nu1/functions/site-photos.php', { f:'photoTagSearch' , q:q }, function(data) {

                 	$('#returned-people').html('');

                         //for( i=0; i<data.li.length ; i++) {

                            //$('#returned-people').append(data.li[i]);

                        // }

                 	  var items = [];

                 	  $.each(data, function(key, val) {
                 	     items.push('<li class="select-person" id="' + key + '">' + val + '</li>');
                 	  });

                 	  $('<ul/>', {
                 	     html: items.join('')
                 	  }).appendTo('#returned-people');

$('.select-person').click(function() { $(this).removeClass('select-person').addClass('selected-person'); selectPerson($(this)); });

                 });


         }

         function selectPerson(t) {

		personId = $(t).attr('id');

                 pictureId = $('#single-photo img').attr('id');

                 coordinates = photox+'-'+photoy;

         	$.getJSON('http://www.educateforlife.org.uk/nu1/functions/site-photos.php',{f:'saveTag',pictureId:pictureId,personId:personId,coordinates:coordinates},function(data) {

         	       //$(t).remove();

                       $('#people-names').html(data.peoplenames);

                       $('.already-tagged').remove();

                       $('.show-photo-box').append(data.peoplemarkers);

                       activateShowPerson();

                       activateAlreadyTagged();

                    });



         }



         function removeTag (personId) {

            pId = $('#single-photo img').attr('id');

                    $.getJSON('http://www.educateforlife.org.uk/nu1/functions/site-photos.php',{f:'removeTag',pId:pId,personId:personId},function(data) {

                       $('#person-marker-box').hide();

		      $('#people-names').html(data.peoplenames);

                       $('.already-tagged').remove();

                       $('.show-photo-box').append(data.peoplemarkers);

                       activateShowPerson();

                       activateAlreadyTagged();

                    });

         }

function loadGallery(gid){

  	$.getJSON('http://www.educateforlife.org.uk/nu1/functions/site-photos.php',{f:'loadAlbumNG',galleryId:gid}, function(data) {

   	$('#gallery-title').html(data.title);
   	$('#photo-album-mover').html(data.thumbs);
   	$('#gallery-desc').html(data.desc);

      $('#gallery-image').css({backgroundImage:'url('+data.preview+')'});

      $('html, body').animate({scrollTop:'65'}, 500);


	   $('#photo-album-mover > a.spthumb').click(function( c ) {
	      c.preventDefault();
	   }).mousedown( function () {
	      start= new Date().getTime();
	   }).mouseup( function () {

	      stop = new Date().getTime();

	      if (stop-start<500) {
	         var pId = $(this).attr('id');
	         loadPhoto(pId);
	      }

	   });

  	});


}

function loadPhoto (pid){

   $('#single-photo, #single-photo-controls').show();

	$('#person-marker-box').hide();
  	$.getJSON('http://www.educateforlife.org.uk/nu1/functions/site-photos.php',{f:'loadPhotoNG',photoId:pid}, function(data) {

      	$('#photo-overlay, .black-overlay, #all-overlays').show();
        	$('#click-to-hide').css('width',$('#all-overlays').outerWidth()+'px');
   		$('html,body').css({'overflow':'hidden'});

 	   url = 'http://www.educateforlife.org.uk/blog/'+data.photopath+'/'+data.photourl;

	   $('<img>').attr('src',url).load( function () {


	      $("#single-photo > img").attr({  	src:url, id:'p'+data.photoid });

         wH = $(window).height();
			pW = (wH/513)*657-25;
         if(pW>1024){pW=1024;}
         if(pW > parseInt(data.width)) {pW=data.width;}
	      $("#single-photo > img").attr({ style:'width:'+pW+'px' });

         if(pW>557) {
				$('#photo-overlay').css('width',pW+'px');
         } else {
				$('#photo-overlay').css('width','577px');
			}


	      $('#nextphoto').val(data.nextphoto);
	      $('#prevphoto').val(data.prevphoto);
	      if(data.albumname != 'From the set <a href="http://www.educateforlife.org.uk/nu1/photos/"></a>.') {
         	$('#albumname').show().html(data.albumname);
         } else {
         	$('#albumname').hide();
         }
	      $('#photodate').html(data.photodate);
	      $('#photocaption').html(data.photocaption);

	      $('#people-names').html(data.peoplenames);
	      $('.already-tagged').remove();
	      $('.show-photo-box').append(data.peoplemarkers);


	      activateShowPerson();
	      activateAlreadyTagged();
	   });
  	});
}

function loadPhotoSinglePic (pUrl){

   $('#single-photo, #single-photo-controls').show();

	$('#person-marker-box').hide();

	   $('<img>').attr('src',pUrl).load( function () {

         wH = $(window).height();
			pW = (wH/513)*657-25;
         if(pW>1024){pW=1024;}
	      $("#single-photo > img").attr({  src:pUrl , style:'width:'+pW+'px' });

         if(pW>557) {
				$('#photo-overlay').css('width',pW+20+'px');
         } else {
				$('#photo-overlay').css('width','577px');
			}

         $('#albumname, .photos-below-left, .photos-below-right').hide();
	      $('#downloadlink').hide();
	      $('#people-names').hide();
	      $('.already-tagged').remove();


	   });

}


function getPosition(arrayName,arrayItem)
{
  for(var i=0;i<arrayName.length;i++){
   if(arrayName[i]==arrayItem)
  return i;
  }
}


