/**
This is a place where we can put javascript that doesn't need to be at the top of the page.
**/

/**
This is a place where we can put javascript that doesn't need to be at the top of the page.
You can safely assume jquery is loaded here.
**/

//Limit.js - http://www.unwrongest.com/projects/limit/
(function ($) { $.fn.extend({ limit: function (limit, element) { var interval, f; var self = $(this); $(this).focus(function () { interval = window.setInterval(substring, 100) }); $(this).blur(function () { clearInterval(interval); substring() }); substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}"; if (typeof element != 'undefined') substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"; substringFunction += "}"; eval(substringFunction); substring() } }) })(jQuery);

// Carousel

function initCarousel() {
  var rotatorStartIndex = parseFloat($('#rotatorstartindex').val()) || 0;
  $("div.tabs").tabs(".rotator > div", {
    // effect: 'horizontal',
    effect: 'fade',
    fadeOutSpeed: "slow",
    rotate: true,
    initialIndex: rotatorStartIndex
  }).slideshow({
    autoplay: true,
    interval: 3750
  });
}

// -----------------------------------------------------------------------------
// Item & List Functions
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// Fluid Lists & Image Scaling
// -----------------------------------------------------------------------------

function initFluidLists(listSelector) {
  var listSelector = listSelector ? listSelector : 'ol.fluid:visible';
  $(listSelector).each(function () {
    var mainImageArray = $(this).find('div.top a.image img');
    var ownerImagegArray = $(this).find('div.owner a.image img');
    // Set container height
    var listHeightMultiple = $(this).attr('data-height-multiple') || 1;
    $(mainImageArray).each(function () {
      var objRoot = $(this).closest('li');
      var objParent = $(this).parent();
      var objParentOriginalWidth = objParent.width();
      var objWidthMultiple = objRoot.attr('data-width-multiple') || 1;
      if (objWidthMultiple != 1) {
        objRoot.css('width', (objRoot.width() * objWidthMultiple) + 'px');
      }
      var objHeightMultiple = objRoot.attr('data-height-multiple') || listHeightMultiple;
      objParent.css('height', Math.round(objParentOriginalWidth * objHeightMultiple) + 'px');
    });
    $(ownerImagegArray).each(function () {
      $(this).parent().css('height', Math.round($(this).parent().width()) + 'px');
    });
    // Resize images
    var imageArray = mainImageArray.add(ownerImagegArray);
    if ($(this).hasClass('scaletofit')) {
      scaleToFit($(imageArray));
    }
    else {
      scaleToFill($(imageArray));
    }
    // Attach Events: Slider
    if ($(this).hasClass('slideinfo')) {
      $('li', this).bind('mouseenter.slider', function () {
        $('div.bottom', this).stop().css('bottom', '-100px').animate({ 'bottom': '0' }, { queue: false, duration: 200 });
      }).bind('mouseleave.slider', function () {
        $('div.bottom', this).stop().animate({ 'bottom': '-100px' }, { queue: false, duration: 200 });
      });
    }
  });
}

