$(document).ready(function() {
  $("ul#nav ul").show();

  $('ul#nav > li').each(function() {
    $(this).find('a:first').next().wrapAll(
      $('<div/>', {
        'class': 'sub'
      })
    );
  });

  $('ul#nav .sub').each(function() {
    $(this).find('> ul > li').unwrap();
    // Wrap any links that have sublinks in groups of 2.
    if($(this).find('ul').length) {
      $(this).find('> li:has(ul)').wrapInChunks('<ul class="column"/>', 2).appendTo($(this));
    }
    // Wrap stand-alone links in a single column.
    $(this).find('> li').wrapAll('<ul class="column"/>');

    $(this).find('.column:last').css({
     'border-right': 0,
     'margin-right': 0,
     'padding-right': 0
    });

    var width = 0;
    var innerWidth = 0;
    var outerWidth = 0;
    var additional = 20;
    var height = 0;

    $(this).find('.column').each(function() {
      height = $(this).height() > height ? $(this).height() : height;

      innerWidth = $(this).innerWidth();
      outerWidth = $(this).outerWidth(true);

      if(innerWidth > 1000 || outerWidth > 1000) {
        height = height + 60;
        innerWidth = innerWidth / 10;
        outerWidth = outerWidth / 10;
      }

      width = innerWidth + additional > width ? innerWidth + additional : width;
      outerWidth = outerWidth > width ? outerWidth : width;
    }).width(width).height(height);
    
    $(this).width(outerWidth * $(this).find('.column').length);
  });

  $("ul#nav .sub h2").each(function() {
    if($(this).children().length > 0) {
      $(this).children().css('display', 'block');
      $(this).css('border-bottom', 0);
    }
  });

  $('ul#nav .sub').hide();

  // Hide all select boxes (if there are any) before showing nav, IE6 revokes hover state on hides so wait for callback.
  if ($.browser.msie && $.browser.version.substr(0,1) < 7 && $("select").length) {
    $("ul#nav > li").hover(function() {
      var li = this;
      $("select").hide(0, function() {
        $(li).find(".sub").show().siblings("a:first").addClass('active')
      })
    }, function() {
      var li = this;
      $("select").show(0, function() {
        $(li).find(".sub").hide().siblings("a:first").removeClass('active')
      })
    })
  } else {
    // Saves a bit of processing for good browsers.
    $("ul#nav > li").hover(function() {
      $(this).find(".sub").show().siblings("a:first").addClass('active')
    }, function() {
      $(this).find(".sub").hide().siblings("a:first").removeClass('active')
    })
  }
  
  // For keyboard navigation.
  $("ul#nav > li > a").focus(function() {
    $("ul#nav").each(function() {
      $(this).find(".sub:visible").hide().siblings("a:first").removeClass('active');
    })

    $(this).addClass('active').parent().find(".sub").stop().fadeTo('fast', 100, function() {
      $(this).show();
    })
  })
  
  $('.search_delete a').click(function(event) {
    event.preventDefault();
    $('input.query').val("");
  });

  // Google Search Field Swap
  $("#home_search").each(function() {
    var search = this;
    $(this).find(".search_toggle .google").click(function() {
      $(this).parent().siblings().find("a").css('background-position', '0 0');
      $(this).css('background-position', '0 16px');
      $(search).find("form:not(.google_search)").hide();
      $(search).find(".google_search").show().find(".query").val($(".sconty_search .query").val()).focus();
      return false;
    })
    $(this).find(".search_toggle .sconty").click(function() {
      $(this).parent().siblings().find("a").css('background-position', '0 0');
      $(this).css('background-position', '0 16px');
      $(search).find("form:not(.sconty_search)").hide();
      $(search).find(".sconty_search").show().find(".query").val($(".google_search .query").val()).focus();
      return false;
    })
    $(search).find(".query:hidden").val($(".query:visible").val());
  })

  // Default Search
  var search_placeholder = 'Search for a product, store or brand'
  
  if($('input#filter_query').val() == search_placeholder) {
    $('input#filter_query').addClass("greydefaulttext");
  }

  $("#filter_main_products").click(function() {
    $('input#filter_query').attr('title', 'Enter product eg Armani Jumper').removeClass("greydefaulttext");
    
    if($('input#filter_query').val() == search_placeholder) {
      $('input#filter_query').val('Enter product eg Armani Jumper');
    }
  })
  
  $('form#sconty_search input.query').click(function() {
    $(this).removeClass('greydefaulttext');
  })

  $("#filter_main_websites").click(function() {
    $('input#filter_query').attr('title', search_placeholder);
    
    if($('input#filter_query').val() == "Enter product eg Armani Jumper") {
      $('input#filter_query').val(search_placeholder);
    }
  })
  
  // Only show the first row of search filters, with an expand link.
  /*$('.filters').each(function() {
    $(this).find('.dropdowns').after($('<a/>', {'href': '#', 'class': 'filterToggle'}).text('+ filters'))

    $(this).find('.filter').unwrap()
    
    $(this).find('> .filter:last').wrap($('<ul/>', {'class': 'more'})).parent().hide()
    $(this).find('> .filter').wrap($('<ul/>'))

    $(this).find('.filterToggle').toggle(function() {
      $(this).siblings('.more').slideDown()
      $(this).text('- filters')
    }, function() {
      $(this).siblings('.more').slideUp()
      $(this).text('+ filters')
    })
  })*/

  $(window).load(function() {
    resize()
  });
  
  function applyFancybox() {
    $("a[rel=fancybox]").fancybox({
      'zoomOpacity'			: true,
      'overlayShow'			: true,
      'zoomSpeedIn'			: 500,
      'zoomSpeedOut'		: 500,
      'easingIn'				: 'easeOutBack',
      'easingOut'				: 'easeInBack',
      'transitionIn'    : 'elastic',
      'transitionOut'   : 'elastic',
      'centerOnScroll'  : 'true',
      'scrolling'       : 'yes'
    })
  }
  
  var ajaxifyFancyBoxForm = function() {
    $('.report-form form').ajaxForm({
      target: '#fancybox-content',
      success: function(responseText, statusText, xhr, $form) {
        ajaxifyFancyBoxForm(this);
        $.fancybox.resize();
      }
    });
  }
  
  $("a.reportfancybox").each(function() {
    $(this).fancybox({
      'zoomOpacity'			: true,
      'overlayShow'			: true,
      'zoomSpeedIn'			: 500,
      'zoomSpeedOut'		: 500,
      'easingIn'				: 'easeOutBack',
      'easingOut'				: 'easeInBack',
      'transitionIn'    : 'elastic',
      'transitionOut'   : 'elastic',
      'centerOnScroll'  : 'true',
      'scrolling'       : 'no',
      'onComplete'      : ajaxifyFancyBoxForm,
      'orig'            : $(this).is(':visible') ? this : $(this).parents(':visible')
    });
  });
  
  $("a.fancyajax").fancybox({
    'zoomOpacity'			: true,
    'overlayShow'			: true,
    'zoomSpeedIn'			: 500,
    'zoomSpeedOut'		: 500,
    'easingIn'				: 'easeOutBack',
    'easingOut'				: 'easeInBack',
    'transitionIn'    : 'elastic',
    'transitionOut'   : 'elastic',
    'centerOnScroll'  : 'true',
    'ajax'            : {}
  })

  applyFancybox()

  //for expanding/narrowing sub cat menu results
  if ($('div#side_nav ul li ul li').hasClass('submargin') || $('div#side_nav ul li ul li').hasClass('cat_selected')) {
    $('div#side_nav ul li ul li').each(function () {
      if (!$(this).next().hasClass("submargin") && !$(this).hasClass("submargin") && !$(this).next().hasClass("submarginsubmargin") && !$(this).hasClass("submarginsubmargin") && !$(this).next().hasClass("submarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmargin") && !$(this).next().hasClass("submarginsubmarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmarginsubmargin") && !$(this).next().hasClass("submarginsubmarginsubmarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmarginsubmarginsubmargin") && !$(this).hasClass("cat_selected")) {
        $(this).slideUp();
      } else if (!$(this).hasClass("submargin") && !$(this).hasClass("submarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmarginsubmarginsubmargin")) {
        if ($(this).hasClass('top')) {
          $(this).removeClass('top');
        }
        $('div#side_nav ul li ul').prepend('<li class="narrowresults">Narrow Results</li>');
        $('div#side_nav ul li ul li.narrowresults').hide();
        $('div#side_nav ul li ul').prepend('<li class="expandresults">Expand Results</li>');
      }
    });
  }

  $('div#side_nav ul li ul li.expandresults').click(function () {
      $(this).hide();
      $('div#side_nav ul li ul li.narrowresults').show();
      $('div#side_nav ul li ul li').each(function () {
    if ($(this).hasClass('top')) {
              $(this).removeClass('top');
          }
          if(!$(this).hasClass('expandresults')) {
              $(this).slideDown();
          }
      });
  });

  $('div#side_nav ul li ul li.narrowresults').click(function () {
      $(this).hide();
      $('div#side_nav ul li ul li.expandresults').show();
      $('div#side_nav ul li ul li').each(function () {
          if (!$(this).next().hasClass("submargin") && !$(this).hasClass("submargin") && !$(this).next().hasClass("submarginsubmargin") && !$(this).hasClass("submarginsubmargin") && !$(this).next().hasClass("submarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmargin") && !$(this).next().hasClass("submarginsubmarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmarginsubmargin") && !$(this).next().hasClass("submarginsubmarginsubmarginsubmarginsubmargin") && !$(this).hasClass("submarginsubmarginsubmarginsubmarginsubmargin") && !$(this).hasClass("expandresults") && !$(this).hasClass("cat_selected")) {
            $(this).slideUp();
          }
      });
  });

  //Toggle full description for offers
 $('.offer_desc_short a').each(function() {
    $(this).click(function(event) {
      event.preventDefault();
      $(this).parent().hide();
      $(this).parent().next().fadeIn(500);
    })
  })

  $('.offer_desc_full a').each(function() {
    $(this).click(function(event) {
      event.preventDefault();
      $(this).parent().hide();
      $(this).parent().prev().fadeIn(500);
    })
  })
  
  $('.offers_box .singleoffer').each(function() {
    $(this).hover(function() {
      $(this).find('.offer-social-icons').slideDown(150);
      var init = $(this).find('.fb-tw-like');
      var link = $(this).find('.offer-social-icons').attr('id');
      $.get(
        link,
        function(data) {
          init.hide().html(data).delay(500).slideDown(150);
        }
      );
    }, function() {
      $(this).find('.fb-tw-like').hide();
      $(this).find('.offer-social-icons').slideUp(150);
      $(this).find('.fbook-comments-popout').slideUp(150);
      $(this).find('.fbook-comments-close').hide();
      $(this).find('.fbook-comments-init').show();
    })
  })
  
  $('.offers_box .singleoffer .fbook-comments-init').each(function() {
    $(this).click(function() {
      var init = $(this);
      init.hide();
      init.parent().find('.fbook-comments-close').show();
      init.parent().find('.fbook-comments-close').attr('style', 'display: inline');
      var link = $(this).find('a').attr('href');
      $.get(
        link,
        function(data) {
          init.parent().parent().parent().find('.fbook-comments-popout').hide().html(data).slideDown(150);
        }
      );
      return false;
      //$(this).parent().parent().parent().find('.fbook-comments-popout').slideDown(150);
    })
  })
  
  $('.offers_box .singleoffer .fbook-comments-close').each(function() {
    $(this).click(function() {
      $(this).parent().parent().parent().find('.fbook-comments-popout').slideUp(150);
      $(this).hide();
      $(this).parent().find('.fbook-comments-init').show();
    })
  })
  
  //Toggle view/hide editing offers
  $('.edit-ind-offer').hide();
  $('.edit-offer-close').hide();
  
  $('.edit-offer-open').click(function() {
    $(this).hide();
    $(this).parent().find('.edit-offer-close').show();
    $(this).parent().next().slideDown(150);
  })
  
  $('.edit-offer-close').click(function() {
    $(this).hide();
    $(this).parent().find('.edit-offer-open').show();
    $(this).parent().next().slideUp(150);
  })
})


$(window).resize(function() {resize()});

function resize() {
  var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();

  if (jQuery.browser.msie) {
    if(parseInt(jQuery.browser.version) == 7) {
      viewportWidth -= 3;
    }
  }

  $('ul#nav .sub').each(function() {
    $(this).css({
      'display': 'block',
      'left': ''
    })
    var offset = $(this).offset().left + $(this).outerWidth(true) + 10;

    if(offset > viewportWidth) {
      if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        ie6offset = 30;
      } else {
        ie6offset = 0
      }
      $(this).css({
        'left': -(offset + 10 - viewportWidth) - ie6offset
      });
    }

    $(this).css({
      'display': 'none'
    })
  })
}

$.fn.wrapInChunks = function(html, chunkSize) {
  chunkSize = chunkSize || 1;
  var items = this.get(),
    rows = [],
    cur = rows[0] = $(html);
  while (items[0]) {
    if (rows[rows.length - 1].children().length === chunkSize) {
        cur = rows[rows.length] = $(html);
    }
    cur.append( items.shift() );
  }
  return this.pushStack(rows);
};
