var openPopup = 0;
var openPopupStore = 0;
var closingapopupnow = 0;
var closingapopupnowstore = 0;
function apply_search_term(a){
  var search_term = a.find('.search');
  if(search_term.size()>0){
    if($('#keywords').val()==$('#keywords').attr('default')){
      $('#keywords').val(search_term.text()).attr('default', search_term.text());
    }
  }
}

var product_info_config = {
   sensitivity:   2,   // number = sensitivity threshold (must be 1 or higher)
   interval:    100,   // number = milliseconds for onMouseOver polling interval
   timeout:     500,   // number = milliseconds delay before onMouseOut
   out:         function(e) {
     var parent = $(this).parent().parent();
     // don't hide the popup if the mouse pointer within
     if (! $('.infopopupouter', parent).data('hover')) {
       $('.infopopupouter', parent).hide();
     }
   },
   over:        function(e) {
     $('.infopopupouter').hide();
     var parent = $(this).parent().parent();
     $('.product_large_popup', parent).load("/stores/_info-popup/" + $('span:first', parent).text(), function() {
       update_price_format();
       if ($(parent).hasClass('left_popup')) {
        $('img.infopopupback', parent).attr('src', '/themes/osoyou/images/infobox2_popup.png');
        $('.infopopupouter', parent).css({ 'position': 'absolute', 'left': '-505px' , 'top': '100px'});
        $('.infopopup', parent).css('left', '3.3em');
       }
      else {
         $('.infopopupouter', parent).css({ 'position': 'absolute', 'left': '120px' , 'top': '100px'});
      }
       $('.infopopupouter', parent).show();
     });
   }
};

$(document).ready(function() {
if(document.location.pathname == '/'){
  apply_search_term($('#main_hero li').first());
}

var change_secondary_categories = true;

$(function() {
    $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        afterEnd: function(a) {
          apply_search_term(a);
        },
        easing: "linear",
        visible: 1,
      speed: 400,
         btnGo:
      [".imageSliderExt .1", ".imageSliderExt .2",
      ".imageSliderExt .3", ".imageSliderExt .4",
      ".imageSliderExt .5", ".imageSliderExt .6",
      ".imageSliderExt .7", ".imageSliderExt .8",
      ".imageSliderExt .9", ".imageSliderExt .10",
    ".imageSliderExt .11", ".imageSliderExt .12"]
    });

});

$(function() {
    $(".carousel2").jCarouselLite({
        btnNext: ".next2",
        btnPrev: ".prev2",
        easing: "linear",
        visible: 4,
      speed: 400,
         btnGo:
      [".imageSliderExt .1", ".imageSliderExt .2",
      ".imageSliderExt .3", ".imageSliderExt .4",
      ".imageSliderExt .5", ".imageSliderExt .6",
      ".imageSliderExt .7", ".imageSliderExt .8",
      ".imageSliderExt .9", ".imageSliderExt .10",
    ".imageSliderExt .11", ".imageSliderExt .12"]
    });

});

$(function() {
    $(".carousel3").jCarouselLite({
        btnNext: ".next3",
        btnPrev: ".prev3",
        easing: "linear",
        visible: 4,
      speed: 400,
         btnGo:
      [".imageSliderExt .1", ".imageSliderExt .2",
      ".imageSliderExt .3", ".imageSliderExt .4",
      ".imageSliderExt .5", ".imageSliderExt .6",
      ".imageSliderExt .7", ".imageSliderExt .8",
      ".imageSliderExt .9", ".imageSliderExt .10",
    ".imageSliderExt .11", ".imageSliderExt .12"]
    });

});

$(function() {
    $(".carousel4").jCarouselLite({
        btnNext: ".next2",
        btnPrev: ".prev2",
        easing: "linear",
        visible: 9,
      speed: 400,
         btnGo:
      [".imageSliderExt .1", ".imageSliderExt .2",
      ".imageSliderExt .3", ".imageSliderExt .4",
      ".imageSliderExt .5", ".imageSliderExt .6",
      ".imageSliderExt .7", ".imageSliderExt .8",
      ".imageSliderExt .9", ".imageSliderExt .10",
    ".imageSliderExt .11", ".imageSliderExt .12"]
    });

});


  function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show();
    $(this).find(".clothingpointer").stop().fadeTo('fast', 1).show();
  }

  function megaHoverOut(){
    $(this).find(".sub").stop().fadeTo('fast', 0, function() {
      $(this).hide();
    });
    $(this).find(".clothingpointer").stop().fadeTo('fast', 0, function() {
          $(this).hide();
    });
  }

  var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
  };

  $("ul#topnav li .sub").css({'opacity':'0'});
  $("ul#topnav li").hoverIntent(config);

  $("#tabs li a").click(function () {
  $("#tabs li a.active").removeClass("active");
  $(this).addClass("active");
  $(".tab").hide();
  var content_show = $(this).attr("rel");
  $("#"+content_show).fadeIn();
  });

