$(document).ready(function() {

  $('.error').slideDown(1000);

  if ($('#username').val())
    $('#password').focus();
  else
    $('#username').focus();

  window.setTimeout(
    function() {
      $('.flash').slideUp(1000);
    },
    1000
  );

  $('.featured_option').change(set_featured);

  $('.add').click(show_product_form);
  $('.category_folder.cat_shoes').click(function() {
    show_category('shoes');
  });
  $('.category_folder.cat_handbags').click(function() {
    show_category('handbags');
  });
  $('.category_folder.cat_accessories').click(function() {
    show_category('accessories');
  });

  $('.cancel').click(function() {
    $('.product_form').fadeOut(500);
    return(false);
  });

  $('button.save').click(save_product);
  $('button.delete').click(delete_product);

  bind_thumbs();

  $('ul.sortable').sortable({ update: function() {
    var data = $(this).sortable('toArray');
    $.post('/admin/products/sort', { 'product_ids[]': data });
  }});

  $('div#smallScroller').smoothDivScroll({mouseDownSpeedBooster: 2, scrollingSpeed: 7});

  $('.scroller img').click(function() {
    display_product($(this).attr('id').replace('product_', ''));
  });

  $('.scroller img').mouseover(function() {
    $(this).addClass('hover');
  });

  $('.scroller img').mouseout(function() {
    $(this).removeClass('hover');
  });

  if (document.location.hash) {
    var hash = document.location.hash.replace('#', '');
    display_product(hash.substring(0, hash.indexOf('-')));
  }
  else if ($('.scrollableArea').length > 0)
    display_product($('.scrollableArea').children('img').eq(0).attr('id').replace('product_', ''));

  $('.image_nav .next').click(function() {
    var next = $('.scroller img.current').next().not('.placeholder');
    if (next.length > 0) display_product(next.attr('id').replace('product_', ''));
  });

  $('.image_nav .previous').click(function() {
    var prev = $('.scroller img.current').prev();
    if (prev.length > 0) display_product(prev.attr('id').replace('product_', ''));
  });

  $('textarea.tinymce').tinymce({
    script_url: '/javascripts/tinymce/tiny_mce.js',
    theme: 'simple',
    width: 400,
    height: 150
  });

});

function show_category(category) {
  $('tr.admin_category_area').hide();
  $('tr.admin_category_area.cat_' + category).slideDown();
}

function bind_thumbs() {
  $('.admin_thumb').mouseover(function() {
    $(this).children('.edit').show();
  });
  $('.admin_thumb').mouseout(function() {
    $(this).children('.edit').hide();
  });
  $('.edit').click(show_product_form);
}

function delete_product() {
  var product_id = $('#product_id').val();
  if (window.confirm('Are you sure you wish to delete "' + $('#title').val() + '"?')) {
    $('#popup_loading').show();
    $('#popup_buttons').hide();
    $.post('/admin/products/delete', { id: product_id }, function(data) { 
      $('.product_form').fadeOut(500);
      $('#image_' + data.id).parent().remove();
    },
    'json');
  }
}

function set_featured() {
  $('.featured_option').blur();
  $('.featured_load').show();
  $('.featured_category').css('backgroundColor', '#ffff88');
  $.post('/admin/categories/set_featured', { category: $(this).val() }, function(data) {
    $('.featured_load').hide();
    $('.featured_category').animate({ backgroundColor: '#dddddd' }, 1000);
  }, 'json');
}

function show_product_form() {
  form_disabled(false);
  $('#popup_loading').hide();
  $('#popup_buttons').show();
  if ($(this).attr('className') == 'add') {
    $('img.admin_edit_img').attr('src', '#null');
    $('#product_id').val('');
    $('button.delete').hide();
    var href = $(this).attr('href');
    $('#category').selectOptions(href.replace('#add_', ''));
    clear_form();
    $('.product_form').fadeIn(500);
    $(this).blur();
    $('#title').focus();
  }
  else {
    $('#product_id').val($(this).parent().children('img').attr('alt'));
    $('button.delete').show();
    $.get('/products/details/' + $('#product_id').val() + '?' + Math.round(new Date().getTime() / 1000), {}, function(data) {
      $('#title').val(data.title);
      $('#description').val(data.description);
      $('#category').selectOptions(data.category);
      $('#product_image').val('');
      $('img.admin_edit_img').attr('src', data.img_src);
      $('.product_form').fadeIn(500);
      $(this).blur();
      $('#title').focus();
    },
    'json');
  }
  return(false);
}

function save_product() {
  $('#popup_buttons').hide();
  $('#popup_loading').show();
  form_disabled(true);
  if ($('#product_image').val().length > 0) {
    $.ajaxFileUpload({
      url: '/admin/products/upload_image',
      secureuri: false,
      fileElementId: 'product_image',
      dataType: 'json',
      success: function(data, status) {
        var postdata = {
          category: $('#category').val(),
          title: $('#title').val(),
          description: $('#description').val()
        };
        if (data.filename) {
          postdata['img_src'] = '/images/' + data.filename + '_full.jpg';
          postdata['thumb_src'] = '/images/' + data.filename + '_thumb.jpg';
        }
        if ($('#product_id').val().length > 0) postdata['id'] = $('#product_id').val();
        $.post('/admin/products/save', postdata, function(data) {
          if (data.saved) {
            $('.product_form').fadeOut(500);
            var html = '<li class="admin_thumb"><div class="edit"></div><img src="' +  data.thumbnail + '" alt="' + data.id + '" id="image_' + data.id +'" title="' + data.title + '" /></li>'
            if ($('#product_id').val().length > 0)
              $('#image_' + data.id).attr('src', data.thumbnail);
            else {
              $('#' + data.category + '_frame').prepend(html);
            }
            bind_thumbs();
          }
          else {
            alert(data.message);
          }
        }, 'json');
      },
      error: function(data, status, e) {
        alert(e);
      }
    });
  }
  else if ($('#product_id').val().length == 0) {
    alert('Please select a photo.');
    form_disabled(false);
    $('#popup_loading').hide();
    $('#popup_buttons').show();
  }
  else {
    var postdata = {
      id: $('#product_id').val(),
      category: $('#category').val(),
      title: $('#title').val(),
      description: $('#description').val()
    };
    $.post('/admin/products/save', postdata, function(data) {
      if (data.saved) {
        $('.product_form').fadeOut(500);
      }
      else {
        alert(data.message);
      }
    }, 'json');
  }
}

function form_disabled(disable) {
  $('#category').attr('disabled', disable);
  $('#image').attr('disabled', disable);
  $('#title').attr('disabled', disable);
  $('#description').attr('disabled', disable);
}

function clear_form() {
  $('#title').val('');
  $('#description').val('');
  $('#product_image').val('');
}

function display_product(id) {
  var product_thumb = $('img#product_' + id);
  $('.scroller img').removeClass('current');
  product_thumb.addClass('current');
  $('.left_frame h3').html('');
  $('.left_frame .description').html('');
  $('.left_frame strong').hide();
  $('.right_frame div').html('<img class="product_load" src="/graphics/product_load.gif" alt="Loading" />');
  $.get('/products/details/' + id + '?' + Math.round(new Date().getTime() / 1000), {}, function(data) {
    document.location.hash = id + '-' + data.permalink;
    $('.left_frame h3').html(data.title);
    $('.left_frame .description').html(data.description);
    $('.right_frame div').html('<a href ="' + data.img_src.replace('_full', '_large') + '"><img src="' + data.img_src + '" alt="' + data.title + '" /></a>');
    $('.right_frame a').lightBox();
  },
  'json');
}

