var use_simple_transitions = /*@cc_on!@*/false;

var pics = new Array();
var current_img = 0;

// grab the images to crossfade from the dom and array-ify them
function init_fader() {
  if (document.images) {
    var w = 908, h = 680; // width and height
    // FIXME: restructure so that only the next 2 are pre-loaded as img objects in ie/sf/ffx
    var nodes = $j('head link[rel=prefetch]');
    var c = 0;
    pics = new Array(nodes.length);
    nodes.each(function(){
      if (c < 2) {
        // preload each image and stuff its path into the pics array for fwd/back movement
        img_buff     = new Image(w, h);
        img_buff.src = this.getAttribute( "href" ); // pull the images out of the prefetch
        pics[c]      = img_buff;
      }
      c++;
    });
  }
}

//basically wrap around indicies so you can -1 turns to the last item, and last item+1 turns into zero
function index_fix(index) {
  if (index < 0) {
    return pics.length - 1;
  }
  if (index >= pics.length) {
    return 0;
  }
  return index;
}

function preload_images(index) {
  var w = 908, h = 680; // width and height
  var nodes = $j('head link[rel=prefetch]');
  
  var oneBack = index-1;
  if (oneBack < 0 ) {
    oneBack = nodes.length - 1;
  }
  var oneForward = index + 1;
  if (oneForward >= nodes.length ) {
    oneForward = 0;
  }
  if (pics[index] == undefined) {
    img_buff = new Image(w,h);
    if( nodes[index] ) {
      img_buff.src = nodes[index].getAttribute( "href" );
      pics[index]  = img_buff;
    }
  }
  
  if (pics[oneForward] == undefined) {
    img_buff = new Image(w,h);
    
    if( nodes[oneForward] )  {
      img_buff.src = nodes[oneForward].getAttribute( "href" );
      pics[oneForward] = img_buff;
    }
  }
  
  if (pics[oneBack] == undefined) {
    img_buff      = new Image(w,h);
    img_buff.src  = nodes[oneBack].getAttribute( "href" );
    pics[oneBack] = img_buff;
  }
}

// turn semantic, search- & machine-readable thumb links into fancy gallery links
function dhtmlize_thumbs() {
  if (document.images) {
    var thumbs = $j('#tinies a');
    var c      = 0;
    thumbs.each(function() {
      this.setAttribute("href", "#" + c);
      // IE is clumsy and can't close over these, so we help it. poor IE.
      var ie_safe_closure = big_thumbs[c].src;
      var ie_safe_closure_2  = c;
      this.onclick     = function() { return jump_to( ie_safe_closure_2 ); };
      c++;
    });
  }
}

// update thumb highlight state:  
function update_thumbs( prev_idx, new_idx ) {
  var old_thumb = $j('#tiny_thumb_' + prev_idx);
  old_thumb.removeClass('current');
  var new_thumb = $j('#tiny_thumb_' + new_idx);
  new_thumb.addClass('current');
}

// clear transparent advance button -- after first click, the space occupied by the trans image will be taken up by the next image div
function handle_initial_advance_on_click() {
  if(!use_simple_transitions)
    if(current_img == 0 && $j('#delete_after_first_advance')[0])
      $j('#delete_after_first_advance').remove();
}

function reveal_image( path ) {
  var orientation = 'v';
  if(path && path.match( /-h-/ ))
    orientation = "h";
  
  $j("#on-deck-img").fadeIn();
}

function update_back_next_thumbs( num ) {
  if (typeof(big_thumbs) == 'undefined') {
    return;
  }
  var next_num = num + 1;
  var back_num = num - 1;
  
  if( next_num > big_thumbs.length - 1 )
    next_num = 0;
  if( back_num < 0 )
    back_num = big_thumbs.length - 1;
  
  $j('#nav_next_thumb').attr('src', big_thumbs[next_num].src);
  $j('#nav_back_thumb').attr('src', big_thumbs[back_num].src);
}

function fade_back() {
  preload_images(index_fix(current_img-1))
  handle_initial_advance_on_click();
  var prev = current_img;
  current_img -= 1;
  
  if( current_img < 0 )
    current_img = pics.length - 1;
  
  track_photo_views();
  update_back_next_thumbs( current_img );
  setup_crossfade_buckets( pics[prev].src, pics[current_img].src );
  
  if( ! use_simple_transitions ) {
    update_thumbs( prev, current_img );
    reveal_image( pics[current_img].src );
  }
}
/* This function checks to see how many photos a user has viewed. When they have viewed three photos
 * then google analytics issues a page track to /{model|photographer}/nickname/photoset/{1|2|3..etc}/view */
