var currentItemId  = false;
var ajax_ratingURL = false;
var ajax_flagURL   = false;
var ajax_editURL   = false;
var ajax_deleteTagURL = false;

jQuery(document).ready(function(){
  // Login link -> Login form
  if (jQuery('#login').size()) {
    jQuery('#login').click(doHideLoginLink);
  }
  
  // Safe Search toggle on homepage
  if (jQuery('#ss-toggle-link').size()) {
    jQuery('#ss-toggle-link').click(toggleSafeSearch);
    updateSafeSearchUI();
  }
  
  // Focus on the search field if it's there
  if (jQuery('#q').size()) {
    jQuery('#q').select().focus();
  }
});

// Handle default values in text fields
function formDefault(selector, default_val) {
  if (jQuery(selector).val() == '') { jQuery(selector).val(default_val); }
  jQuery(selector).focus(function() { if (jQuery(selector).val() == default_val) { jQuery(selector).val(''); } });
  jQuery(selector).blur(function() { if (jQuery(selector).val() == '') { jQuery(selector).val(default_val); } });
}

function doHideLoginLink() {
  jQuery('#login-signup').css('position', 'relative');
  jQuery('#login-signup').fadeOut('normal', function(){
    doShowLoginForm();
  });
}

function doShowLoginForm() {
  if (jQuery('#login-error').size()) {
    jQuery('#login-error').remove();
  }
  jQuery('#account-func').append('<div id="login-form-wrap" class="block"><form id="login-form" method="post" action="' + ajax_loginURL + '"> \
                              <label id="login-label">Login</label> \
                              <input type="text" id="username" name="username" value="email address / username" class="login-input" /> \
                              <input type="password" id="password" name="password" value="password" class="login-input" /> \
                              <input type="submit" value="submit" id="login-btn" class="button" /> \
                              </form></div>');
  jQuery('#login-form-wrap').fadeIn('normal', function(){
    jQuery('#username').select().focus();
  });
}

function toggleSafeSearch() {
  if (jQuery('#safesearch').val() == 'true') {
    // Change Field
    jQuery('#safesearch').val('false');
    updateSafeSearchUI();
    setting = 'false';
  } else {
    // Change Field
    jQuery('#safesearch').val('true');
    updateSafeSearchUI();
    setting = 'true';
  }
  jQuery.get(ajax_userSafeSearchURL, { set: setting }, function(data, status){});
}

function updateSafeSearchUI() {
  if (jQuery('#safesearch').val() == 'true') {
    // Change Background
    jQuery('#ss-toggle-link').css('background-image', 'url("/images/dot-green.png")');
    
    // Change Text
    jQuery('#ss-toggle-link').html('Safe Search <strong>On</strong>');
  } else {
    // Change Background
    jQuery('#ss-toggle-link').css('background-image', 'url("/images/dot-red.png")');
    
    // Change Text
    jQuery('#ss-toggle-link').html('Safe Search <strong>Off</strong>');
  }
}

function sortSearch(sort, submit) {
  jQuery('#sortsearch').val(sort);
  if (submit) {
    jQuery('#searchform').submit();
  }
}

function showItemEdit(item_id, dom_id) {
  if (!dom_id) {
    dom_id = '#img-' + item_id;
  }

  // AJAX request to load Item details via JSON
  request = ajax_resultDetailURL + item_id;
  response = jQuery.ajax({  dataType: 'json',
                            url: request,
                            success: function(item, status){
                              renderResultBox(item, dom_id, 'edit-pop');
                            },
                            error: function(xmlhttp, status, error){
                              alert(status + ' ' + error);
                            }
                        });
}


/**
 * Load Item details and render the popup box for a search result.
 */
function showResultDetail(item_id, dom_id) {
  if (!dom_id) {
    dom_id = '#img-' + item_id;
  }

  // AJAX request to load Item details via JSON
  request = ajax_resultDetailURL + item_id;
  response = jQuery.ajax({  dataType: 'json',
                            url: request,
                            success: function(item, status){
                              renderResultBox(item, dom_id, 'result-pop');
                            },
                            error: function(xmlhttp, status, error){
                              alert(status + ' ' + error);
                            }
                        });
}

