/**
 * Idearranger, Copyright 2007, All Rights Reserved
 * @author Lindsey Simon (lsimon@commoner.com)
 */


jQuery.fn.outerHTML = function(s) {
  return (s)
  ? this.before(s).remove()
  : jQuery('<p>').append(this.eq(0).clone()).html();
};

/* jQuery's onload routine */
$(document).ready(function() {
  // this button is not really needed
  $('.ideas-info-page form button').hide();
  $('.ideas-info-page form select').change(function(e){
    var form = e.target.parentNode;
    form.submit();
  });

  // stars interface?
  idr.starsInit();

  // yes|no interface?
  idr.yesNoInit();


  // turn off message slowly if there's text, otherwise hide
  idr.msg = $('#message-container span');

  if (idr.msg.html() && idr.msg.html().match(/\w/)) {
    idr.timeout = idr.timeoutVisibility();
  }
  else {
    idr.msg.css('visibility', 'hidden');
  }

  // Prevent double click breaking XSRF..
  $('.submit-button').each(function(el) {
    if (el.value == 'Cool, hang on...') {
      $(el).val('Submit');
    }
  });
  $('.submit-button').click(function(e) {
    var el = $(this);
    el.disabled = true;
    el.val('Cool, hang on...');
  });


  // put the tooltip in the body
  idr.tooltip = $('<div id="tooltip" class="tooltip" style="display:none"></div>');
  idr.tooltip.appendTo(document.body);

  idr.tooltip.mouseout(function(e) {
    if (e.target.id) {
      return;
    }
    if (e.relatedTarget != 'tooltip') {
      return;
    }
    idr.tooltip.hide();
  });

  // description tooltip for full text
  $('#ideas-list td.description').mouseover(function(e) {
    // really this is mouseenter
    if (e.relatedTarget && !idr.isAncestor(this, e.relatedTarget)) {
      var td = this;
      idr.showDescriptionTooltip(td);
    }
  });

  // description tooltip for full text
  $('#ideas-list td.description').mouseout(function(e) {
    var case1 = idr.isAncestor(this, e.target);
    var case2 = idr.isAncestor(this, e.relatedTarget);
    var mousedIntoTooltip = e.relatedTarget && e.relatedTarget.id == 'tooltip';
    // really this is mouseout
    if (e.relatedTarget && case1 && !case2 && !mousedIntoTooltip) {
      idr.tooltip.hide();
    }
  });

  // set up keyboard navigation
  $('#ideas-list tr').keynav('row-selected', 'row-unselected');

  // hover style
  $('#ideas-list tr').hover(
    function (e) {
      $('#ideas-list tr.row-selected').removeClass('row-selected');
      $(this).addClass('row-selected');
    },
    function (e) {
      if (e.relatedTarget && e.relatedTarget.id == 'tooltip') {
        return;
      }
      $(this).removeClass('row-selected');
    }
  );

  // search options
  $('.show-search-options').click(function(e) { idr.showSearchOptions(e); });
  $('#search-options a').click(function(e) { idr.hideSearchOptions(e); });

  // email
  //idr.dialogInit();
  //$('.title .admin-email').click(function(e) { idr.dialogOpen(e); });

  // define an ajax error
  $().ajaxError(function(ev, xhr, s) {
    //console.debug(xhr);
    alert('Sorry, but there was a server side error saving your stars. Please email lsimon@commoner.com and tell him about your browser and what happened. It will be fixed ASAP for everyone that way.');
  });

});

var idr = {};
idr.ua = navigator.userAgent;
idr.isOpera = typeof opera != 'undefined';
idr.isSafari = !idr.isOpera && idr.ua.indexOf('WebKit') != -1;
idr.isAncestor = function(p, c) {
  if (!p || !c) {return false;}

  if (p.contains && !idr.isSafari) {
    //console.debug('used contains');
    return p == c || p.contains(c);
  } else if (p.compareDocumentPosition) {
    //console.debug('used compare');
    return p == c || !!(p.compareDocumentPosition(c) & 16);
  } else {
    var parent = c.parentNode;
    while (parent) {
      if (parent == p) {
        return true;
      }
      else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
        return false;
      }
      parent = parent.parentNode;
    }
    return false;
  }
};