$("#shops").mousedown(function() {

  $(document).find(".shops").css("display", "block");
  $(document).find(".celebrities, .clothing, .accessories").css("display", "none");
  $(document).find("#shops").addClass("active");
  $(document).find("#celebrities, #clothing, #accessories").removeClass("active");

  });

$("#celebrities").mousedown(function() {

  $(document).find(".shops, .clothing, .accessories").css("display", "none");
  $(document).find(".celebrities").css("display", "block");
  $(document).find("#shops, #clothing, #accessories").removeClass("active");
  $(document).find("#celebrities").addClass("active");

  });

$("#accessories").mousedown(function() {

  $(document).find(".shops, .clothing, .celebrities").css("display", "none");
  $(document).find(".accessories").css("display", "block");
  $(document).find("#shops, #clothing, #celebrities").removeClass("active");
  $(document).find("#accessories").addClass("active");

  });

$("#clothing").mousedown(function() {

  $(document).find(".shops, .celebrities, .accessories").css("display", "none");
  $(document).find(".clothing").css("display", "block");
  $(document).find("#shops, #accessories, #celebrities").removeClass("active");
  $(document).find("#clothing").addClass("active");

  });

// ****************************************************************************
// pop-ups
// FIXME: gawd knows what this is all tring to guard against but I'll refactor later

$('.toprightplus', '#catpagecontent').live('mouseenter', function() {
  $('.infopopupouter').hide();
  $('.infopopupouter', $(this).parent()).show();
});

$('div.plusholder', '#catpagecontent').live('mouseleave', function() {
  $('.infopopupouter', this).hide();
});

$('.TCsholder').mouseover(function() {
  $(this).find('.TCspopupback').css('display', 'block');
  $(this).find('.TCspopup').css('display', 'block');
  });

$('.TCsholder').mouseout(function() {
  $(this).find('.TCspopupback').css('display', 'none');
  $(this).find('.TCspopup').css('display', 'none');
  });

// ****************************************************************************
// home page ticker

$('#webticker').webTicker({travelocity: 0.05, direction: 1});

// ****************************************************************************
// product details images on hover
// TODO: hoverIntent me with fadein/out

$('.miniimages img').hover(function(){
  id = $(this).attr('id');
  for (var image = 1; image <= 5; image++) {
    $('#topleftmainimage_' + image).hide();
  }
  image = (id.match(/^.*_([0-9])$/))[1];
  $('#topleftmainimage_' + image).show();
}, null);

// ****************************************************************************
// roundabout gallery display (/street-style and /celebrity-style)
// -- pages the right hand thumb collection
// -- the (function() {})(); just keeps everything local
function update_thumbs() {
  var c = '.rightimageholder';           // work in the context of the rightimageholder
  var page_size = 15;                    // thumbs per page
  this.page      = 0;                     // current page (zero makes the calcs mildly easier)
  var thumbs    = $('ul li', c).size();  // number of thumbs

  if(thumbs > page_size) {
    $('.forwardarrow', c).css('visibility', 'visible');
    $('.paginationholder', c).css('visibility', 'visible');
  }

  $('.forwardarrow', c).click(function(){
    page += 1;
    var end = page * page_size;
    $('ul li', c).slice(0, end).hide();

    if ((page + 1) * page_size > thumbs) {
      $('.forwardarrow', c).css('visibility', 'hidden');
    }

    $('.backarrow', c).css('visibility', 'visible');
    return false;
  });

  $('.backarrow', c).click(function(){
    page -= 1;
    var start = (page * page_size);
    $('ul li', c).slice(start, thumbs).show();

    if (page === 0) {
      $('.backarrow', c).css('visibility', 'hidden');
    }

    $('.forwardarrow', c).css('visibility', 'visible');
    return false;
  });
}
update_thumbs();

// ****************************************************************************
// roundabout gallery display (/street-style and /celebrity-style)
//

$.address.init(function(e){
  this.autoUpdate(false);
  this.strict(false);
}).externalChange(function(){
  goto_gallery_hashtag('address');
});

// initialise the roundabout
$('ul#myRoundabout').roundabout({
  btnNext: '#nextarrowcarousel',
  btnPrev: '#prevarrowcarousel',
  easing: 'easeInOutExpo',
  minScale: 0.60,
  maxScale: 0.90,
  minOpacity: 0.10,
  clickToFocus: true
});