function scaleToFill(imgSelector, fallbackScaleToFit) {
  $(imgSelector).not('img.noimage').each(function () {
    $(this).parent().css({
      'position': 'relative',
      'overflow': 'hidden'
    });
    $(this).css({
      'position': 'absolute',
      'height': 'auto',
      'width': 'auto'
    });
    var objHeight = $(this).height();
    var objWidth = $(this).width();

    //this can happen when an image hasn't downloaded yet.  If so, go back and scale it when it's ready
    if (imageIsNotLoaded(this)) {
      WPJS.Debug("Image hadn't loaded when we tried to scale it: " + $(this).attr("src"));
      $(this).load(function () { scaleToFill(this, fallbackScaleToFit); });
      return true;
    }
    //WPJS.Debug("Scaling to fill: " + $(this).attr("src"));

    var parentHeight = $(this).parent().height();
    var parentWidth = $(this).parent().width();

    if (fallbackScaleToFit && (objHeight * 2 < parentHeight && objWidth * 2 < parentWidth) || objHeight / objWidth > 2 || objWidth / objHeight > 2) {
      WPJS.Debug("Doing a scaletofit because image was too small or oddly-shaped (" + objHeight + "x" + objWidth + "): " + this + " " + $(this).attr("src"));
      return scaleToFit(this);
    }

    var heightDiff = parentHeight - objHeight;
    var widthDiff = parentWidth - objWidth;
    if (heightDiff >= widthDiff) {
      $(this).css('height', parentHeight + 'px');
    }
    else if (widthDiff > heightDiff) {
      $(this).css('width', parentWidth + 'px');
    }
    $(this).css({
      'top': Math.round((parentHeight - $(this).height()) / 2) + 'px',
      'left': Math.round((parentWidth - $(this).width()) / 2) + 'px',
      'visibility': 'visible'
    });
  });
}

function scaleToFit(imgSelector) {
  $(imgSelector).not('img.noimage').each(function () {
    $(this).parent().css({
      'position': 'relative',
      'overflow': 'hidden'
    });
    $(this).css({
      'position': 'absolute',
      'height': 'auto',
      'width': 'auto'
    });
    var objHeight = $(this).height();
    var objWidth = $(this).width();

    //this can happen when an image hasn't downloaded yet.  If so, go back and scale it when it's ready
    if (imageIsNotLoaded(this)) {
      WPJS.Debug("Image hadn't loaded when we tried to scale it: " + $(this).attr("src"));
      $(this).load(function () { scaleToFit(this); });
      return true;
    }
    
    var parentHeight = $(this).parent().height();
    var parentWidth = $(this).parent().width();
    var heightDiff = parentHeight - objHeight;
    var widthDiff = parentWidth - objWidth;
    
    if (heightDiff >= widthDiff) {
      $(this).css('width', parentWidth + 'px');
    }
    else if (widthDiff > heightDiff) {
      $(this).css('height', parentHeight + 'px');
    }
    $(this).css({
      'top': Math.round((parentHeight - $(this).height()) / 2) + 'px',
      'left': Math.round((parentWidth - $(this).width()) / 2) + 'px',
      'visibility': 'visible'
    })
  });
}

//Runs through images with the specific class and swaps them if they aren't loaded
function correctErroredImages() {
  $('.handleError > img').each(function () {
    if (imageIsNotLoaded(this)) swapImageForError(this);
  });
}

function swapImageForError(imageSelector) {
  WPJS.Debug("Error handler called for: " + $(imageSelector).attr("src"));
  if ($(imageSelector).hasClass('wishPic') || $(imageSelector).hasClass('listPic'))
    $(imageSelector).attr('src', '/img/item_100.gif');
  else if ($(imageSelector).hasClass('userPic'))
    $(imageSelector).attr('src', '/img/nopicusr.gif');
  else if ($(imageSelector).hasClass('prodPic'))
    $(imageSelector).attr('src', '/img/item_150.gif');
  else
    $(imageSelector).attr('src', '/img/nophoto160x160.gif');

  //if the parent has height, fill it (some parents have a tiny bit of height 'cause of some text)
  if ($(imageSelector).parent().height() > 15)
    scaleToFill(imageSelector);
  else
    $(imageSelector).css({ 'height': 'auto', 'width': 'auto' });
}

// -----------------------------------------------------------------------------
// Search Functions
// -----------------------------------------------------------------------------

