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

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

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

  $j('ul#profile_tabs li').click(function(){
    var currDiv = $j('.selected_tab').attr("id").split('nav_')[1] + '_container';
    var nextDiv = $j(this).attr('id').split('nav_')[1] + '_container';

    double_swap($j(this).attr('id'), 'selected_tab');
    $j('#'+currDiv).fadeOut('fast', function(){
      $j('#'+nextDiv).fadeIn('fast');
    });
  });
  
  $j('ul#content_tabs li').click(function(){
    var currDiv = $j('.selected_tabz').attr("id").split('nav_')[1] + '_container';
    var nextDiv = $j(this).attr('id').split('nav_')[1] + '_container';

    double_swap($j(this).attr('id'), 'selected_tabz');
    $j('#'+currDiv).fadeOut('fast', function(){
      $j('#'+nextDiv).fadeIn('fast');
    });
  });

  
  if (window.location.hash == '#wall') {
    var currDiv = $j('.selected_tab').attr("id").split('nav_')[1] + '_container';
    var nextDiv = 'wall_container';

    double_swap('nav_wall', 'selected_tab');
    $j('#'+currDiv).fadeOut('fast', function(){
      $j('#'+nextDiv).fadeIn('fast');
    });
  }

  if ($j.browser.msie === true) {
    $j('p#text_count').empty().html('Maximum Characters: 400');
  } else {
    $j('textarea.grow_this').autogrow();
  }
  
  $j(':input[type=textarea]').textCounting({lengthExceededClass: 'too_big'});
  $j('.nsfw').each( function(){ 
    
    var the_id = $j(this).attr('id');
    var num_only = $j(this).attr('id').split('photoset_')[1];
    
    if ($j.browser['mozilla']) {
      var add_on = 1;
    } else {
      var add_on = 0;
    }
    
    $j('#clone_safemode_overlay').clone()
      .attr({id:  'safemode_' + num_only, title: $j('#'+the_id+' > a').attr('title')})
      .css({left: $j('#'+the_id).position()["left"], top: $j('#'+the_id).position()["top"] + add_on})
      .insertAfter('#photoset_preview');
      
    $j('#safemode_' + num_only + ' a').attr('href', $j('#link_' + num_only).attr('href'));
    
    $j('#safemode_' + num_only).fadeIn('fast');

  });
  
  $j('.must_subscribe').each( function(){ 
    
    var the_id = $j(this).attr('id');
    var num_only = $j(this).attr('id').split('photoset_')[1];
    
    if ($j('body').attr('id') == 'public_profile'){
      var add_on = 0;
    } else if ($j.browser['mozilla']) {
      var add_on = 1;
    } else {
      var add_on = 0;
    }
    
    $j('#clone_must_subscribe_overlay').clone()
      .attr({id:  'must_subscribe_' + num_only, title: $j('#'+the_id+' > a').attr('title')})
      .css({left: $j('#'+the_id).position()["left"], top: $j('#'+the_id).position()["top"] - add_on})
      .insertAfter('#photoset_preview');
      
    $j('#must_subscribe_' + num_only + ' a').attr('href', $j('#link_' + num_only).attr('href'));
    
    $j('#must_subscribe_' + num_only).fadeIn('fast');

  });
	
  //jquery fix for ie6's "no width = 100% not just the width" bug
  $j('#friends_item').css("width", $j('#friends_item').width());
  $j('#fan_item').css("width", $j('#fan_item').width());
  $j('#edit_profile_alert').css("width", $j('#edit_profile_alert').width());
  
  $j('#relationship_text').click(function() { clear_input($j(this).attr("id")); });   

  var ready_message = $j('#relationship_text').val();
  if (ready_message) {
    $j('#friending_text').html(ready_message);
  }

  // the message replacement
  var message = ''; // that's two single quotation-marks at the end
  $j('#relationship_text').keyup(function() {
  message = $j(this).val();
  message = message.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />').replace(/(<\/?)script/g,"$1noscript");
    $j('#friending_text').html(message);
  });


  // **********************************************************************************************************
  // Profile Friend
  $j("#submit_friend_request").click( function () {
    $j(this).val('Submitting...').attr('disabled', 'disabled');
    var message_text = $j("#relationship_text").val();
    var user_id = $j("#user_id").val();
    var user_role = $j('#relationship_user_role').val();


    $j.ajax({ type: "POST", url: "/user/relationships/create_ajax", data: "relationship_text="+message_text+"&user_id="+user_id,
      success: function(data) {
        if (data == 'success') {
          /* tracking code -track successful friend request */
          if( user_role == 'user') {
           track_page_view("FRIEND_TO_USER");
          }
          else if(user_role == 'model') {
           track_page_view("FRIEND_TO_MODEL");
          }
          else if( user_role == 'photographer') {
           track_page_view("FRIEND_TO_PHOT");
          }
          /* tracking code */
          $j("#question").hide();
          $j('#red_flash_msg').append('<h1>Success! Your request was sent!</h1>').corner('9px').show();
          setTimeout('$j("#red_flash_msg").hide().empty()', 7000);
          setTimeout('$j("#click_add_friend").empty()', 500);
        } else {
          $j("#question").hide();
          $j('#red_flash_msg').append('<h1>Something bad happened...</h1>').corner('9px').show();
					$j("#submit_friend_request").removeAttr("disabled");
          setTimeout('$j("#red_flash_msg").hide().empty()', 7000);
        }
      }
     });

  });


  // **********************************************************************************************************
  // Profile Unfriend
  $j("#submit_unfriend_request").click( function () {
    var user_id = $j("#user_id").val();

    $j.ajax({ type: "POST", url: "/user/relationships/destroy_ajax", data: "user_id="+user_id,
      success: function(data) {
        if (data == 'failure') {
          $j("#question").hide();
          $j('#red_flash_msg').append('<h1>FAIL! Something bad happened!</h1>').corner('9px').show();
          setTimeout('$j("#red_flash_msg").hide().empty()', 7000);
        } else {
          $j('#red_flash_msg').append('<h1>Success!</h1>').corner('9px').show();
          $j("#question").hide();
          setTimeout('$j("#red_flash_msg").hide().empty()', 7000);
          setTimeout('$j("#click_add_friend").empty()', 1000);      
        }
      }
     });

  });


  // **********************************************************************************************************
  // Profile Send Email
  $j("#submit_email_message").click( function () {
    var message_subject = $j("#message_subject").val();
    var message_message = $j("#message_message").val();
    var message_recipient = $j("#message_recipient_id").val();
    var message_recipient_role = $j("#message_recipient_role").val();
    var re = /^\s*$/; 
    var subject_input_NOT_OK = message_subject.match(re);
    var message_input_NOT_OK = message_message.match(re);
    
    if (subject_input_NOT_OK) {
      alert('Please type a subject to your message first.');
      return false;
    } else if (message_input_NOT_OK) {
      $j('#message_message')[0].focus();
      alert('Please type a message first.');
      return false;
      
    } else {

      $j("#submit_email_message").val("Submitting...").attr("disabled", "true");

      $j.ajax({ type: "POST", url: "/user/messages/create", data: "message[subject]="+message_subject+"&message[body]="+message_message+"&message[recipient_id]="+message_recipient,
        success: function(data) {
          /* track events of the model sending to the user */
          if(message_recipient_role == 'user') {
            track_page_view('MESSAGE_TO_USER');
          } else if(message_recipient_role == 'photographer') {
            track_page_view('MESSAGE_TO_PHOT');
          } else if(message_recipient_role == 'model') {
            track_page_view('MESSAGE_TO_MODEL');
          }
          $j('#message').hide();
          $j('#red_flash_msg').append('<h1>Success! Your message was sent!</h1>').corner('9px').show();
          setTimeout('$j("#red_flash_msg").hide().empty()', 7000);
          $j("#message_subject").val("");
          $j("#message_message").val("");
          $j("#submit_email_message").val("Send").removeAttr("disabled");
        }

       });
    }

  });


  // **********************************************************************************************************
  // Profile "My Sites" Selector
  function replace_site_text() {  
    var name = $j("#site-selector").val();
    if ($j("#"+name).val()) {
      var pre = $j("#"+name).val().split('!', 2)[0];
      var post = $j("#"+name).val().split('!', 2)[1];
    } else {
      var pre = "http://";
    }

    $j("#site-pretext").empty().append(pre);

    if (post) {
      $j("#site-posttext").empty().append(post);
    } else {
      $j("#site-posttext").empty();    
    }
  }

  $j("#site-selector").change(replace_site_text); //run the fn on change
  replace_site_text(); //run the fn on ready to get the initial url parsed


  // **********************************************************************************************************
  // Friends/Fans Pagination
  function page_icons(type, direction){
    
    // gather some variables
    var current_page = parseInt($j('#'+type+'_current_page').html());
    var total_pages = parseInt($j('#'+type+'_total_pages').html());
    if (direction == 'next') {
      var page_number = current_page + 1;
    } else {
      var page_number = current_page - 1;
    }
    
    // unbind the next/prev buttons
    $j('#prev_'+type+'_with_link').unbind();
    $j('#next_'+type+'_with_link').unbind();
    
    // the next few conditionals set up the navigation for us
    if(page_number == '1') {
      $j('#prev_'+type+'_with_link').hide(); 
      $j('#prev_'+type+'_without_link').show();
    } else {
      $j('#prev_'+type+'_without_link').hide();
      $j('#prev_'+type+'_with_link').show();
    }
    if(page_number == total_pages) {
      $j('#next_'+type+'_with_link').hide(); 
      $j('#next_'+type+'_without_link').show(); 
    } else {
      $j('#next_'+type+'_without_link').hide();
      $j('#next_'+type+'_with_link').show();
    }

    if (type === 'fans'){
      // gather variables - there are two sets of hidden input fields: #fans_next_foo and #fans_previous_bar
      var user_id = $j('#'+type+'_'+direction+'_user_id').val();
      var order_fans = $j('#'+type+'_'+direction+'_order').val();
      var is_a_fan = $j('#'+type+'_'+direction+'_is_a_fan').val();
      var sorted = $j('#fans_sort').val();
      
      // unbind the sorting tabs
      if (sorted === 'top') {
        $j('#loyal_fans_btn').unbind('click');
        $j('#recent_fans_btn').unbind('click');
      } else if (sorted === 'loyal') {
        $j('#top_fans_btn').unbind('click');
        $j('#recent_fans_btn').unbind('click');
      } else {
        $j('#top_fans_btn').unbind('click');
        $j('#loyal_fans_btn').unbind('click');
      }

    } else { // if it is the friends side
      
      // gather variables
      var user_id = $j('#'+type+'_'+direction+'_user_id').val();
      var sorted = $j('#fans_sort').val();

    }

    // hide the div and THEN perform some actions...
    $j('#ff_'+type+'_zone').fadeOut('fast', function(){ 

      // set up the spinner
      $j('#ff_'+type+'_zone').clone() // clone the main container
        .attr('id', type+'_container_2') // change the id so that we don't duplicate div ids
        .empty() // empty out all the contents and (below) refill it with a spinner and Loading... text.
        .html('<p class="centered"><img src="/images/layout/ajax-loader.gif" width="66" height="66" id="temp_spinner" /><br />Loading...</p>')
        .insertBefore('#ff_'+type+'_zone') // insert the new element in the html before the id
        .fadeIn('fast'); // show


      // test which direction we're headed
      if (direction === 'next') {
        
        // update the page number
        $j('#'+type+'_current_page').empty().html(page_number);

        // if we're moving to the last page we need to remove the link from the next button
        if (page_number === total_pages) {
          $j('#next_'+type+'_with_link').fadeOut('fast', function(){
            $j('#next_'+type+'_without_link').fadeIn('fast');
          });      
        }

        // if we were on the first page we need to add the link to the previous tab
        if (current_page === 1) {
          $j('#prev_'+type+'_without_link').fadeOut('fast', function(){
            $j('#prev_'+type+'_with_link').fadeIn('fast');
          });
        }

      } else {
        
        // update the page number
        $j('#'+type+'_current_page').empty().html(page_number);

        // if we were on the second page we need to remove the link to the previous tab
        if (current_page === 1) {
          $j('#prev_'+type+'_with_link').fadeOut('fast', function(){
            $j('#prev_'+type+'_without_link').fadeIn('fast');
          });
        }

        //if we were on the last page and we moved back we need to add the next link back
        if (current_page === total_pages) {
          $j('#next_'+type+'_without_link').fadeOut('fast', function(){
            $j('#next_'+type+'_with_link').fadeIn('fast');
          });
        }

      }


      if (type === 'fans'){
        // update the thumbs
        $j('#ff_fans_zone').empty()  // empty the main container
          .load('/user/profile/fan_page?user_id='+user_id+'&page='+page_number+'&order_fans='+order_fans+'&is_a_fan_of='+is_a_fan, function (){ // load the partial and THEN perform some actions
            $j('#fans_container_2').hide().remove(); // hide and destroy the spinner
            $j('#ff_fans_zone').fadeIn(800); // fade in the new page
            $j('#prev_fans_with_link').click(function(){ page_icons('fans','previous'); });
            $j('#next_fans_with_link').click(function(){ page_icons('fans','next'); });
            
            if (sorted === 'top') {
              $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
              $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
            } else if (sorted === 'loyal') {
              $j('#top_fans_btn').click(function(){ page_sort('top'); });
              $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
            } else {
              $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
              $j('#top_fans_btn').click(function(){ page_sort('top'); });
            }
            
        });

      } else {
        // update the thumbs
        $j('#ff_friends_zone').empty()  // empty the main container
          .load('/user/profile/friend_page?user_id='+user_id+'&page='+page_number, function (){ // load the partial and THEN perform some actions
            $j('#friends_container_2').hide().remove(); // hide and destroy the spinner
            $j('#ff_friends_zone').fadeIn(800); // fade in the new page
            $j('#prev_friends_with_link').click(function(){ page_icons('friends','previous'); });
            $j('#next_friends_with_link').click(function(){ page_icons('friends','next'); });
            
            if (sorted === 'top') {
              $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
              $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
            } else if (sorted === 'loyal') {
              $j('#top_fans_btn').click(function(){ page_sort('top'); });
              $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
            } else {
              $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
              $j('#top_fans_btn').click(function(){ page_sort('top'); });
            }
            
        });

      }

    });  

  }

  function page_sort(direction){
    // gather variables
    var user_id = $j('#fans_user_id').val();
    var is_a_fan = $j('#fans_is_a_fan').val();
    
    $j('#fans_sort').val(direction);
    
    $j('#top_fans_btn').unbind('click').unbind('mouseover').unbind('mouseout').attr('src', '/images/buttons/tab_fans_top_fans_off.png');
    $j('#loyal_fans_btn').unbind('click').unbind('mouseover').unbind('mouseout').attr('src', '/images/buttons/tab_fans_loyal_off.png');
    $j('#recent_fans_btn').unbind('click').unbind('mouseover').unbind('mouseout').attr('src', '/images/buttons/tab_fans_recent_off.png');
    
    $j('#prev_fans_with_link').unbind('click');
    $j('#next_fans_with_link').unbind('click');
    

    $j('#ff_fans_zone').fadeOut('fast', function(){ // hide the div and THEN perform some actions...

      $j('#ff_fans_zone').clone() // clone the main container
        .attr('id', 'fans_container_2') // change the id so that we don't duplicate div ids
        .empty() // empty out all the contents and (below) refill it with a spinner and Loading... text.
        .html('<p class="centered"><img src="/images/layout/ajax-loader.gif" width="66" height="66" id="temp_spinner" /><br />Loading...</p>')
        .insertBefore('#ff_fans_zone') // insert the new element in the html before the id
        .show(); // show

      $j('#ff_fans_zone').empty()  // empty the main container
        .load('/user/profile/fan_page?user_id='+user_id+'&page=1&order_fans='+direction+'&is_a_fan_of='+is_a_fan, function (){ // load the partial and THEN perform some actions
          $j('#fans_container_2').hide().remove(); // hide and destroy the spinner
          $j('#ff_fans_zone').fadeIn('fast'); // fade in the new page

          if (direction === 'top') {
            $j('#top_fans_btn').attr('src', '/images/buttons/tab_fans_top_fans_over.png');
            $j('#loyal_fans_btn').bind('mouseover', function(){ img_over('loyal_fans_btn'); });
            $j('#loyal_fans_btn').bind('mouseout', function(){ img_off('loyal_fans_btn'); });
            $j('#recent_fans_btn').bind('mouseover', function(){ img_over('recent_fans_btn'); });
            $j('#recent_fans_btn').bind('mouseout', function(){ img_off('recent_fans_btn'); });
            $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
            $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
            $j('#prev_fans_with_link').click(function(){ page_icons('fans','previous'); });
            $j('#next_fans_with_link').click(function(){ page_icons('fans','next'); });

          } else if (direction === 'recent') {
            $j('#recent_fans_btn').attr('src', '/images/buttons/tab_fans_recent_over.png');
            $j('#top_fans_btn').bind('mouseover', function(){ img_over('top_fans_btn'); });
            $j('#top_fans_btn').bind('mouseout', function(){ img_off('top_fans_btn'); });
            $j('#loyal_fans_btn').bind('mouseover', function(){ img_over('loyal_fans_btn'); });
            $j('#loyal_fans_btn').bind('mouseout', function(){ img_off('loyal_fans_btn'); });
            $j('#top_fans_btn').click(function(){ page_sort('top'); });
            $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
            $j('#prev_fans_with_link').click(function(){ page_icons('fans','previous'); });
            $j('#next_fans_with_link').click(function(){ page_icons('fans','next'); });

          } else if (direction === 'loyal') {
            $j('#loyal_fans_btn').attr('src', '/images/buttons/tab_fans_loyal_over.png');
            $j('#top_fans_btn').bind('mouseover', function(){ img_over('top_fans_btn'); });
            $j('#top_fans_btn').bind('mouseout', function(){ img_off('top_fans_btn'); });
            $j('#recent_fans_btn').bind('mouseover', function(){ img_over('recent_fans_btn'); });
            $j('#recent_fans_btn').bind('mouseout', function(){ img_off('recent_fans_btn'); });
            $j('#top_fans_btn').click(function(){ page_sort('top'); });
            $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
            $j('#prev_fans_with_link').click(function(){ page_icons('fans','previous'); });
            $j('#next_fans_with_link').click(function(){ page_icons('fans','next'); });

          } else {
            alert('There was an error...');
          }
 
 
          if (parseInt($j('#fans_current_page').html()) > 1) {
           
            $j('#fans_next_page').val('2');
            $j('#fans_previous_page').val('0');
            $j('#fans_current_page').html(1);
            $j('#prev_fans_with_link').fadeOut('fast', function(){
              $j('#prev_fans_without_link').fadeIn('fast');
            });
            
            $j('#next_fans_without_link').fadeOut('fast', function(){
              $j('#next_fans_with_link').fadeIn('fast');
            });
            
          }
          
        });
    });

  }
  
  // Bind the pagination events
  $j('#next_fans_with_link').click(function(){ page_icons('fans','next'); });
  $j('#prev_fans_with_link').click(function(){ page_icons('fans','previous'); });
  $j('#prev_friends_with_link').click(function(){ page_icons('friends','previous'); });
  $j('#next_friends_with_link').click(function(){ page_icons('friends','next'); });
  
  // Bind the sorting events
  $j('#loyal_fans_btn').hover( function(){ img_over('loyal_fans_btn'); }, function(){ img_off('loyal_fans_btn'); });
  $j('#recent_fans_btn').hover( function(){ img_over('recent_fans_btn'); }, function(){ img_off('recent_fans_btn'); });
  $j('#loyal_fans_btn').click(function(){ page_sort('loyal'); });
  $j('#recent_fans_btn').click(function(){ page_sort('recent'); });
  
  // Bind Message/Friending Windows
  $j('#cancel_friending').click(function(){ toggle_div('question'); });
  $j('#close_question_window').click(function(){ toggle_div('question'); });
  $j('#close_message_window').click(function(){ toggle_div('message'); });
  $j('#click_send_message').click(function (){ toggle_div('message'); });
  $j('#click_add_friend').click(function (){ toggle_div('question'); });
  $j('.click_add_friend').click(function (){ toggle_div('question'); });
  $j('.click_send_message').click(function (){ toggle_div('message'); });
  
  
  // Load feeds
  $j.ajax({ 
    type: "GET", 
    url: "/users/" + profile.owner.login + "/feed",
    success: function(data) {
        $j('#feed_container').html(data);
        // Pulled in from actions.js:
        $j('.feed_swap').click( function(){
          double_swap($j(this).attr('id'), 'selected_menu_item');
          track_page_view('TAB_SWITCH');
        });
        $j('#feed').corner('7px cc:#181818');
    }
   });
});  