/**
 * Renders the actual search results detail box from a DOM template.
 * Does all the replacements from the item Object
 */
function renderResultBox(item, dom_id, template) {
  offset = jQuery(dom_id).offset();
  
  // Set up the popup window
  jQuery('.' + template + '-template')
    .clone(true)
    .appendTo('body')
    .css({top: (offset.top - 100) + 'px',
          left: (offset.left + 120) + 'px'})
    .removeClass(template + '-template')
    .addClass(template)
    .addClass(template + '-' + item.item_id);
    
  // Do string replacements
  jQuery.each(item, function(key, val){
    regex = eval("/#"+key+"#/ig");
    jQuery('.' + template + '-' + item.item_id).html(jQuery('.' + template + '-' + item.item_id).html().replace(regex, val));
  });
  
  // Set up item-sepecific variables
  currentItemId  = item.item_id;
  ajax_ratingURL = item.rate_url;
  ajax_flagURL   = item.flag_url;
  ajax_editURL   = item.edit_url;
  ajax_deleteTagURL = item.deletetag_url;
  
  jQuery('#canvas').click(function(){ closeResultBox(template); });
  
  // Show it
  jQuery('.' + template).fadeIn('fast', function(){
    if (template == 'edit-pop') {
	    jQuery('.edit-pop .item').hover(function() {
	      jQuery(this).append('<div class=\"change-img-overlay\"><a href=\"#\" onclick=\"return uploadNewImage();\">Change this Photo</a></div>');
	    }, function() {
	      jQuery('.change-img-overlay').fadeOut('fast', function(){ jQuery(this).remove(); });
	    });
	  }
  });
}

function uploadNewImage() {
  jQuery('.edit-pop .item').slideUp('normal', function(){
    jQuery('.edit-pop .new_img').slideDown();
  });
  return false;
}

function deleteTag(id, tag) {
  if (!confirm('Are you sure you want to remove the tag \'' + tag + '\' from this upload?')) {
    return false;
  }
    
  // Send AJAX request to delete the tag from the DB
  jQuery.post(ajax_deleteTagURL + tag, { id: id, tag: tag }, function(data, status){
    if (data == 'SUCCESS') {
      // Remove the tag from the DOM to avoid confusion
      jQuery('#'+tag+'-'+id).fadeOut('fast', function(){ jQuery(this).remove(); });
    } else {
      alert('You cannot do that!');
    }
  });
}

function closeResultBox(template) {
  if (jQuery('.' + template).size()) {
    currentItemId  = false;
    ajax_ratingURL = false;
    ajax_flagURL   = false;
    ajax_editURL   = false;
    ajax_deleteTagURL = false;
    jQuery('.' + template).fadeOut('fast', function(){ jQuery(this).remove(); });
    jQuery('#canvas').unbind('click');
  }
}

function rateItem(rate) {
  request = ajax_ratingURL + rate;
  jQuery.ajax({ url: request,
                success: function(str, status){
                   jQuery('.result-pop-'+currentItemId+' .rating').slideUp('fast', function(){
                     jQuery('.result-pop-'+currentItemId+' .rating-block').html(str).slideDown('normal');
                   });
                },
                error: function(xmlhttp, status, error){
                  alert(status + ' ' + error);
                }
              });
}

function flagItem() {
  request = ajax_flagURL;
  jQuery.ajax({ url: request,
                success: function(str, status){
                   jQuery('.result-pop-'+currentItemId+' .flag').slideUp('fast', function(){
                     jQuery('.result-pop-'+currentItemId+' .flag').html(str).addClass('result-positive').slideDown('normal');
                   });
                },
                error: function(xmlhttp, status, error){
                  alert(status + ' ' + error);
                }
              });
}