function initSearch() {
  var searchForm = $('#searchForm');
  var searchField = $('#search-text');
  var searchDefaultText = $('#search-text-default').val();
  var searchClearButton = $('#search-clear');
  var searchMenu = $(searchField).parent().find('div.wishpot-menu:first');

  // Show default search field text...
  if (searchField.val() == '' || searchField.val() == searchDefaultText) {
    searchField.addClass('default').val(searchDefaultText);
  }
  // ... or set the search button text and show the clear button.
  else {
    var buttonText = searchForm.find('input[checked]').val();
    $('#searchForm button span:first').html(buttonText);
    searchClearButton.show();
  }

  // Form events
  searchForm.mouseenter(function () {
    if (searchField.val() != '' && searchField.val() != searchDefaultText) {
      searchMenu.show();
    }
  })
	.mouseleave(function () {
	  searchMenu.hide();
	  if (searchField.val() == '') {
	    searchField.addClass('default').val(searchDefaultText).blur();
	  }
	})
	.submit(function () {
	  var selectedId = $("input[name='searchtype']:checked").attr('id');
	  var formurl = $('#' + selectedId + '-url').val();
	  var addparams = $('#' + selectedId + '-params').val();
	  if (formurl != null)
	    searchForm.attr('action', formurl);
	  if (addparams != null) {
	    var paramset = addparams.split('=');
	    for (var i = 0; i < paramset.length; i += 2) {
	      searchForm.append("<input type='hidden' name='" + paramset[i] + "' value='" + paramset[i + 1] + "' />");
	    }
	  }
	  //make sure the button label isn't submitted
	  $("input[name='searchtype']").removeAttr('name');
	});

  // Search field events
  searchField.focus(function () {
    // Hide default text
    if (searchField.val() == searchDefaultText) {
      searchField.val('').removeClass('default');
    }
    // Show search menu, hide others
    $('#wishpot-topnav .wishpot-menu').hide();
    searchMenu.show();
  })
	.keyup(function () {
	  searchMenu.show();
	  if ($(this).val() != '') {
	    searchClearButton.show();
	  }
	  else {
	    searchClearButton.hide();
	  }
	});

  // Search menu radio events
  searchForm.find('input[type=radio]').each(function () {
    $(this).click(function () {
      var buttonText = $(this).val();
      var formurl = $('#' + this.id + '-url').val();
      $('#searchForm button span:first').html(buttonText);
      searchForm.attr('action', formurl);
    })
		.change(function () {
		  searchField.select();
		});
  });

  // Clear search button events	
  searchClearButton.click(function () {
    searchField.val('').focus();
    $(this).hide();
    return false;
  });
}

function initTopNav() {
  $('#wishpot-topnav li.section').hover(
		function () {
		  $('#header .wishpot-menu, #wishpot-topnav .wishpot-menu').hide().stop();
		  $(this).find('div.wishpot-menu').show();
		},
		function () {
		  $(this).find('div.wishpot-menu').hide().stop();
		}
	);
  $('#wishpot-topnav div.section a').focus(function () {
    $('#header .wishpot-menu, #wishpot-topnav .wishpot-menu').hide();
    $(this).parents('li:first').find('div.wishpot-menu').show();
  });
  $('#wishpot-topnav a:last').blur(function () {
    $(this).parents('div.wishpot-menu:first').hide();
  });
}

// -----------------------------------------------------------------------------
// Content Functions
// -----------------------------------------------------------------------------

function initToggleContent() {
  $('dl.toggle dt a').click(function () {
    $(this).parents('dl.toggle:first').find('dd').toggle('fast', function () {
      initFluidLists($(this).find('ol.fluid'));
    });
    return false;
  });
  $('ol.toggle > li, ul.toggle > li').find('a:first').click(function () {
    $(this).nextAll().toggle('fast', function () {
      initFluidLists($(this).find('ol.fluid'));
    });
    return false;
  });
  $('a.toggle').click(function () {
    $(this).find('.toggle').toggle();
    $($(this).attr('rel')).toggle('fast');
    return false;
  });
}


