/**
* Sets the stars to match the specified ratings value - provided as a percent
**/
function set_stars_to (rating, numvotes) {
  // Stars
  $('.rating_stars img').each(function() {
    if (rating >= 20) {
      $(this).attr('src', 'images/star_full.gif');
    } else if (rating >= 10) {
      $(this).attr('src', 'images/star_half.gif');
    } else {
      $(this).attr('src', 'images/star_empty.gif');
    }
    
    $(this).data('src', $(this).attr('src'));
    
    rating -= 20;
  });
  
  // Numvotes
  if (numvotes == 0) {
    $('#numvotes').html('No votes yet');
  } else if (numvotes == 1) {
    $('#numvotes').html('Only one vote');
  } else {
    $('#numvotes').html(numvotes + ' votes');
  }
}


/**
* Turns photos in the slider into links which open up the extended area
**/
function set_photo_links () {
  $('.photo-pics a').click(function() {
    
    $.get('ajax/tabs_photos_getinfo.php', {'id': $(this).children('img').attr('imageid'), 'url':window.location.href}, function(html) {
      $('#photo-info').html(html);
    });
    
    $('#pic-large img')
      .attr('src', $(this).children('img').attr('longdesc'))
      .attr('title', $(this).children('img').attr('title'))
      ;
    
    // Sort out the stars
    var rating = $(this).children('img').attr('rating');
    var numvotes = $(this).children('img').attr('numvotes');
    set_stars_to (rating, numvotes);
    
    // Store some info in the stars that is used later when rating
    var imageid = $(this).children('img').attr('imageid');
    $('.rating_stars img').each(function(index) {
      $(this).data('imageid', imageid);
      $(this).data('rating', index + 1);
    });
    
    $('#photos-extended').slideDown('slow');
    
    return false;
  });
}


/**
* Only used when the get variable photo_id is set
**/
function show_photo (id) {
  $('#photos-extended').show();
  window.location.hash = '#photos';
  
  $('#photo-info').html('<p>Loading...</p>');
  
  $.get('ajax/tabs_photos_getinfo.php', {'id': id, 'url':window.location.href}, function(html) {
    if (html == '') {
      $('#photo-info').html('<p>Photo not found</p>');
      return;
    }
    
    $('#photo-info').html(html);
    
    $('#pic-large img')
      .attr('src', 'file.php?f=U01ypT.vHKD2o.' + id + '.medium')
      .attr('title', $('#photo-info h3').text())
      ;
    
    // Sort out the stars
    var rating = parseInt($('#photo-info span[field=Rating]').text(), 10);
    var numvotes = parseInt($('#photo-info span[field=RatingsNumber]').text(), 10);
    set_stars_to (rating, numvotes);
    
    // Store some info in the stars that is used later when rating
    $('.rating_stars img').each(function(index) {
      $(this).data('imageid', id);
      $(this).data('rating', index + 1);
    });
  });
}


$(document).ready( function() {

  $("#photos").tabs();
  $('#photos-extended').hide();
  
  // Set a click event for all photos - opens extra info box 
  $('#photos').bind('tabsshow', function(event, ui) {
    if (ui.index != 3) {
      set_photo_links();
    }
  });
  
  // Login required for 'submit' tab.
  $('#photos').bind('tabsselect', function(event, ui) {
    if (ui.index == 3) {
      
      if (user_logged_in == false) {
        jQuery.facebox(function() {
          jQuery.get('ajax/login.php', function(data) {
            jQuery.facebox(data);
          })
        });
        return false;
        
      } else {
        $('#photos-extended').slideUp('slow');
      }
      
    }
  });
  
  // Clicking on a close link to close the 'extra info' box.
  $('a.closelink').click(function(){
    $('#photos-extended').slideUp('slow');
    return false;
  });
  
  // Clicking on 'submit a photo' button that is in the main area
  $('.submit-link').click(function() {
    $("#photos").tabs('select', 3);
  }).css('cursor', 'pointer');
  
  // Rating hover
  $('.rating_stars img').hover(function() {
    $(this).prevAll().attr('src', 'images/star_full.gif');
    $(this).attr('src', 'images/star_full.gif');
    $(this).nextAll().attr('src', 'images/star_empty.gif');
    
  }, function() {
    $('.rating_stars img').each(function() {
      $(this).attr('src', $(this).data('src'));
    })
  });
  
  // Rating click
  $('.rating_stars img').click(function() {
    // processing msg
    $('.rating_stars').slideUp('slow', function() {
      $('.rating_stars').after('<p class="confirmation">Processing, please wait.</p>');
      $('.rate .confirmation').hide();
      $('.rate .confirmation').slideDown('slow');
    });
    
    // json request
    var data = {
      rating: $(this).data('rating'),
      imageid:  $(this).data('imageid')
    };
    $.getJSON("ajax/rate_photo.php", data, function(json) {
      $('.rate .confirmation').slideUp('slow', function() {
      
        // Success
        if (json.result == 1) {
      
          $('.rate .confirmation')
            .html('<p class="confirmation">Thanks for your vote!</p>')
            .slideDown('slow');
            
          // Hides the entire ratings box after 5000 seconds
          // Once the box is hidden, shows all the sub elements again
          $('.rate .confirmation').animate({opacity: 1}, 2000, function() {
            $('.rate .confirmation').slideUp('slow', function() {
              $('.rate .confirmation').remove();
              $('.rating_stars').slideDown('slow');
            });
          });
          
          set_stars_to (json.newrating, json.newnumber);
          
        // Failure
        } else {
        
          $('.rate .confirmation')
            .html('<p class="error">Database error while submitting vote.</p>')
            .slideDown('slow')
            .animate({opacity: 1}, 2000, function() {
              $('.rate .confirmation').slideUp('slow', function() {
                $('.rate .confirmation').remove();
                $('.rating_stars').slideDown('slow');
              });
            });
            
        }
        
      });
    });
  });
  
  
  if (location.hash == '#submit') {
    $("#photos").delay(500, function() {
      $("#photos").tabs('select', 3);
    });
  }
  
  var index = location.href.lastIndexOf('photo_id=');
  if (index != -1) {
    var photo_id = location.href.substr(index + 9);
    photo_id = parseInt(photo_id, 10);
    if (! isNaN(photo_id)) {
      show_photo(photo_id);
    }
  }
});