idr.showDescriptionTooltip = function(td) {
  var pos = $(td).offset();
  var left = pos.left + 20 + 'px';
  var top = pos.top + td.offsetHeight - 5 + 'px';
  var yesno = $(td.parentNode).find('.yesno');
  var tooltipHtml = $(td).html() + yesno.outerHTML();
  idr.tooltip.html(tooltipHtml);
  idr.tooltip.css({
    left: left,
    top: top,
    width: td.offsetWidth + 50 + 'px'
  });

  // set up yesno click mapping
  var yesno_yes = idr.tooltip.find('.yesno-yes a');
  var real_yesno_yes = $(td.parentNode).find('.yesno-yes a').get(0);
  yesno_yes.click(function(e) {
    $(real_yesno_yes).trigger('click');
    e.preventDefault();
  });
  var yesno_no = idr.tooltip.find('.yesno-no a');
  var real_yesno_no = $(td.parentNode).find('.yesno-no a').get(0);
  yesno_no.click(function(e) {
    $(real_yesno_no).trigger('click');
    e.preventDefault();
  });

  idr.tooltip.show();
};


/**
 * Yes|No interface
 */
idr.yesNoInit = function() {
  var yesno = $('.yesno a');
  if (!yesno) {
    return;
  }
  yesno.click(idr.yesNoUpdate);
};

idr.yesNoUpdate = function(e) {
  e.preventDefault();
  var link = $(this);
  var undo = false;

  var url = link.attr('href').replace(/\?.*/, '');
  var xsrfToken = document.getElementById('xsrf_token').value;

  // Undo
  if (link.attr('class').match(/\byesno\-sel\b/)) {
    undo = true;
    var re = /\/\-?1\/?$/;
    url = url.replace(re, '/0');;
  }


  window.clearTimeout(idr.timeout);
  idr.msg.css('visibility', 'hidden');
  idr.msg.html('Saving your vote...');
  idr.msg.css('visibility', 'visible');

  $.getJSON(url, null, function(json) {
    if (!json.success) {

      // set the message
      idr.msg.html(json.message);

      // make sure we scroll to the top
      window.scroll(0, 0);
    }
    else {

      // remove other yesno-sel distinguishment
      link.parents('.yesno').find('a.yesno-sel').each(function(el) {
        $(this).removeClass('yesno-sel');
      });
      $('#tooltip .yesno-sel').each(function(el) {
        $(this).removeClass('yesno-sel');
      });

      if (!undo) {
        var classToHightlight = link.get(0).parentNode.className;
        $('#tooltip .' + classToHightlight + ' a').each(function(el) {
          $(this).addClass('yesno-sel');
        });
        link.addClass('yesno-sel');
      }

      if (json.message) {

        // set the msg
        idr.msg.css('visibility', 'hidden');
        idr.msg.html(json.message);
        idr.msg.css('visibility', 'visible');

        // timeout the msg
        idr.timeout = idr.timeoutVisibility();

        // get row
        var trs = $(link).parents('tr');

        // then highlight
        trs.highlightFade();
      }

      // try to remove the stars
      if (!json.saved) {
        // remove other yesno-sel distinguishment
        link.parents('.yesno').find('a.yesno-sel').each(function(el) {
          $(this).removeClass('yesno-sel');
        });
        // make sure we scroll to the top
        window.scroll(0,0);
      }
    }
  });

};


/**
 * @param {Number} timeout
 */
idr.timeoutVisibility = function(timeout) {
  timeout = timeout || 15000;
  return window.setTimeout(
    function() {
      idr.msg.css('visibility', 'hidden');
    }, timeout
  );
}


/**
 * showSearchOptions
 * @param {Event} e
 */
idr.showSearchOptions = function(e) {
  $('#search-q').hide();
  $('#search-options').show();
  e.preventDefault();
};

/**
 * hideSearchOptions
 * @param {Event} e
 */
idr.hideSearchOptions = function(e) {
  $('#search-q').show();
  $('#search-options').hide();
  e.preventDefault();
};




/**
 * Initialize the stars interface
 */
