jQuery(function($){
/*
 * Copyright (c) 2008 Borgar Thorsteinsson (borgar.net)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */

  // -- text selection helper functions

  function getSelection () {
    return ( $.browser.msie ) 
      ? document.selection
      : ( window.getSelection || document.getSelection )();
  }
  
  function getRange () {
    return ( $.browser.msie ) 
        ? getSelection().createRange()
        : getSelection().getRangeAt( 0 )
  }
  
  function parentContainer ( r ) {
    return ( $.browser.msie )
        ? r.parentElement()
        : r.commonAncestorContainer;
  }
  
  // -- string helper functions
  
  String.prototype.reverse = function () {
    return this.split('').reverse().join('');
  }
  String.prototype.ltrim = function () {
   return this.replace( /^\s+/, '' );
  }
  String.prototype.rtrim = function () {
   return this.replace( /\s+$/, '' );
  }
  String.prototype.trim = function () {
   return this.ltrim().rtrim();
  }

  // -- regexp helper functions

  RegExp.escape = function ( s ) {
   // return s.replace(/[\(\)\^\$\&\.\*\?\-\/\+\|\[\]\\]/g, "\\$&");
   return s.replace(/[\(\)\^\$\.\*\?\/\+\|\[\]\\]/g, "\\$&");
  }
   

  // -- the interesting part of this document:

  function getCurrentWord (e ) {
    var range = getRange(), txt = '', s = null;
    if ( $.browser.msie && range && range.text.length == 0) {
      var end = Math.abs( range.duplicate().moveEnd('character', -1000000) );
      var r = range.duplicate();
      range.collapse( false );
      var parentElm = r.parentElement();
      var children = parentElm.getElementsByTagName('*');
      for (var i = children.length - 1; i >= 0; i--) {
        r.moveToElementText( children[i] );
        if ( r.inRange(r) ) {
          parentElm = children[i];
          break;
        }
      }
      r.moveToElementText( parentElm );
      txt  = parentElm.innerText;
      s    = end - Math.abs( r.moveStart('character', -1000000) ) -1;
    }
    else if (!$.browser.msie && range.startContainer === range.endContainer && 
                         range.startOffset === range.endOffset) {
      txt  = range.startContainer.textContent;
      s    = range.startOffset;
    }
    if (txt && s !== null ) {
      var pre  = txt.substring( 0, s ).reverse().ltrim();
      var post = txt.substring( s, txt.length ).rtrim();
      var pre_i  = pre.search( /(\s+|$)/ );
      var post_i = post.search( /(\s+|$)/ );
      var word = '';
      if ( pre_i > -1 && post_i > -1 ) {
        word = pre.substring( 0, pre_i ).reverse() + post.substring( 0, post_i );
      } 
      else if ( pre_i > -1 ) {
        word = pre.substring( 0, pre_i ).reverse();
      }
      else if ( post_i > -1 ) {
        word = post.substring( 0, post_i );
      }
      
      return word;
    }
    return '';
  }
  
  
  // this should only happen if ("skiptitákn" !== &shy;) and "Skiptiaðferð" == compound
  var hypmeth = $('#hypmeth option[selected]').val();
  var hypeSymbol  = parseInt( $('#symbol option[selected]').val(), 10 ) || 0;
  var hyphenators = ['^-', '-', '~', '¬', '&shy;'];

  if ( hypeSymbol !== 4 && hypmeth == 'compound' ) {
    $('#hyphenated div.b')
      .attr('title', 'Smelltu á orð til þess að laga skiptingu.')
      .click(function (e) {

        var word = getCurrentWord( e ).replace(/\<\/?[a-z1-5]+\>/g, '');
        word = word.replace(/^[\s"'«»!¡¿?#$%&*×\-+±÷·=~¬.,:;\/\\\[\](){}<>|¦^_`´@¤¢£¥§©®¯°ªº¹²³¨µ¶¼½¾]+/, '');
        word = word.replace(/[\s"'«»!¡¿?#$%&*×\-+±÷·=~¬.,:;\/\\\[\](){}<>|¦^_`´@¤¢£¥§©®¯°ªº¹²³¨µ¶¼½¾]+$/, '');
        var orgword = word;
        word = word.replace(/(\^-|-|~|¬|&shy;)+/g, '-');

        $( '#pop' ).remove();

        if ( word ) {

          var pop = $(
            '<div class="pop" id="pop">'+
              '<div class="f_group">'+
                '<input type="hidden" id="orgword" name="orgword" value="" />' + 
                '<div class="fi_txt">'+
                  '<label for="p_newword">Breyta skiptingu orðs í orðabók:</label>'+
                  '<input id="p_newword" name="newword" value="" type="text" />'+
                '</div>'+
                '<div class="fi_btn"><input value="Vista" type="submit" /></div>'+
                '<a href="#" class="close">Loka</a>'+
              '</div>'+
            '</div>');

          pop
            .hide()
            
            .keypress(function (e){
              // escape
              if ( e.keyCode == 27) {
                pop.fadeOut( 300, function () { $(this).remove(); } );
                return false;
              }
              // enter
              if ( e.keyCode == 13) {
                $( this ).find( 'input[type=submit]' ).click();
              }
            })

            // assign action to close button
            .find('a.close')
              .click(function(e){
                pop.fadeOut( 300, function () { $(this).remove(); } );
                return false;
              })
              .end()

            // assign action to save button
            .find('input[type=submit]').click(function(e){

              // find out the correct hyphenation symbol (the one we rode in on)
              var nword = $('input#p_newword').val();
              var oword = $('input#orgword').val();
              
              // strip out the hyphens
              var nclean = nword.replace( /-/g, '' );
              var oclean = oword.replace( hyphenators[hypeSymbol], '', 'g' );
              
              // if cleaned words match, and hyphenation has changed 
              if (nclean == oclean && word != nword) {
                
                var owordrx = new RegExp( RegExp.escape(oword.toLowerCase()), 'gi' );
                var ctx = $('#hyphenated div.b')[0];
                var spl = nword.split('-');

                // capitals must be preserved
                ctx.innerHTML = ctx.innerHTML.replace( owordrx, function ( a ) {
                  var r = [], d = a.replace( hyphenators[hypeSymbol], '', 'g' );
                  for (var l=0,i=0; l<d.length; l+=spl[i++].length) {
                    r.push( d.substring( l, l + spl[i].length ) );
                  }
                  return r.join( hyphenators[hypeSymbol] );
                });

                // notify the server about this
                if (word != nword) {
                  $.ajax({
                    type : 'POST',
                    url  : '/api/hyphenation.add/',
                    data : 'word=' + nword.toLowerCase(),
                  });
                }

              }

              // close popup
              pop.fadeOut( 300, function () { $(this).remove(); } );
              
              return false;
            });

          // display the popup box
          $( 'div.pgmain div.wrap' )
            .append( pop )
            .find( '#pop' )
              .css({
                top :  e.clientY - (pop.height() / 2) + $( window ).scrollTop(),
                left : e.clientX - (pop.width() / 2)
              })
              .find('input#p_newword')
                .val( word )
                .end()
              .find('input#orgword')
                .val( orgword )
                .end()
              .fadeIn( 300, function (){
                  $(this).find('#p_newword').focus();
               });

        }  // if word

      });
  }
  
});