// Base URL for ajax request
var base = $('base').attr('href') + (location.href.match !== null ? 'index.php/' : null);

// Popup CSS menus
$.fn.dropdown = function() {

	$(this).hover(function(){
		$(this).addClass("hover");
		$('> .dir',this).addClass("open");
		$('ul:first',this).css('visibility', 'visible');
	},function(){
		$(this).removeClass("hover");
		$('.open',this).removeClass("open");
		$('ul:first',this).css('visibility', 'hidden');
	});
}
// Popup menu
$(document).ready(function(){
	$("ul.dropdown li").not('.current').dropdown();
});








// Function for when items added to basket
function add_to_basket() {

  // Check stock
  if($(this).find('select#variant_id option:selected').hasClass('outofstock')) {
    alert('Sorry, the item you selected is out of stock');
    return false;
  }


  // Add basket notification div
  /*
  $('#basket_notification').remove();
  $('#header div.inner').append('<div id="basket_notification"><div></div></div>');
    */

  var button = $(this).find('input[type=submit]');
  $(button).hide();
  $(button).after('<img id="ajax_loader" style="padding-top: 7px" src="plugins/themes/lavenderworld/images/ajax-loader.gif" alt="Loading..." />');

  $.post(base + 'ajax/basket/add', $(this).serialize(), function(data) {

      $(button).show();
      $('#ajax_loader').remove();

      // Update minibasket basket total and number of items
      $('p.inbasket span').text(data.item_count + ' items');
      $('p.total span').html('&pound;' + data.total);

      // Update which the basket notifcation with product details
      var h = '<img src="image.php/' + data.image_id + '/40/40" alt="" />';
      h    += '<h2>' + data.title + '</h2>';
      h    += '<p>Item added to basket</p>';
      $('#basket_notification div').html(h);

      // Animate the product image going into the basket
      var im = $('<img class="productanimation" src="image.php/' + data.image_id + '/300/280" style="display: block; width: 300px; height: 280px; position: fixed" />');
      $('body').append(im);

      // Set initial position
      $(im).css({ left : $('#minibasket').position().left,
                  top  : 200});
                  
      // Start animation
      $(im).animate({ top     : 0,
                      left    : $('#minibasket').position().left,
                      opacity : 0}, 'slow', function() {
                        
        // Remove image
        $(this).remove();

        // Fade in basket notification
        $('#basket_notification').fadeIn('normal', function() {
          window.setTimeout(function() {
            $('#basket_notification').fadeOut('normal');
          }, 3000);
        })

      })
  }, 'json');

  return false;
}


// Function for when swatch selector div is clicked
function swatch_click() {
  // Get selected hex, and hide all other options
  var hex = $(this).attr('id').split('_')[1];
  $('option').hide();
  $('option.colour_' + hex).show();

  // Add selected class to swatch
  $('div.swatch').removeClass('selected');
  $(this).addClass('selected');

  // If currently selected option is now hidden, autoselect the first non-hidden option
  if($('option:selected').is(':hidden'))
    $('select').val($('select option:visible:first').val());
  return false; 
}


// When DOM is ready (images not necessarily ready)
$('document').ready(function() {
  
  // Search box
  $('input[name=q]').addClass('placeholder').focus(function() {
    if($(this).val() == 'Search...') {
      $(this).val('');
      $(this).removeClass('placeholder');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val('Search...');
      $(this).addClass('placeholder');
    }
  });


  // Set up fancybox gallery
  $("a.fancybox").attr('rel', 'gallery').fancybox({type : 'image', titleShow : false});


  
  var bRun = false;

  // Profile gallery with pager and zoom
  $('#mainimage_container img').imagesLoaded(function() {

    if(bRun) {
      return;
    }

    $('#mainimage_container').cycle({
        pager   : '.thumbnails',

        timeout : 0,

        // callback fn that creates a thumbnail to use as pager anchor
        pagerAnchorBuilder: function(idx, slide) {
            var image_id = $(slide).attr('id').split('_')[1];
            var img_src = 'plugins/overlays/image.php/lavenderworld/images/imagebox-s.png/' + image_id + '/90/90';

            // Return pager link with image
            return '<a href="#"><img src="' + img_src + '" /></a>';
        }});



    // Add magnifier icon
    $('a.fancybox').prepend('<img src="plugins/themes/lavenderworld/images/icon-mag.png" alt="" class="magnifier" />');

    bRun = true;

  });


  // Fix small screens
  if(screen.width<1024) {
    $('body').addClass('smallscreen');
  };
  
  // Add radio class to radio fields
  $('input[type=radio]').addClass('radio');

  // Address finders
  $('input[name=billing_address]').addressfinder({
      address_1 : 'input[name=billing_address]',
      address_2 : 'input[name=billing_address_2]',
      town      : 'input[name=billing_town]',
      county    : 'input[name=billing_county]',
      postcode  : 'input[name=billing_postcode]'});

      
  $('input[name=delivery_address]').addressfinder({
      address_1 : 'input[name=delivery_address]',
      address_2 : 'input[name=delivery_address_2]',
      town      : 'input[name=delivery_town]',
      county    : 'input[name=delivery_county]',
      postcode  : 'input[name=delivery_postcode]'});


  // Add basket notification div
  var notify = $('<div id="basket_notification" title="View basket" style="cursor: pointer"><div></div></div>');
  $('#minibasket_container').after(notify);

  // Make click on notification go to basket
  $(notify).click(function() {
    location.href = $('#minibasket').find('a').attr('href');
    return false;
  })



  // Ajax add to basket
  $('form.addtobasket').submit(add_to_basket)

  // Swatch selector
  $('div.swatch').click(swatch_click);

  // Add newline after row of product boxes
  $('.lastinrow').after('<br class="all" />');

  // Make main area full width if sidebar empty
  if($('div#sidebar').text().length == 0)
    $('div#main').addClass('fullwidth');

  // Hide un-expanded product categories, expand when selected
  $('li.current').parent('ul').parent('li').addClass('current_parent');


  // Slide-down product info
  var hidden_div  = $('<div></div>').hide().append($('div.productinfo p').not(':first-child'));

  $('div.productdescr').append(hidden_div);

  var expand_link = $('<a href="#">read more &raquo;</a>');
  $(expand_link).click(function() {
    $(hidden_div).slideDown();
    $(this).hide();
    return false;
  })

  // Add expand link if not empty
  if(!$(hidden_div).is(':empty'))
    $('div.productdescr').append(expand_link);

    



  // Setup main image preloader on product page
  var Im = new Image();
  Im.id = 'mainimage';
  $(Im).load(function() {
    $('#mainimage').hide().attr('src', Im.src).fadeIn();
  })



  // Thumbnail gallery
  $('div.thumbnails a').click(function(ev) {

    ev.stopPropagation();
    ev.preventDefault();

    var a = this;
    $(Im).attr('src', $(a).attr('href'));

    return false;
  })

})