function doItemSaveSuccess(msg) {
  jQuery('.edit-pop .success-msg').addClass('result-positive').html(msg).slideDown('fast');
  setTimeout('closeResultBox(\'edit-pop\'); document.location.href = document.location.href;', 2000);
}

function doItemSaveErrors(data) {
  jQuery.each(data, function(id, msg){
    jQuery('.edit-pop .' + id).addClass('result-negative').html(msg).slideDown();
  });
}

function clearItemErrors() {
  jQuery.each(['title_msg', 'url_msg'], function(x,id){
    jQuery('.edit-pop .' + id + ':visible').slideUp().html('');
  });
}

function doDeleteItem(item_id) {
  if (confirm('This will permanently delete this upload.\n\nAre you sure?')) {
    request = ajax_deleteURL + item_id;
    jQuery.post(request, {id:item_id}, function(data, status){
      data = eval('('+data+')');
      if (data.success == undefined) {
        // Display error for them
        jQuery('.edit-pop-' + item_id + ' .delete-msg').addClass('result-negative').html(data.error).slideDown();
      } else {
        // Reload page
        document.location.href = document.location.href;
      }
    });
  }
  return false;
}

function showSignupBox() {
  // Show the signup box
  jQuery('#signup-box').css({ left: ((jQuery('body').width() / 2) - (jQuery('#signup-box').width() / 2)) + 'px' }).fadeIn('fast', function(){
    jQuery('#shortname').focus().select();
    jQuery('#canvas').click(function(){ closeSignupBox(); });
  });
}

function closeSignupBox() {
  if (jQuery('#signup-box').size()) {
    jQuery('#signup-box').fadeOut('fast');
    jQuery('#canvas').unbind('click');
  }
}

function submitSignup() {
  jQuery('#signup-msg').slideUp('fast').removeClass('result-negative').removeClass('result-positive').html();
  jQuery.post(ajax_signupURL, 
              { terms:jQuery('#terms:checked').val(),
                shortname:jQuery('#shortname').val(),
                email:jQuery('#signup-email').val() },
              function(data, status){
                if (data.indexOf('<ul') != -1) {
                  viz = 'result-negative';
                } else {
                  viz = 'result-positive';
                }
                jQuery('#signup-msg').addClass(viz).html(data).slideDown();
              });
}

function uploadItem() {
  jQuery('#add-content-box').css({ left: ((jQuery('body').width() / 2) - (jQuery('#add-content-box').width() / 2)) + 'px' }).fadeIn('fast', function(){
    formDefault('#add-content-box #item_title', 'Enter a title');
    formDefault('#add-content-box #item_description', 'How would you describe this website?');
    formDefault('#add-content-box #item_item_new_tags', 'Separate tags with commas');
    jQuery('#canvas').click(function(){ closeContentBox(); });
  });
}

function closeContentBox() {
  if (jQuery('#add-content-box').size()) {
    jQuery('#add-content-box').fadeOut('fast');
    clearUploadErrors();
    jQuery('#canvas').unbind('click');
  }
}

function clearUploadErrors() {
  jQuery.each(['title_msg', 'url_msg', 'item_new_tags_msg', 'item_img_msg'], function(x,id){
    jQuery('#' + id + ':visible').slideUp().html('');
  });
}

function doUploadErrors(data) {
  jQuery.each(data, function(id, msg){
    jQuery('#' + id).addClass('result-negative').html(msg).slideDown();
  });
}

function showUploadConfirm(item) {
  // Close the box they were looking at
  closeContentBox();
  
  // Create a box to show them the details of what they uploaded
  confirm = '<div id="upload-confirm" style="left: ' + ((jQuery('body').width() / 2) - (150 / 2)) + 'px;"> \
						  <div class="item">' + item.img + '</div> \
						  <div class="hr"><hr /></div> \
						  <h2>' + item.title + '</h2> \
						  <p>' + item.description + '</p> \
						  <p class="tags">Tags: ' + item.tags + '</p> \
						  <div class="hr"><hr /></div> \
						  <p class="success">Successfully uploaded</p> \
						  <p class="launch"><a href="' + item.url + '" target="_blank">Launch the Website</a></p> \
						  <p class="close"><a href="#" onclick="closeContentConfirmBox(); return false;">close this window</a></p> \
						</div>';
  
  // Show a new box, using the item details
  jQuery('body').append(confirm).fadeIn('fast', function(){
    jQuery('#canvas').click(function(){ closeContentConfirmBox(); });
  });
}