function initMoreLinks() {
  $('a.more').click(function () {
    var link = $(this);
    var href = link.attr('href');
    var rel = link.attr('rel');
    // Ajax
    if (link.hasClass('ajax')) {
      var target = $('#' + rel);
      if (target.length == 0) {
        target = link.parent().prepend('<div id="' + rel + '" style="display: none;"></div>');
      }
      $('#' + rel).load(href, function (response, status, xhr) {
        $('#' + rel).fadeIn('400', function () {
          initFluidLists('#' + rel + ' ol.fluid');
        });
        link.remove();
      });
      return false;
    }
    // Iframes
    else if (link.hasClass('iframe')) {
      var iframeHTML = '<iframe src="' + href + '" id="' + rel + '" name="' + rel + '" allowtransparency="true" frameborder="no" scrolling="no" style="display: block; height: 0; line-height: 0; width: 100%;"></iframe>';
      link.parent().prepend(iframeHTML);
      $('#' + rel).load(function () {
        var height = frames[rel].document.body.scrollHeight;
        $(this).css('height', height + 'px').hide().fadeIn();
        link.remove();
      });
      return false;
    }
  });
}

// -----------------------------------------------------------------------------
// Helper Functions
// -----------------------------------------------------------------------------

function getBackgroundPosition(obj) {
  // Other Browsers
  var string = jQuery(obj).css('background-position');
  // Internet Explorer
  if (string == undefined) {
    string = jQuery(obj).css('background-position-x') + ' ' + jQuery(obj).css('background-position-y');
  }
  // Pixel values
  if (string.indexOf('px') != -1) {
    var objheight = jQuery(obj).height();
    var objWidth = jQuery(obj).width();
    var x = string.split(' ')[0];
    var y = string.split(' ')[1];
    x = x == '0px' ? '0%' : x == objWidth + 'px' ? '100%' : x == (objWidth / 2) + 'px' ? '50%' : x;
    y = y == '0px' ? '0%' : y == objheight + 'px' ? '100%' : y == (objheight / 2) + 'px' ? '50%' : y;
    string = x + ' ' + y;
  }
  // Label values
  string = string.replace(/top/g, '0%');
  string = string.replace(/bottom/g, '100%');
  string = string.replace(/left/g, '0%');
  string = string.replace(/right/g, '100%');
  string = string.replace(/center/g, '50%');
  return string;
}

function hexToHsb(hexstring) {
  return rgbToHsb(hexToRgb(hexstring));
}

function hexToRgb(hexstring) {
  // Ex: "#336699"
  var red = parseInt(hexstring.substring(1, 3), 16);
  var green = parseInt(hexstring.substring(3, 5), 16);
  var blue = parseInt(hexstring.substring(5, 7), 16);
  return new Array(red, green, blue);
}

function hsbToHex(hsb) {
  return rgbToHex('rgb(' + hsbToRgb(hsb) + ')');
}

function hsbToRgb(hsb) {
  var br = Math.round(hsb[2] / 100 * 255);
  if (hsb[1] == 0) {
    return [br, br, br];
  }
  else {
    var hue = hsb[0] % 360;
    var f = hue % 60;
    var p = Math.round((hsb[2] * (100 - hsb[1])) / 10000 * 255);
    var q = Math.round((hsb[2] * (6000 - hsb[1] * f)) / 600000 * 255);
    var t = Math.round((hsb[2] * (6000 - hsb[1] * (60 - f))) / 600000 * 255);
    switch (Math.floor(hue / 60)) {
      case 0: return [br, t, p];
      case 1: return [q, br, p];
      case 2: return [p, br, t];
      case 3: return [p, q, br];
      case 4: return [t, p, br];
      case 5: return [br, p, q];
    }
  }
  return false;
}