// change gallery title, roundabout image and related products
// NOTE: must initialise after the roundabout above, otherwise it will trigger and we don't want that ...
$('ul#myRoundabout li').bind('focus', function(e) {
  
  $('#headerline .titleinner h2').text($('.ee_title').text());

  var hashtag = $('.ee_url_title', this).text();

  if (hashtag !== window.location.hash) {
    window.location.hash = hashtag;
  }

  // TODO: put this into the a 'thumbs' object
  $('ul li', '.rightimageholder').css('border', '0').css('padding', '0.6em');
  $('ul li a[href="#' + hashtag + '"] img', '.rightimageholder').parent().parent().css('border', '0.3em solid #ed5caf').css('padding', '0.3em');

  $('#ee_related_products').load("/street-style/_related-products/" + $('.ee_entry_id', this).text(), function() {
    update_price_format();
    update_right_to_left_popup();
    $('.plusholder', '#catpagecontent').hoverIntent(cat_product_info_config);
  });
  $('#ee_related_products_celeb').load("/celebrity-styles/_related-products/" + $('.ee_entry_id', this).text(), function() { update_price_format(); update_right_to_left_popup(); });
  $('#ee_related_products_product').load("/product-gallery/_related-products/" + $('.ee_entry_id', this).text() + '/' + $('.ee_cat_id', this).text(), function() {
    console.log('ok');
    update_price_format();
    update_right_to_left_popup();
    $('.plusholder', '#catpagecontent').hoverIntent(cat_product_info_config);
  });

});

// set the correct roundabout image from the carousel
// NOTE: must bind event with .live because of new carousel entries set in the DOM after event initialisation
$('.ss_carousel').live('click', function(e) {
  window.location.hash = $(this).attr('href');
});

// go to the correct street style in the roundabout
// I could use startingChild in the options above but this way we get the focus event
// TODO: does not do anything with carousel yet ...
var goto_gallery_hashtag = function(e, hashtag) {
  var child = 1;

  if (hashtag === undefined) {
    hashtag = window.location.hash;
  }
  if (hashtag !== '') {
    child = $(hashtag).text();
  }
  
  $('ul#myRoundabout').roundabout_animateToChild(child - 1 /* offset is from 0 */, 0 /* duration */);
  
  if (e === 'load' && child === 1) {
    $('ul#myRoundabout li').eq(child - 1).trigger('focus');
  }
};
goto_gallery_hashtag('load');

// ****************************************************************************
// login/regsiter via expressionengine
//

$('#ee_login').colorbox({title: "Login via OSOYOU", width: "349px", height: "239px", href: "/signup/login/"});
$('#ee_logout').colorbox({width: "349px", height: "239px", href: "/signup/logout/"});

// Update the login status
$('#ee_login, #ee_logout').bind('cbox_closed', function(){
    $('#loginstatus').load("/site/_login-status");
});

$('#ee_forgot').live('click', function(e) {
  $('#ee_auth').load("/signup/forgot/");
});

$('#ee_register').live('click', function(e) {
  $('#ee_auth').load("/signup/register/");
});

$("#ee_register_form").live('submit', function(e) {
  /* Send the data using post and put the results in a div */
  $(this).ajaxSubmit({
    success:       function(data, status) {
      var ee_status = data.status;
      if (ee_status == 'error') {
        $('#ee_register_error').empty().html(data.content);
      }
    }
  });
  // return false to prevent normal browser submit and page navigation
  return false;
});

// ****************************************************************************
// search
// home page

var keywords_previous = '';
var timeout;
$('#keywords', $('.carouselwrap')).bind('keyup', function(e) {
  var keywords = $(this).val();
  if (keywords.length > 3 && keywords != keywords_previous) {
    keywords_previous = keywords;

    if (timeout) {
      clearTimeout(timeout);
    }

    timeout = setTimeout(function() {
      $('#suggestcontents').empty().html('<p style="padding:10px">... for the best products for you. They will be displaying shortly. Alternatively, click on the "search" button.</p>').css({'background' : 'url(/themes/osoyou/images/colorbox/loading.gif) no-repeat 180px center', 'height' : "129px"});
      $('#search').ajaxSubmit({
        url: '/dig/rest/?ee_size=small&num=5',
        success: function(data, status) {
          $('#suggestcontents').empty().html(data);
          $('#suggestcontents').css({'height' : "0"});
        }
      });
      $('#suggest,#suggestback').show();
    }, 500);
  }
});

$('#suggestclosebutton').bind('click', function(e) {
    $('#suggest,#suggestback').hide();
});