function track_photo_views() {
  page.photos_viewed["photo" + (current_img) ] = 1;
  var c = 0;
  
  for ( p in page.photos_viewed ) { c++; }
  
  if( c == NUMBER_OF_PHOTOS_PER_VIEW && ! photoset_view_tracked ) {
     track_page_view_custom( '/' + page.artist_role + 's/' + page.artist + '/photosets/' + page.artist_pnum + '/view');
     photoset_view_tracked = true;
  }
}

function fade_next() {
  preload_images(index_fix(current_img+1));
  handle_initial_advance_on_click();
  var prev = current_img;
  current_img += 1;
  
  if (current_img >= pics.length) {
    current_img = 0;
    
    if (!end_of_photoset_showing) {
      show_end_of_set_overlay();
    } else {
      close_all_photo_overlays();
    }
  } else {
    close_all_photo_overlays();
  }
  
  if (current_img == pics.length - 1)
    show_end_of_set_overlay(3000);
  
  track_photo_views();
  update_back_next_thumbs( current_img );
  setup_crossfade_buckets( pics[prev].src, pics[current_img].src );
  if( ! use_simple_transitions ) {
    update_thumbs( prev, current_img );
    reveal_image( pics[current_img].src );
  }
  // FIXME: update url for future bookmarkable #anchors
}

function jump_to( index ) {
  if( current_img == index )
    return;
  
  close_all_photo_overlays();
  preload_images(index)
  handle_initial_advance_on_click();
  var img_to_jump_to = pics[index];
  setup_crossfade_buckets( pics[current_img].src, img_to_jump_to.src );
  
  if( ! use_simple_transitions ) {
    update_thumbs( current_img, index );
    reveal_image( img_to_jump_to.src );
  }
  
  current_img = index;
  track_photo_views();
  update_back_next_thumbs(index);
  
  return false;
}

function setup_crossfade_buckets( about_to_be_faded_OUT_img, new_fading_in_img ){     
  if( use_simple_transitions ) {
    document.getElementById("currently-visible").style.background = '#000 url('+ new_fading_in_img+') no-repeat center center';
  } else {
    // swap the images so that the one that has been faded in is in the currently-visible
    // and the next one to be faded in is waiting in the invisible inner div...
    document.getElementById("currently-visible").style.background = '#000 url('+ about_to_be_faded_OUT_img+') no-repeat center center';
    document.getElementById("on-deck-img").style.display = 'none';
    document.getElementById("on-deck-img").style.background = '#000 url('+new_fading_in_img+') no-repeat center center';
  }
}
  
function do_the_fade() {
  // fade in whatever crossfade is preloaded in the buckets:
  // NOTE: THIS IS NEVER CALLED WHEN IN SIMPLE TRANSITIONS MODE
  $j("#on-deck-img").fadeIn('fast');
}

function fade_and_setup_next_fade( queued_up_img ){
  var current_img, fade_in_img_id;
  
  // first, do the damn fade (fade in whatever crossfade is preloaded in the buckets)
  do_the_fade();
  
  current_img = queued_up_img;
  
  // then, set up the NEXT fade:
  if(queued_up_img == pics.length-1)
    fade_in_img_id = 0;
  else
    fade_in_img_id = queued_up_img+1;
  
  // pass the img paths to setup_crossfade_buckets...
  fade_out_img = pics[current_img];
  fade_in_img = pics[fade_in_img_id];
  
  if( use_simple_transitions ) {
    setup_crossfade_buckets( fade_in_img.src );
  } else {
    setTimeout("setup_crossfade_buckets('" +  fade_out_img.src + "', '" + fade_in_img.src + "')", 3000);
    setTimeout("fade_and_setup_next_fade(" + fade_in_img_id + ")", 4000);   
  }
}

var JUST_VOTED     = 4;
var OUT_OF_VOTES   = 7;
var timeout        = 1;
var has_user_voted = false;
var click_prompt_showing    = false;
var post_vote_showing       = false;
var recommendation_showing  = false;
var end_of_photoset_showing = false;
var is_overlay_animating    = false;
var queued_overlay_request  = null;

