$(function () {
  $('.embed_player').each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 2000;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.embed_trigger');
    var popup = $('.embed_popup');
    var txtarea = $('textarea', popup);

    function update_embed_code() {
        // look for checkbox, follback to hidden field
        var code = $('input[name=embed_type]:checked', popup);
        if (code.length == 0) {
                code = $('input', popup);
        }
        txtarea.get(0).value = unescape(code.val());
        txtarea.focus().select();
    }
    
    $('input', popup).click(function () {
        update_embed_code();
    });
    
    $('textarea', popup).click(function() {
        txtarea.focus().select();            
    })
    
    $([trigger.get(0)]).click(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        // reset position of popup box
        popup.css({
          top: trigger.offset().top - popup.innerHeight() - 8,
          left: trigger.offset().left + - popup.innerWidth() + trigger.innerWidth(),
          display: 'block' // brings the popup back in to view
        })
        update_embed_code();
      }
    });
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
        if (hideDelayTimer) clearTimeout(hideDelayTimer);
    });
    popup.mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.css('display', 'none');
      }, hideDelay);
    });
    
    // default to 1st item in drop down
    if (!$.browser.safari) {
            $('#embed_type_this', popup).attr("checked", true); 
    }
    update_embed_code();
  });
});