// any keywords search box
$('#keywords').bind('blur', function(e) {
  if ($(this).val() === '') {
    $(this).val($(this).attr('default'));
  }
});

$('#keywords').bind('focus', function(e) {
  if ($(this).val() == $(this).attr('default')) {
    $(this).val('');
  }
});

$('.searchbox').bind('blur', function(e) {
  if ($(this).val() === '') {
    $(this).val('Your email here.....');
  }
});

$('.searchbox').bind('focus', function(e) {
  if ($(this).val() == 'Your email here.....') {
    $(this).val('');
  }
});

// "get the look" (annoying) floater
function close_floater(){
  $('#floaterwrap').css('z-index', '-1');
  $('#floater').hide();
  $('#floaterwrap').css('z-index', '-10');
  $('.getthelooksidetab').addClass('getthelooksidetab-off').attr('src', '/themes/osoyou/images/testtab.png');
}
function open_floater(){
  $('.getthelooksidetab').removeClass('getthelooksidetab-off').attr('src', '/themes/osoyou/images/getthelook_sidetab.png');
  $('#floaterwrap').css('z-index', '10');
  $('#floater').show();
  $('#floaterwrap').css('z-index', '10');
}

$('#floatercloser').mousedown(close_floater);
if($('.getthelooksidetab').hasClass('getthelooksidetab-off')){
  $('.getthelooksidetab').toggle(open_floater, close_floater);
}else{
  $('.getthelooksidetab').toggle(close_floater, open_floater);
}

// ****************************************************************************
// search
// sort selection

$('#search_sort').live('change', function(e) {
  if($('option:selected', this).val()!='indicator'){
    var url = document.location.href;
    document.location = url.replace(/&sort=[^&]*/, '') + '&sort=' + $('option:selected', this).val();
  }
});

// ****************************************************************************
// shorten descriptions

$('.description').each(function(){
var q = this;
if ($(q).text().length > 265){
  $(q).cutString({length:265, ellipsisText:'...'});
  }
});

$('div.storedescription').each(function(){
var w = this;
if ($(w).text().length > 126){

  $(w).cutString({length:126, ellipsisText:'...'});
  }
});

// ****************************************************************************
// price - format as £657 00 or £1234
// FIXME: doesn't work for inserted DOM elements after page load (e.g. AJAX insertions)

window.update_price_format = function() {
  $('.price span').each(function(){
    // bomb out if we've already formatted this price
    if ($(this).parent().hasClass('formatted_price')) return;

    var price = '0';
    var pounds_pence = $(this).text().split('.');
    if (typeof pounds_pence[0] != 'undefined') {
      price = pounds_pence[0];
    }
    $(this).html(price);
    var pence = '00';
    if (typeof pounds_pence[1] != 'undefined') {
      // we have some pence
      pence = pounds_pence[1];
      if (pence.length == 1) {
        // make sure it's padded to 2 digits
        pence += '0';
      }
    }
    // remove spaces and check length

    if (price.split(' ').join('').length < 5) {
      // if we have less than 4 digits plus the pound sign (not including spaces), add in the pence
      price += ".<span style='font-size:0.8em'>" + pence + "</span>";
    }
    // make a note that this is a formatted price and change it
    $(this).parent().addClass('formatted_price').html(price);
  });
};
update_price_format();



var update_right_to_left_popup = function() {
    $('.number4, .number5, .number6').each(function(){
    $(this).find('img.infopopupback').css('left', '-52em');
    $(this).find('img.infopopupback').attr('src', '/themes/osoyou/images/infobox2_popup.png');
    $(this).find('.infopopup').css('left', '-49.7em');
  });
};
update_right_to_left_popup();

// ****************************************************************************
// stores - carousel stores of the week, featured products

var store_related_products_carousel = function() {
  $(".store_related_products_carousel").jCarouselLite({
    btnNext: ".next_store_related_products_carousel",
    btnPrev: ".prev_store_related_products_carousel",
    easing:  "linear",
    visible: 3,
    speed:   300,
    auto:    false
  });
  // HACK:  Height seems to be a problem in the carousel with AJAX - so force the issue here
  // FIXME: Find out why ...
  $(".store_related_products_carousel li").css({ "height": "230px" });
};
store_related_products_carousel();

$(".stores_of_the_week_carousel").jCarouselLite({
    afterEnd: function(li) {
      $('.store_related_products_carousel').load("/stores/_related-products/" + $('span:first', li).text(), function() {
        update_price_format();
        store_related_products_carousel();
      });
    },
    btnNext: ".next",
    btnPrev: ".prev",
    easing: "linear",
    visible: 1,
    speed: 400,
    btnGo:
  [".imageSliderExt .1", ".imageSliderExt .2",
  ".imageSliderExt .3", ".imageSliderExt .4",
  ".imageSliderExt .5", ".imageSliderExt .6",
  ".imageSliderExt .7", ".imageSliderExt .8",
  ".imageSliderExt .9", ".imageSliderExt .10",
".imageSliderExt .11", ".imageSliderExt .12"]
});
// go to the first item, so tha t
$(".stores_of_the_week_carousel").trigger("go", 0);