idr.starsInit = function() {
  var starslinks = $('.stars li a');
  if (!starslinks) {
    return;
  }
  // add a click hander for the stars
  $('.stars li a').click(function(e) {

    // stop the event
    e.preventDefault();
    $(e.target).trigger('blur');

    // update stars
    var current = $(this).parent().parent().children()[0];
    var stars = parseInt(this.className.replace('s-', ''));
    idr.updateStars(stars, current);
  });

  // 0 star is special cuz this is sorta set up dumb
  $('.s-0').click(function(e) {

    // stop the event
    e.preventDefault();
    $(e.target).trigger('blur');

    var span = $(this).next();
    var ul = $(span).children()[0];
    var current = $(ul).children()[0];
    idr.updateStars(0, current);
  });
  $('#bd a.s-0').mouseover(function(e) {
    var span = $(this).next();
    var ul = $(span).children()[0];
    var current = $(ul).children()[0];
    $(current).hide();
  });


  // need to turn off current when we mouse over stars
  $('#bd span.stars-inline').mouseover(function(e) {
    var ul = $(this).children()[0];
    var current = $(ul).children()[0];
    $(current).hide();
  });
  $('#bd span.stars-inline').mouseout(function(e) {
    var ul = $(this).children()[0];
    var current = $(ul).children()[0];
    $(current).show();
  });
};

/**
 * updateStars sends XHR with new rating of an idea
 * @param {Number} stars
 * @param {Element} current is the li that stores the current rating
 */
idr.updateStars = function(stars, current) {
  //console.debug('update ' + stars + ', ' + current);
  var originalWidth = current.style.width;
  var newWidth = stars * 20;
  current.style.width = newWidth + '%';
  $(current).trigger('blur');

  var ideaId = current.id.replace('stars-', '');
  var xsrfToken = document.getElementById('xsrf_token').value;

  var url = '/stars/update/' + ideaId + '/' + stars + '/' + xsrfToken;


  //msg.css('opacity', '0');
  window.clearTimeout(idr.timeout);
  idr.msg.css('visibility', 'hidden');
  idr.msg.html('Saving your stars...');
  idr.msg.css('visibility', 'visible');

  $.getJSON(url, null, function(json) {
    if (!json.success) {
      console.debug('Failed save stars for idea: ' + ideaId);
      current.style.width = '0%';

      // set the message
      idr.msg.html(json.message);

      // make sure we scroll to the top
      window.scroll(0,0);
    }
    else {
      //console.debug('Saved stars for idea: ' + ideaId + ', ' + json.message);
      if (json.message) {

        // set the msg
        idr.msg.css('visibility', 'hidden');
        idr.msg.html(json.message);
        idr.msg.css('visibility', 'visible');

        // timeout the msg
        idr.timeout = idr.timeoutVisibility();

        // get row
        var trs = $(current).parents('tr');

        // then highlight
        trs.highlightFade({
          complete: function() {
            this.style.backgroundColor = '';
          }
        });
      }

      // try to remove the stars
      if (!json.saved) {
        //console.debug('not saved', originalWidth);
        current.style.width = originalWidth;
        $(current).trigger('blur');
        // make sure we scroll to the top
        window.scroll(0,0);
      }
    }
  });

};


/**
 *
idr.dialogInit = function(e) {

  idr.dialog = document.createElement('div');
  idr.dialog.title = '';
  idr.dialogContent = document.createElement('p');
  idr.dialog.appendChild(idr.dialogContent);
  document.body.appendChild(idr.dialog);
  $(idr.dialog).dialog({
    autoOpen: false,
    width: 600,
    buttons: {
      'Ok': function() {
        $(this).dialog('close');
      },
      'Cancel': function() {
        $(this).dialog('close');
      }
    }
  });
  idr.dialogTitle = $('#ui-dialog-title-ideas-dialog');
};

@param {event} e
idr.dialogOpen = function(e) {
  var href = e.target.href;
  jQuery.get(href, {}, function(response, e) {
    //$(idr.dialogContent).html(response);
    //$(idr.dialog).dialog('open');
  });

  e.preventDefault();
};
 */