function closeContentConfirmBox() {
  if (jQuery('#upload-confirm').size()) {
    jQuery('#upload-confirm').fadeOut('fast', function(){ jQuery(this).remove(); });
    jQuery('#canvas').unbind('click');
    document.location.href = document.location.href;
  }
}

// Profile editing defaults
default_user_shortname = 'Username/Full Name';
default_user_bio       = 'How would you describe yourself? I mean if someone actually wanted to know?';
default_user_city      = 'City';
default_user_state     = 'State';
default_user_password  = 'Password';

function editProfile() {
  jQuery('#edit-profile').clone(true).attr('id', 'edit-profile-open').appendTo('body').css({ left: ((jQuery('body').width() / 2) - (jQuery('#edit-profile').width() / 2)) + 'px' }).fadeIn('fast', function(){
    formDefault('#edit-profile-open .user_bio', default_user_bio);
    formDefault('#edit-profile-open .user_shortname', default_user_shortname);
    url = jQuery('#edit-profile-open .user_url').val();
    if (url == 'http://' || url == '') {
      jQuery('#edit-profile-open .user_url').val('http://');
    }
    formDefault('#edit-profile-open .user_city', default_user_city);
    formDefault('#edit-profile-open .user_state', default_user_state);
    formDefault('#edit-profile-open .user_password', default_user_password);
    formDefault('#edit-profile-open .user_password_confirm', default_user_password);
    jQuery('#edit-profile-open .user_shortname').focus().select();
    jQuery('#edit-profile-open .user_bio').focus(function(){ jQuery(this).select(); }); // Automatically select the description text to make things faster for keyboard people
    jQuery('#canvas').click(function(){ closeEditProfile(); });
  });
}

function saveProfile() {
  if (jQuery('#edit-profile-open .user_shortname').val() == default_user_shortname) {
    jQuery('#edit-profile-open .user_shortname').val('');
  }
  if (jQuery('#edit-profile-open .user_url').val() == 'http://') {
    jQuery('#edit-profile-open .user_url').val('');
  }
  if (jQuery('#edit-profile-open .user_bio').val() == default_user_bio) {
    jQuery('#edit-profile-open .user_bio').val('');
  }
  if (jQuery('#edit-profile-open .user_city').val() == default_user_city) {
    jQuery('#edit-profile-open .user_city').val('');
  }
  if (jQuery('#edit-profile-open .user_state').val() == default_user_state) {
    jQuery('#edit-profile-open .user_state').val('');
  }
  if (jQuery('#edit-profile-open .user_password').val() == default_user_password) {
    jQuery('#edit-profile-open .user_password').val('');
  }
  if (jQuery('#edit-profile-open .user_password_confirm').val() == default_user_password) {
    jQuery('#edit-profile-open .user_password_confirm').val('');
  }
  jQuery.post(ajax_profileURL, jQuery('#edit-profile-open form').serialize(), function(data, status) {
    if (data.indexOf('{') != -1) { // JSON response
      doProfileErrors(eval('('+data+')'));
    } else {
      jQuery('#edit-profile-open .success-msg').addClass('result-positive').html(data).slideDown('fast');
      setTimeout('closeEditProfile()', 2000);
    }
  });
  
  return false;
}

function doProfileErrors(data) {
  jQuery.each(data, function(id, msg){
    jQuery('#edit-profile-open .' + id).addClass('result-negative').html(msg).slideDown();
  });
}

function clearProfileErrors() {
  jQuery.each(['shortname_msg', 'bio_msg', 'url_msg', 'email_msg', 'password_msg'], function(x,id){
    jQuery('#edit-profile-open .' + id + ':visible').slideUp().html('');
  });
}