function post_vote( magic_rails_url ) {
  //note page.photoset and current image will only be defined on PHOTOSET pages
  //pageTracker._trackPageview("/" + current_user.role + "s/" + current_user.user_id + "/vote/" + page.photoset + "/" + (current_img + 1) );
  if(num_votes_remaining) {
    //unbind additional clicks
    $j('#vote_btn').unbind("click");
    $j('#vote_again_btn').unbind("click");
    $j('#prompt_vote_btn').unbind("click");
    
    $j.post('/artist/photosets/' + page.photoset + '/vote', {funct: 'post'},
    
    function(data){
      if (data === 'success') {
        
        //update the shoutout form
        if (voted_for_this_set == false) {
          $j('#form_vote_and_shout').fadeOut('slow', function(){
            $j('#you_can_shout').fadeIn('slow');
          });
        }
        //update values of: 
        //current_user.avail_votes/num_votes_remaining, current_user.monthly_votes, current_user.purchased_votes, num_votes_for_set, num_fans_for_set
        if (num_votes_remaining == 1) { //fixing a strange bug with disappearing zeros!
          num_votes_remaining = '0';
        } else {
          num_votes_remaining -= 1;
        }
        
        num_votes_for_set   += 1;
        
        if (current_user.monthly_votes > 1) {
          current_user.monthly_votes -= 1;
        } else {
          current_user.purchased_votes -= 1;
        }
        
        if (!voted_for_this_set) {
          num_fans_for_set  += 1;
          voted_for_this_set = 1;
        }
    
        perform_post_vote_activies();
        
        //update elements w/ new values: 
        var vote_noun = num_votes_remaining == 1 ? 'vote' : 'votes';
        
        //left pane: #voting_avail_votes, #voting_vote_noun
        $j('#voting_avail_votes').html(num_votes_remaining);
        $j('#voting_vote_noun').html(vote_noun);
        $j('#top_nav_votes_noun').html(vote_noun);
        
        //menus: #votes_for_this_set, #ajax-votes-left, #ajax-votes-left-sub, #ajax_monthly_votes_left, #ajax_purchased_votes_left
        $j('#votes_for_this_set').empty().html(num_votes_for_set);
        $j('#ajax-votes-left').empty().html(num_votes_remaining);
        $j('#ajax-votes-left-sub').empty().html(num_votes_remaining);
        $j('#ajax_monthly_votes_left').empty().html(current_user.monthly_votes);
        $j('#ajax_purchased_votes_left').empty().html(current_user.purchased_votes);
        
        if(page.artist) {
          track_page_view_custom( '/' + page.artist_role + 's/' + page.artist + '/photosets/' + page.artist_pnum + '/vote'); 
        }
        
      } else if (data === 'insufficient_balance') {
        show_buy_more_votes();
        
        if(page.artist) {
          track_page_view_custom( '/' + page.artist_role + 's/' + page.artist + '/photosets/' + page.artist_pnum + '/no_votes_left' ); 
        }
                
      } else {
        alert('Sorry! There was an application error while processing your vote, please try again.');
      
      }
      
      //rebind the voting aqction to the vote buttons
      setTimeout('reset_vote_btn()', 150);

    });
    
  } else {
    show_buy_more_votes();

    if(page.artist) {
      track_page_view_custom( '/' + page.artist_role + 's/' + page.artist + '/photosets/' + page.artist_pnum + '/no_votes_left' ); 
    }

  }  
}

function get_photo_from_uri() {
  var s = new String(window.location.hash);
  if(!s || s.length == 0)
    return;
  s = s.substring(1, s.length);
  if(isNaN(s) || s < 0 || s > (pics.length - 1))
    return;
  jump_to(s);
}

function reset_vote_btn() {
  $j('#vote_btn').bind('click', function() {
    if (post_vote_showing)
      trigger_vote_fade();
    
    post_vote();
  });
  $j('#vote_again_btn').bind('click', function() {
    trigger_vote_fade();
    post_vote();
  });
}

function update_vote_count_to(i) {
	num_votes_remaining += parseInt(i);
	update_nums_and_nouns();
}