// ****************************************************************************
// stores - related products info popup - AJAX

$(".toprightplus", '#shopspagecontent').live('mouseenter', function(e){
  $('#store_related_products_popup').data('inplus', true);
  var me = $(this);
  setTimeout(function(){
    if ($('#store_related_products_popup').data('inplus')) {
      var x = me.positionAncestor('.bottomleftcarousel').left;
      var y = me.positionAncestor('.bottomleftcarousel').top;

      // alert($(this).siblings('span:first').text());
      $('#store_related_products_popup').load("/stores/_info-popup/" + me.siblings('span:first').text(), function() {
        $('#store_related_products_popup').css({ 'position': 'absolute', 'left': x+'px' , 'top': y+'px'});
        $('#store_related_products_popup .infopopupouter').show();
      });    
    }
  }, 200);
});

$(".toprightplus", '#shopspagecontent').live('mouseleave', function(e){
  $('#store_related_products_popup').data('inplus', false);
  store_popup_hide();
});

$("#store_related_products_popup", '#shopspagecontent').bind('mouseenter', function(e){
  $('#store_related_products_popup').data('inpopup', true);
});

$("#store_related_products_popup", '#shopspagecontent').bind('mouseleave', function(e){
  $('#store_related_products_popup').data('inpopup', false);
  store_popup_hide();
});

var store_popup_hide = function() {
  setTimeout(function(){
    if (! $('#store_related_products_popup').data('inplus') && ! $('#store_related_products_popup').data('inpopup')) {
      $('#store_related_products_popup .infopopupouter').hide();
    }
  }, 200);
};

// ****************************************************************************
// search - products info popup - AJAX


$('.productbox > div > img', '#searchpagecontent').hoverIntent(product_info_config);
$('.productbox > div > a', '#searchpagecontent').hoverIntent(product_info_config);

// manage the state of the mouse (so we can let the main hover know above)
$('.product_large_popup .infopopupouter').live('mouseenter', function() {
  $.data(this, 'hover', true);
});

$('.product_large_popup .infopopupouter').live('mouseleave', function() {
  $.data(this, 'hover', false);
  $(this).hide();
});


// ****************************************************************************
// category - products info popup - AJAX

var cat_product_info_config = {
   sensitivity:   2,   // number = sensitivity threshold (must be 1 or higher)
   interval:    100,   // number = milliseconds for onMouseOver polling interval
   timeout:     500,   // number = milliseconds delay before onMouseOut
   out:         function(e) {
     // don't hide the popup if the mouse pointer within
     if (! $('.infopopupouter', $(this)).data('hover')) {
       $('.infopopupouter', $(this)).hide();
     }
   },
   over:        function(e) {
     var container = $('div[name="infopopup"]', $(this));
     if (container.text() === "") {
       var id = container.attr('id').split('_');
       var entry_id = id[1];
       $('.infopopupouter').hide();
       $('div[name="infopopup"]', $(this)).load("/stores/_info-popup/" + entry_id, function() {
         update_price_format();
         update_right_to_left_popup();
         $('.infopopupouter', $(this)).show();
       });
     }
   }
};

$('.plusholder', '#catpagecontent').hoverIntent(cat_product_info_config);

// manage the state of the mouse (so we can let the main hover know above)
$('.plusholder .infopopupouter', '#catpagecontent').live('mouseenter', function() {
  $.data(this, 'hover', true);
});

$('.plusholder .infopopupouter', '#catpagecontent').live('mouseleave', function() {
  $.data(this, 'hover', false);
  $(this).hide();
});

// ****************************************************************************
// reviews - products/stores

$(".reviewheading a:first", '#reviews').bind('click', function(e){
  $("#reviews_form", '#reviews').toggle(200);
  return false;
});

$('h6 a[href="#review_form"]', '#catpagecontent').bind('click', function(e){
  $("#reviews_form", '#reviews').show();
});

// ****************************************************************************
// reviews - review form