function closeEditProfile() {
  if (jQuery('#edit-profile-open').size()) {
    jQuery('#edit-profile-open').fadeOut('fast', function(){ jQuery(this).remove(); });
    jQuery('#canvas').unbind('click');
  }
}

function inviteFriends() {
  jQuery('#invite').clone(true).attr('id', 'invite-open').appendTo('body').css({ left: ((jQuery('body').width() / 2) - (jQuery('#invite').width() / 2)) + 'px' }).fadeIn('fast', function(){
    formDefault('#invite-open #recipients', 'Email addresses, separated by commas.');
    formDefault('#invite-open #message', 'Tell them how wonderful Gurutoy.com is, so they know what they\'re getting themselves into.');
    jQuery('#canvas').click(function(){ closeInviteFriends(); });
  });
}

function sendInvites() {
  // Make sure recipients looks like at least one email
  if (!validateEmailString(jQuery('#invite-open .recipients').val())) {
    // If not, set error message and bail
    jQuery('#invite-open .recipients-msg').addClass('result-negative').html('That doesn\'t look like a valid email address.').slideDown('fast');
    return false;
  }
  
  // Send via AJAX
  jQuery.post(ajax_invitesURL, jQuery('#invite-open form').serialize(), function(data, status) {
    jQuery('#invite-open .sent-msg').addClass('result-positive').html(data).slideDown('fast');
    setTimeout('closeInviteFriends()', 2000);
  });
  
  return false;
}

function validateEmailString(str) {
  // Get an array of potential emails
  if (str.indexOf(',') != -1) {
    emails = str.split(',');
  } else {
    emails = Array(str);
  }
  
  // Clean the array up and validate on the way through
  space_re = / /gi;
  email_re = /^[a-z\d\.\-\+]+@[a-z\d\.\-]{2,}$/i;
  for (e = 0; e < emails.length; e++) {
    emails[e] = emails[e].replace(space_re, '');
    if (!emails[e].match(email_re)) {
      return false;
    }
  }
  
  return true;
}

function clearInviteErrors() {
  jQuery('#invite-open .recipients-msg').slideUp('fast').removeClass('result-negative').html('');
}

function closeInviteFriends() {
  if (jQuery('#invite-open').size()) {
    jQuery('#invite-open').fadeOut('fast', function(){ jQuery(this).remove(); });
    jQuery('#canvas').unbind('click');
  }
}

function uploadNewAvatar() {
  jQuery('#change-avatar').clone(true).attr('id', 'change-avatar-open').appendTo('body').css({ left: ((jQuery('body').width() / 2) - (jQuery('#change-avatar').width() / 2) - 100) + 'px' }).fadeIn('fast', function(){
    jQuery('#canvas').click(function(){ closeNewAvatar(); });
  });
}

function doAvatarErrors(data) {
  jQuery.each(data, function(id, msg){
    jQuery('#change-avatar-open .' + id).addClass('result-negative').html(msg).slideDown();
  });
}

function clearAvatarErrors() {
  jQuery('#change-avatar-open .avatar_msg').slideUp('fast').removeClass('result-negative').html('');
}

function doAvatarSuccess() {
  jQuery('#change-avatar-open .avatar_msg').addClass('result-positive').html('Your avatar has been changed!').slideDown(function(){
    setTimeout(function(){ closeNewAvatar(); document.location.href=document.location.href; }, 2000);
  });
}

function closeNewAvatar() {
  if (jQuery('#change-avatar-open').size()) {
    jQuery('#change-avatar-open').fadeOut('fast', function(){ jQuery(this).remove(); });
    jQuery('#canvas').unbind('click');
  }
}

function deleteUser(hash, id) {
  jQuery.post(ajax_deleteUserURL, { id: id, hash: hash }, function(data, status){
    if (data == 'SUCCESS') {
      document.location.href = ajax_logoutURL;
    } else {
      alert('Something is not working correctly, please contact us to have your account deleted.');
    }
  });
  return false;
}