function perform_post_vote_activies() {
  if (post_vote_showing)
    return;
  
  if (check_for_open_overlay('thanks_for_voting'))
    return;
  
  if (set_category != 'set')
    return;
  
  post_vote_showing = true;
  
  show_photo_overlay('thanks_for_voting', 133);
}

function hide_thanks_for_voting() {
  if (!post_vote_showing)
    return;
  
  if (set_category != 'set')
    return;

  hide_photo_overlay('thanks_for_voting');
}

function request_a_set_recommendation() {
  if (recommendation_showing) {
    hide_set_recommendation();
    return;
  }
  
  if (check_for_open_overlay('recommendation'))
    return;
  
  recommendation_showing = true;
  
  show_photo_overlay('recommendation', 133);
}

function hide_set_recommendation() {
  if (!recommendation_showing)
    return;
  
  hide_photo_overlay('recommendation');
}

var photo_overlays_timeout;
function show_click_prompt_overlay() {
  if (click_prompt_showing)
    return;
  
  click_prompt_showing = true;
  
  clearTimeout(photo_overlays_timeout);
  photo_overlays_timeout = setTimeout(function() {
    hide_click_prompt_overlay();
  }, 40400);
  
  show_photo_overlay('click_prompt', 61);
}

function hide_click_prompt_overlay() {
  if (!click_prompt_showing)
    return;
  
  clearTimeout(photo_overlays_timeout);
  hide_photo_overlay('click_prompt');
}

function show_end_of_set_overlay(delay) {
  if (delay > 0) {
    clearTimeout(photo_overlays_timeout);
    photo_overlays_timeout = setTimeout(show_end_of_set_overlay, delay);
    return;
  }
  
  if (end_of_photoset_showing || has_user_voted)
    return;
  
  if (check_for_open_overlay('end_of_photoset'))
    return;
  
  end_of_photoset_showing = true;
  
  show_photo_overlay('end_of_photoset', 133);
}

function hide_end_of_set_overlay() {
  if (!end_of_photoset_showing)
    return;
  
  hide_photo_overlay('end_of_photoset');
}

function show_photo_overlay(id, height) {
  if (display_set_overlays) {
    $j("#photo_overlays").css({display: 'block'});
    $j("#photo_overlays #" + id).animate({top: 534 - height}, 400, "swing");
  };
}

function hide_photo_overlay(id) {
  if (display_set_overlays) {
    is_overlay_animating = true;
    $j("#photo_overlays #" + id).animate({top: 534}, 400, "swing", function() {
      photo_overlay_hidden();
    });
  }
}

function photo_overlay_hidden() {
  is_overlay_animating    = false;
  click_prompt_showing    = false;
  post_vote_showing       = false;
  recommendation_showing  = false;
  end_of_photoset_showing = false;
  
  $j("#photo_overlays").css({display: 'none'});
  
  if (queued_overlay_request != null) {
    switch (queued_overlay_request) {
      case 'recommendation' :
        request_a_set_recommendation();
        break;
      case 'thanks_for_voting' :
        perform_post_vote_activies();
        break;
      case 'end_of_photoset' :
        show_end_of_set_overlay();
        break;
    }
    
    queued_overlay_request = null;
  }
}

function check_for_open_overlay(id) {
  clearTimeout(photo_overlays_timeout);
  
  if (click_prompt_showing || post_vote_showing || recommendation_showing || end_of_photoset_showing) {
    queued_overlay_request = id;
    
    if (!is_overlay_animating)
      close_all_photo_overlays();
    
    return true;
  }
  
  return false;
}

function close_all_photo_overlays() { // also called from fade_next()
  clearTimeout(photo_overlays_timeout);
  hide_click_prompt_overlay();
  hide_set_recommendation();
  hide_thanks_for_voting();
  hide_end_of_set_overlay();
}

function update_voting_UI( state ) {
  has_user_voted = true;
  
  switch( state ) {
    case JUST_VOTED:
      
      break;
    case OUT_OF_VOTES:
      show_buy_more_votes();
      break;
    default:
      alert( "update_voting_UI(): un-handled state: " + state );
  }
}

function view_all() {
	$j("#back_next").slideToggle(500, function() {
		$j("#tinies").slideToggle(500);
	});
  // new Effect.BlindUp('back_next', {duration: 0.5, afterFinish: function() {  new Effect.BlindDown( 'tinies', {duration: 0.5} ); }});
	$j("#view_all_link").hide();
  $j("#show_back_next_nav_link").show();
}