$('#reviews_form form').bind('submit', function(e){

  var id = $('.review_entries', '#reviews').attr('id').split('_');
  var entry_id = id[2];
  $(this).ajaxSubmit({
    success: function(data){
      $('.review_entries', '#reviews').load("/review/_review_entries/" + entry_id, function(data) {
        $("#reviews_form input[name='review_sentiment']", '#reviews').val('');
        $("#reviews_form textarea[name='review']", '#reviews').val('');
        $("#reviews_form", '#reviews').hide();

        $.get('/review/_count/' + entry_id + '/' + 'review', function(data){
          var plural = '';
          if (data > 1) plural = 's';
          $("h6 span a", $(".productdetailstext")).text(data + ' Review' + plural);
          $("h6 span", $(".productdetailstext")).show();
        });
      });
    }
  });
  return false;
});


// ****************************************************************************
// reviews - likes

$(".likes").live('click', function(e){

  var review_href = $('a.shopstyle', this).attr('href');
  var name = $('div.like_form_container', $(this).parent()).attr('name').split('_');
  var entry_id = name[2];
  var return_template = 'review/_count/' + entry_id + '/' + 'like';
  $('div.like_form_container', $(this).parent()).load("/review/_like/", {'entry_id': entry_id, 'review_href': review_href, 'return_template': return_template, 'rating': 5, 'collection': 'like'}, function(data) {
    $('.like_love_form', this).ajaxSubmit({
      success: function(data){
        // only select the first direct span child
        var likes = $('p[name="likes_' + entry_id + '"]');
        var plural = '';
        if (data > 1) plural = 's';
        $('> span:first-child', likes).text(data + ' Like' + plural);
        $('> span:nth-child(2)', likes).show();
      }
    });

  });
  return false;
});

// ****************************************************************************
// reviews - loves

$(".loves a").live('click', function(e){
  var container = $(this).parent().parent();
  var review_href = $(this).attr('href');
  var name = $('div.love_form_container', container).attr('id').split('_');
  var entry_id = name[2];
  var return_template = 'review/_count/' + entry_id + '/' + 'love';
  $('div.love_form_container', container).load("/review/_like/", {'entry_id': entry_id, 'review_href': review_href, 'return_template': return_template, 'rating': 5, 'collection': 'love'}, function(data) {
    $('.like_love_form', this).ajaxSubmit({
      success: function(data) {
        if ($('div.love_form_container', container).hasClass('love_update')) {
          var featured = $('.featuredproductholder');
          $('h3', featured).text(data);
          if (data >= 10) {
            var left = '0.6em';
            if ($('h3', featured).hasClass('topheart')) {
              left = '0.9em';
            }
            $('h3', featured).css({'left': left});
          }
          // the first image is the featured product badge (on its own), so turn it off
          $('> img', featured).hide();
          $('.love_badge', featured).show();
        }
      }
    });

  });
  return false;
});

// ****************************************************************************
// contact form

$("#from").bind('blur', function(e){
  var to = $(this).val();
  
  $('#contactemailto').val(to);
  $('#contactemail').val(to);
});

/**
 * Get the current coordinates of the first element in the set of matched
 * elements, relative to the closest positioned ancestor element that
 * matches the selector.
 * @param {Object} selector
 */
jQuery.fn.positionAncestor = function(selector) {
  var left = 0;
  var top = 0;
  this.each(function(index, element) {
    // check if current element has an ancestor matching a selector
    // and that ancestor is positioned
    var $ancestor = $(this).closest(selector);
    if ($ancestor.length && $ancestor.css("position") !== "static") {
      var $child = $(this);
      var childMarginEdgeLeft = $child.offset().left - parseInt($child.css("marginLeft"), 10);
      var childMarginEdgeTop = $child.offset().top - parseInt($child.css("marginTop"), 10);
      var ancestorPaddingEdgeLeft = $ancestor.offset().left + parseInt($ancestor.css("borderLeftWidth"), 10);
      var ancestorPaddingEdgeTop = $ancestor.offset().top + parseInt($ancestor.css("borderTopWidth"), 10);
      left = childMarginEdgeLeft - ancestorPaddingEdgeLeft;
      top = childMarginEdgeTop - ancestorPaddingEdgeTop;
      // we have found the ancestor and computed the position
      // stop iterating
      return false;
    }
  });
  return {
    left: left,
    top:  top
  };
};
$('ul#myRoundabout li').eq(0).focus();
// ****************************************************************************
// search
// refine selection and fire off a GET request

$('.filter_toggle span').click(function(){
  if($(this).parent().next().is(':visible')){
    $(this).parent().removeClass('open').addClass('closed');
    $(this).parent().next().hide();
  }else{
    $(this).parent().removeClass('closed').addClass('open');
    $(this).parent().next().show();
  } 
});
var filters = ['store', 'brand', 'colour', 'price_GBP', 'ESP_CategoryTitles'];