function rgbToHex(rgbstring) {
  // Ex: "rgb(0, 70, 255)"
  if (rgbstring) {
    if (rgbstring.indexOf('rgb(') == -1) {
      return rgbstring;
    }
    var parts = rgbstring.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    delete (parts[0]);
    for (var i = 1; i <= 3; ++i) {
      parts[i] = parseInt(parts[i], 0).toString(16);
      if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    var hexstring = parts.join('');
    return '#' + hexstring;
  }
}

function rgbToHsb(rgb) {
  var red = rgb[0], green = rgb[1], blue = rgb[2];
  var hue, saturation, brightness;
  var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
  var delta = max - min;
  brightness = max / 255;
  saturation = (max != 0) ? delta / max : 0;
  if (saturation == 0) {
    hue = 0;
  } else {
    var rr = (max - red) / delta;
    var gr = (max - green) / delta;
    var br = (max - blue) / delta;
    if (red == max) hue = br - gr;
    else if (green == max) hue = 2 + rr - br;
    else hue = 4 + gr - rr;
    hue /= 6;
    if (hue < 0) hue++;
  }
  return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
}

function imageIsNotLoaded(imgObj) {
  //WPJS.Debug("Checking if image has loaded: " + $(imgObj).attr("src"));
  if (typeof (imgObj.naturalWidth) != "undefined") return (imgObj.naturalWidth == 0);
  if (typeof (imgObj.readyState) != "undefined") return (imgObj.readyState == 'uninitialized');
  return ($(imgObj).width() == 0 || $(imgObj).height() == 0);
}

/*
This is the code that runs onload/onready/etc
*/

jQuery(document).ready(function () {
  // Internet Explorer 6 PNG Fix - not yet in use, we use a filter for now
  // if ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined)) {
  //     DD_belatedPNG.fix('.png');
  // }
  if (isFacebookConnectReload()) return;

  // Fluid Lists (items, collections, and users) & Image Scaling
  initFluidLists();
  scaleToFill('.scaletofill img');
  scaleToFit('.scaletofit img');

  //add a param to every form, so we can detect "real" posts inside facebook.
  //don't bother doing this outside of facebook, as it just add url params, and
  //can confuse the CRM form.
  if (window.top != window) {
    jQuery('form').append('<input type="hidden" name="isPost" value="1" />');
  }

  //run any functions who had registered
  if (typeof (WishpotOnDomReadyFunctions) != "undefined") {
    for (x in WishpotOnDomReadyFunctions) {
      WishpotOnDomReadyFunctions[x]();
    }
  }

  // Toggle Content
  initToggleContent();

  // More Links
  initMoreLinks();

  // Add events to buttons
  $('button').click(function () {
    if ($(this).hasClass('clicked')) {
      return false;
    }
    //only mark submit buttons, otherwise clicked will never be cleared
    if ($(this).attr('type') == 'submit') {
      $(this).addClass('clicked');
    }
  });

  // Buttons Spinners
  $('.b-spinready').click(function () {
    //only mark submit buttons, otherwise clicked will never be cleared
    if ($(this).attr('type') == 'submit') {
      $(this).removeClass('b-spinready').addClass('b-spinner');
    }
  });

  //Links with internal anchors, scroll within the page.  Just add a rel="scroll" to them
  $('a[rel=scroll]').click(function () {
    $('html, body').stop().animate({
      scrollTop: jQuery(jQuery(this).attr('href')).offset().top
    }, 1500, 'easeInOutExpo');
  });

  //see if we were instructed to highlight anything
  if (document.location.hash != null && document.location.hash.indexOf("h=") >= 0) {
    var highlightObjName = document.location.hash.substring(document.location.hash.indexOf("h=") + 2);
    if (document.getElementById(highlightObjName) != null)
      WithJQueryUi(function () {
        $("#" + highlightObjName).effect("highlight", {}, 5000);
      });
  }

});

jQuery(window).load(function () {
  WPJS.Debug("window loaded: " + document.location.href);
  if (isFacebookConnectReload()) return;

  // Prevent links with href="#" from jumping
  $('a[href="#"]').click(function () {
    return false;
  });

  correctErroredImages();
});

function isFacebookConnectReload() {
  return (window.location.search.indexOf('fb_xd_bust') >= 0);
}