function show_back_next_nav() {
	$j("#tinies").slideToggle(500, function() {
		$j("#back_next").slideToggle(500);
	});

  $j("#show_back_next_nav_link").hide();
	$j("#view_all_link").show();
}

function show_why_vote() {
  $j('#voting div.content').animate({height: 415});
  
  $j('#voting div.footer span.open').css({display: 'inline'});
  $j('#voting div.footer span.close').css({display: 'none'});
}

function hide_why_vote() {
  $j('#voting div.content').animate({height: 93});
  
  $j('#voting div.footer span.open').css({display: 'none'});
  $j('#voting div.footer span.close').css({display: 'inline'});
}

function init_overlays(jsonData) {
  // Recommended
  $j('#recommendation').append('<h2>' + jsonData.recommendation.h1 + '</h2><ul></ul>');
  create_photo_set_from_json($j('#recommendation ul')[0], jsonData.recommendation.ul.li);
  
  // End Of Set
  $j(jsonData.end_of_set.div).each(function() {
    switch (this._class.toLowerCase()) {
      case 'yes' :
        $j('#end_of_photoset #prompt_vote').append('<h2>' + this.h1 + '</h2><div></div>');
        switch(current_user.classification) {
          case 'visitor' : $j('#end_of_photoset #prompt_vote div').append('<p>' + this.ul.li[0] + '</p><a id="public_vote_btn" href="/join">I Love It!</a><p>' + this.ul.li[1] + '</p>');
          default        : $j('#end_of_photoset #prompt_vote div').append('<p>' + this.ul.li[0] + '</p><a id="prompt_vote_btn">I Love It!</a><p>' + this.ul.li[1] + '</p>');
        }
        break;
      case 'no' :
        $j('#end_of_photoset div.other_photo_sets').append('<h2>' + this.h1 + '</h2><ul></ul>');
        create_photo_set_from_json($j('#end_of_photoset div.other_photo_sets ul')[0], this.ul.li);
        break;
    }
  });
  
  // Thanks For Voting
  $j(jsonData.thanks.div).each(function() {
    switch (this._class.toLowerCase()) {
      case 'vote_again' :
        $j('#thanks_for_voting #vote_again').append('<h2>' + this.h1 + '</h2><dl><dt></dt><dd></dd></dl><h3>' + this.h2 + '</h3>');
        
        $j(this.a).each(function() {
          switch (this._class.toLowerCase()) {
            case 'profile' :
              $j('#thanks_for_voting #vote_again dl dt').append('<a href="' + this.href + '" title="' + this.title + '""><img src="' + this.img.src + '" alt="' + this.img.alt + '" width="30" height="30" /></a>');
              $j('#thanks_for_voting #vote_again dl dd').append(this.img.alt + '<br /><a href="' + this.href + '" title="' + this.title + '">' + this.title + '</a>');
              break;
            case 'vote' :
              $j('#thanks_for_voting #vote_again').append('<a id="vote_again_btn">Yeah!</a>');
              break;
          }
        });
        break;
      case 'other_photo_sets' :
        $j('#thanks_for_voting div.other_photo_sets').append('<h2>' + this.h1 + '</h2><ul></ul>');
        create_photo_set_from_json($j('#thanks_for_voting div.other_photo_sets ul')[0], this.ul.li);
        break;
    }
  });
  
  // Vote Buttons
  $j('#prompt_vote_btn').bind('click', function() {
    post_vote();
  });
  $j('#vote_again_btn').bind('click', function() {
    trigger_vote_fade();
    post_vote();
  });
}

function create_photo_set_from_json(ulEl, jsonLi) {
  if (jsonLi == null) {
    return;
  }
  
  $j(jsonLi).each(function() {
    $j(ulEl).append('<li class="' + this.a.attribute_to + '"><a href="' + this.a.href + '" title="' + this.a.title + '"><img src="' + this.a.img.src + '" alt="' + this.a.title + '" width="64" height="64" /></a></li>');
  });
}

function trigger_vote_fade() {
  $j('#back_fade').css({display: 'block', opacity: '1'});
  $j('#back_fade').animate({opacity: '0'}, 450, vote_fade_complete);
}

function vote_fade_complete() {
  $j('#back_fade').css('display', 'none');
}