for(i=0;i<filters.length;i++){
  if(document.location.href.indexOf(filters[i])>=0){
    $('.'+filters[i]).show();
  }
}

$('.clear_filters').click(function(e) {
  change_secondary_categories = true;
  $('.row input[type=checkbox]:checked, .row input[type=radio]').removeAttr('checked');
  clear_price_range();
  clear_categories();
  search(e);
});

function load_brands(brands){
  for(brand in brands){
    count = brands[brand];
    $('#brands').append('<div class="row"><input type="checkbox" value="'+brand+'" name="filter_brand" class="filter styled" id="filter_brand_' + brand + '" /><label for="filter_brand_'+brand+'">'+brand.slice(0,1).toUpperCase()+brand.slice(1)+' <span class="count" style="font-size:0.8em">(' + count + ')</span></label></div>');
  }
  $('#brands').append('<div class="float:none;clear:both"></div>');
}

function load_stores(stores){
  for(store in stores){
    count = stores[store];
    $('#stores').append('<div class="row"><input type="checkbox" value="'+store+'" name="filter_store" class="filter styled" id="filter_store_' + store + '" /><label for="filter_store_'+store+'">'+store.slice(0,1).toUpperCase()+store.slice(1)+' <span class="count" style="font-size:0.8em">(' + count + ')</span></label></div>');
  }
  $('#stores').append('<div class="float:none;clear:both"></div>');
}

function load_price(price){
}

function load_types(types){
  for(type in types){
    $('#types').append('<div class="row"><input type="checkbox" value="'+type+'" name="filter_type" class="filter styled" id="filter_type_' + type + '" /><label for="filter_type_'+type+'">'+type.slice(0,1).toUpperCase()+type.slice(1)+'</label></div>');
  }
  $('#types').append('<div class="float:none;clear:both"></div>');
}

function load_price(price){
                     $( "#price_slider" ).slider({
                       range: true,
                       min: price.min,
                       max: price.max,
                       step: 10,
                       values: [ price.min, price.max],
                       slide: function( e , ui ) {
                          $("#amount" ).html( "&pound; " + ui.values[ 0 ] + " - &pound; " + ui.values[ 1 ] );
                          $("[name=price_from]").val(ui.values[0]);
                          $("[name=price_to]").val(ui.values[1]);
                       },
                       stop: function(e, ui){
                         search(e);
                       }

                     });
}

function load_colours(colours){
  var count = null;
  for(colour in colours){
    count = colours[colour];
    $('#colours').append('<div class="row"><input type="checkbox" value="'+colour+'" name="filter_colours" class="filter styled" id="filter_colour_' + colour + '" /><label for="filter_colour_'+colour+'">'+colour.slice(0,1).toUpperCase()+colour.slice(1)+' <span class="count" style="font-size:0.8em">(' + count + ')</span></label></div>');
  }
  $('#colours').append('<div class="float:none;clear:both"></div>');
}

function clear_price_range(){
  $( "#price_slider" ).slider('values', 0, price.min);
  $( "#price_slider" ).slider('values', 1, price.max);
  $("#amount" ).html( "&pound; " + price.min  + " - &pound; " + price.max );
  $("[name=price_from]").val(price.min);
  $("[name=price_to]").val(price.max);
}

function clear_categories(){
  $('input[type=radio]').parents('.row').css('color', 'black');
}

if($('#search_refine').size()>0){
  $('.clear').click(function(){
    if(!$(this).hasClass('price_range')){
      $(this).parent().next().find('input[type=checkbox], input[type=radio]').removeAttr('checked');
    }else{
      clear_price_range();
    }
    search();
  });
  //load_colours(colours);
  //load_stores(stores);
  //load_brands(brands);
  load_price(price);
  //$('#colours').jScrollPane();
  $('#stores').jScrollPane();
  $('#brands').jScrollPane();
  $('#brands').hide();
  $('input[type=checkbox]').change(search);
  $('input[type=radio]').change(function(e){
    change_secondary_categories=true;
    $(this).parents('.row').css('color', 'black').siblings().css('color', '#ccc');
    search(e);
  });
  register_pagination();
}

function register_pagination(){
  $('.paginationbutton').click(function(e){
    var page = $(this).text();
    $('[name=pg]').val(page);
    search(e);
    $('[name=pg]').val(1);
    return false;
  });
}