function show_top_fans() {
  $j('#top_fans_of_set').animate({height: '154px'});
  
  timeout = setTimeout('$j("#top_fans_of_set").animate({height: "1px"})', 6000);
}

function hide_top_fans() {
  $j('#top_fans_of_set').animate({height: '1px'});
}

function toggle_top_fans() {
  if (parseInt($j('#top_fans_of_set').height()) < 20) {
    show_top_fans();
  } else {
    hide_top_fans();
  }
}

// This code checks the document and waits until it's ready to be manipulated
$j(document).ready(function() {
  $j('#voting div.content').height(93);
  init_fader(); 
  
  $j("#photo_overlays #hit_area").bind('click', function() {
    fade_next();
  });
  $j("#photo_overlays #click_prompt").bind('click', function() {
    fade_next();
  });
  $j("#photoset #title").bind('click', function() {
    fade_next();
  });
  $j('#vote_btn').bind('click', function() {
    post_vote();
  });
  $j('#top_fans_vote_btn').bind('click', function() {
    post_vote();
  });
  
  if (flash_available) {
    upgrade_player_to_flash_version();
  }
  
  $j('#set_top_fans').hover(function() {
    clearTimeout(timeout);
  }, function() {
    timeout = setTimeout('$j("#top_fans_of_set").animate({height: "1px"})', 6000);
  });
});

$j(window).load(function() {
  if (!flash_available && set_category == 'set') {
    photo_overlays_timeout = setTimeout(show_click_prompt_overlay, 1000);
    
    $j.ajax({
        url: OVERLAY_JSON_PATH,
        dataType: 'json',
        success: function(result) {
          init_overlays(result.overlays);
        }
      });
  }

  get_photo_from_uri();
});


var current_page = 1;
var per_page = 10;

$j(document).ready(function(){

  $j('#more_shoutouts').click(function(){
    current_page++;
  
    $j.getJSON('/photosets/'+ page.photoset +'/shoutouts.json?page='+current_page+'&per_page='+per_page, function(data) {
    
      if (data.length < per_page) {
        $j('#more_shoutouts').hide();
      }
      
      //top_shoutout_data = data; // this stores the json into a variable: will be helpful when we paginate
      $j.each(data, function(i,item){
      
        x = 
        //clone the divs
        $j('#clone_this_shoutout').clone()
          .attr({id:  'top_fan_page' + current_page + '_' + i})
          .appendTo('#top_fan_shouts');
          
        //populate the thumbnail
        $j('#top_fan_page' + current_page + '_' + i + ' .shoutout_icon').html('<img src="'+ item.thumbnail +'" height="62px" width="62px" alt="" />');
        var time_noun = item.votes == 1 ? 'time' : 'times';
        //populate the text
        $j('#top_fan_page' + current_page + '_' + i +  ' .shoutout_text').html('<p><a href="'+ item.profile +'">'+ item.nickname +'</a> (voted '+ item.votes +' '+ time_noun +')</p><p>&ldquo;'+ item.shoutout +'&rdquo;</p>');
        
        //show the item
        $j('#top_fan_page' + current_page + '_' + i).fadeIn('fast');
      });
    });
    
    $j.getJSON('/photosets/'+ page.photoset +'/shoutouts.json?sort=recent&page='+current_page+'&per_page='+per_page, function(data) { 
      //recent_shoutout_data = data; // this stores the json into a variable: will be helpful when we paginate
      $j.each(data, function(i,item){
        //clone the divs
        $j('#clone_this_shoutout').clone()
          .attr({id:  'recent_fan_page'+ current_page + '_' + i})
          .appendTo('#recent_fan_shouts');
        
        //populate the thumbnail
        $j('#recent_fan_page'  + current_page + '_' + i +  ' .shoutout_icon').html('<img src="'+ item.thumbnail +'" height="62px" width="62px" alt="" />');
  
        //populate the text
        $j('#recent_fan_page'  + current_page + '_' + i + ' .shoutout_text').html('<p><a href="'+ item.profile +'">'+ item.nickname +'</a> (last voted '+ item.last_voted +' ago)</p><p>&ldquo;'+ item.shoutout +'&rdquo;</p>');
  
        //show the item
        $j('#recent_fan_page' + current_page + '_' + i).fadeIn('fast');
      });
    });
  });

  $j('#form_vote_and_shout #shoutout').click(function() { $j(this).val(''); });
  $j('#form_shout #shoutout').click(function() { 
    $j(this).val('');
    $j('#form_shout #shoutout').unbind('click'); 
  });
  
  $j('#form_vote_and_shout #shoutout').keyup(function() {
    shout = '"' + $j(this).val() + '"';
    shout = shout.replace(/(<\/?)script/g,"$1noscript");
    $j('#preview_vote_and_shout').text(shout).html();
  });
  
  $j('#form_shout #shoutout').keyup(function() {
    shout = '"' + $j(this).val() + '"';
    shout = shout.replace(/(<\/?)script/g,"$1noscript");
    $j('#preview_shout').text(shout).html();
  });
  
  $j('#form_edit #shoutout').keyup(function() {
    shout = '"' + $j(this).val() + '"';
    shout = shout.replace(/(<\/?)script/g,"$1noscript");
    $j('#preview_edit').text(shout).html();
  });
  
  var vns_validator = $j("#form_vote_and_shout").validate({
	rules: {
		content: { required: true, minlength: 4, maxlength: 200 }
	},
	// the errorPlacement has to take the table layout into account
	errorPlacement: function(error, element) {
	  error.appendTo('#form_vote_and_shout .val_error');
	}
  });

  var s_validator = $j("#form_shout").validate({
	rules: {
		content: { required: true, minlength: 4, maxlength: 200 }
	},
	// the errorPlacement has to take the table layout into account
	errorPlacement: function(error, element) {
	  error.appendTo('#form_shout .val_error');
	}
  });

  var e_validator = $j("#form_edit").validate({
	rules: {
		content: { required: true, minlength: 4, maxlength: 200 }
	},
	// the errorPlacement has to take the table layout into account
	errorPlacement: function(error, element) {
	  error.appendTo('#form_edit .val_error');
	}
  });
});