function search(e){
  if(change_secondary_categories && !$("input[name='filter_primary_category_id']").size()==1){
    $('#secondary_categories_container').hide();
    $('#secondary_categories').empty();
  }
  $('#loading_holder').html("<img src='/themes/osoyou/images/colorbox/loading.gif' />");
  var url = document.location.search;
  if(!url){
    url = '?';
  }
  url += '&filter_price_GBP=' + $('[name=price_from]').val() + ':' + $('[name=price_to]').val();
  $("input:checked").each(function(){
    url += '&' + $(this).attr('name') + '=' + encodeURIComponent($(this).val());
  });
  url += '&pg=' + $('[name=pg]').val();
  //CATEGORY pages
  if($('#category_filter').size()>0){
    url += '&' + $('#category_filter').attr('name')+'='+$('#category_filter').val();
  }
  if($('#store_filter').size()>0){
    url += '&' + $('#store_filter').attr('name')+'='+$('#store_filter').val();
  }

  url = '/dig/api' + url;
  $('.products').fadeTo(500,0.2);
        $.ajax({
                url: url,
                dataType: 'html',
                type:'GET',
                success : function(data, textStatus, jqXHR){
                        $('.products').html(data);
                        var pagination = $("#new_pagination").html();
                        $('.pagination').replaceWith(pagination);
                        register_pagination();
                        var meta = $('#meta');
                        meta = $.parseJSON(meta.text());
                        var pages = Math.ceil(meta.hits / hits_per_page);
                        if(meta.hits<4){
                          $('.pagination').eq(2).hide();
                        }else{
                          $('.pagination').eq(2).show();
                        }
                        console.log($("input[name='filter_primary_category_id']").size()!=1);
                        console.log(change_secondary_categories);
                        if(change_secondary_categories && $("input[name='filter_primary_category_id']").size()!=1){
                          if($('.row input[type=radio]:checked').size()>0){
                            $('#secondary_categories').empty();
                            change_secondary_categories = false;
                            //then we show secondary filters
                            for(category in meta.categories['secondary']){
                              name = category;
                              category = meta.categories['secondary'][category];
                              count = category.count;
                              id = category.id;
                              $('#secondary_categories').append('<div class="row"><input type="checkbox" value="'+id+'" name="filter_secondary_category_id" class="filter styled" id="filter_category_' + id+ '" /><label for="filter_category_'+id+'">'+name+' <span class="count" style="font-size:0.8em">(' + count + ')</span></label></div>');
                            }
                            $('#secondary_categories').append('<div class="float:none;clear:both"></div>');
                            $('#secondary_categories_container').show();
                            $('#secondary_categories input[type=checkbox]').change(search);
                          }else{
                            $('#secondary_categories_container').hide();
                            $('#secondary_categories').empty();
                          }
                        }
                        $('#hits').text(meta.hits_format);
                        $('#loading_holder').html('');
                        $('.products').fadeTo(500,1);
                        $('.productbox > div > img', '#searchpagecontent').hoverIntent(product_info_config);
                        $('.productbox > div > a', '#searchpagecontent').hoverIntent(product_info_config);
                        update_price_format();
                }
        });

  return false;
}

$("#topnav a[href='']").click(function(){
  return false;
}).css('cursor', 'default');

$('.expander_200').expander({
  slicePoint: 200
});
$('.expander_300').expander({
  slicePoint: 300
});
$('.expander_500').expander({
  slicePoint: 500
});

$('#tab_google_plus img').qtip({
  content:{
    text:"<em>Login to OSOYOU with your Google+ and share your favourite finds</em>"
  },
  position:{
    my: 'right center',
    at: 'left center'
  },
  show:{
    solo:true
  },
  style: {
    classes: 'ui-tooltip-light ui-tooltip-rounded ui-tooltip-shadow',
    width: '150'
  }
});

$('#tab_twitter img').qtip({
  content:{
    text:"<em>Login to OSOYOU with your Twitter account and tweet the items you love</em>"
  },
  position:{
    my: 'right center',
    at: 'left center'
  },
  show:{
    solo:true
  },
  style: {
    classes: 'ui-tooltip-light ui-tooltip-rounded ui-tooltip-shadow',
    width: '150'
  }
});

$('#tab_fashioncard').qtip({
  content:{
    text:"<em>Download your free OSOYOU fashion card and receive exclusive offers and promotions</em>"
  },
  position:{
    my: 'right center',
    at: 'left center'
  },
  show:{
    solo:true
  },
  style: {
    width: '150',
    classes: 'ui-tooltip-light ui-tooltip-rounded ui-tooltip-shadow'
  }
});

$('#tab_facebook img').qtip({
  content:{
    text:"<em>Login to OSOYOU with your FB account and share your favourite finds</em>"
  },
  position:{
    my: 'right center',
    at: 'left center'
  },
  show:{
    solo:true
  },
  style: {
    classes: 'ui-tooltip-light ui-tooltip-rounded ui-tooltip-shadow',
    width: '150'
  }
});
});