$j(window).load( function(){

  $j.getJSON('/photosets/'+ page.photoset +'/shoutouts.json?page='+current_page+'&per_page='+per_page, function(data) {
    if (data.length > 0) {
      $j('#shoutouts_container').show();
    } 
    //top_shoutout_data = data; // this stores the json into a variable: will be helpful when we paginate
    $j.each(data, function(i,item){
      //clone the divs
      $j('#clone_this_shoutout').clone()
        .attr({id:  'top_fan_page' + current_page + '_' + i})
        .appendTo('#top_fan_shouts');
        
      //populate the thumbnail
      $j('#top_fan_page' + current_page + '_' + i +  ' .shoutout_icon').html('<img src="'+ item.thumbnail +'" height="62px" width="62px" alt="" />');
      var time_noun = item.votes == 1 ? 'time' : 'times';
      //populate the text
      $j('#top_fan_page' + current_page + '_' + i +  ' .shoutout_text').html('<p><a href="'+ item.profile +'">'+ item.nickname +'</a> (voted '+ item.votes +' '+ time_noun +')</p><p>&ldquo;'+ item.shoutout +'&rdquo;</p>');
      
      //show the item
      $j('#top_fan_page'  + current_page + '_' + i).fadeIn('fast');
    });
  });
  
  
  $j.getJSON('/photosets/'+ page.photoset +'/shoutouts.json?sort=recent&page='+current_page+'&per_page='+per_page, function(data) {
      if (data.length == per_page) {
        $j('#more_shoutouts').show();
      }
   
    //recent_shoutout_data = data; // this stores the json into a variable: will be helpful when we paginate
    $j.each(data, function(i,item){
      //clone the divs
      $j('#clone_this_shoutout').clone()
        .attr({id:  'recent_fan_page' + current_page + '_' + i})
        .appendTo('#recent_fan_shouts');
      
      //populate the thumbnail
      $j('#recent_fan_page' + current_page + '_' + i + ' .shoutout_icon').html('<img src="'+ item.thumbnail +'" height="62px" width="62px" alt="" />');

      //populate the text
      $j('#recent_fan_page'  + current_page + '_' + i + ' .shoutout_text').html('<p><a href="'+ item.profile +'">'+ item.nickname +'</a> (last voted '+ item.last_voted +' ago)</p><p>&ldquo;'+ item.shoutout +'&rdquo;</p>');

      //show the item
      $j('#recent_fan_page'  + current_page + '_' + i).fadeIn('fast');
    });
  });
});