
var PP_autocomplete = PP_autocomplete || {};
var ActiveAutoCompleteAjaxURL = "";
/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
PP_autocomplete.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;

/**
 * Extends the current object with the parameter. Works recursively.
 */
PP_autocomplete.extend = function(obj) {
  for (var i in obj) {
    if (this[i]) {
      PP_autocomplete.extend.apply(this[i], [obj[i]]);
    }
    else {
      this[i] = obj[i];
    }
  }
};

/**
 * Redirects a button's form submission to a hidden iframe and displays the result
 * in a given wrapper. The iframe should contain a call to
 * window.parent.iframeHandler() after submission.
 */
PP_autocomplete.redirectFormButton = function (uri, button, handler) {
  // Trap the button
  button.onmouseover = button.onfocus = function() {
    button.onclick = function() {
      // Create target iframe
      PP_autocomplete.createIframe();

      // Prepare variables for use in anonymous function.
      var button = this;
      var action = button.form.action;
      var target = button.form.target;

      // Redirect form submission to iframe
      this.form.action = uri;
      this.form.target = 'redirect-target';

      handler.onsubmit();

      // Set iframe handler for later
      window.iframeHandler = function () {
        var iframe = $('#redirect-target').get(0);
        // Restore form submission
        button.form.action = action;
        button.form.target = target;

        // Get response from iframe body
        try {
          response = (iframe.contentWindow || iframe.contentDocument || iframe).document.body.innerHTML;
          // Firefox 1.0.x hack: Remove (corrupted) control characters
          response = response.replace(/[\f\n\r\t]/g, ' ');
          if (window.opera) {
            // Opera-hack: it returns innerHTML sanitized.
            response = response.replace(/&quot;/g, '"');
          }
        }
        catch (e) {
          response = null;
        }

        response = PP_autocomplete.parseJson(response);
        // Check response code
        if (response.status == 0) {
          handler.onerror(response.data);
          return;
        }
        handler.oncomplete(response.data);

        return true;
      }

      return true;
    }
  }
  button.onmouseout = button.onblur = function() {
    button.onclick = null;
  }
};

/**
 * Retrieves the absolute position of an element on the screen
 */
PP_autocomplete.absolutePosition = function (el) {
  var sLeft = 0, sTop = 0;
  var isDiv = /^div$/i.test(el.tagName);
  if (isDiv && el.scrollLeft) {
    sLeft = el.scrollLeft;
  }
  if (isDiv && el.scrollTop) {
    sTop = el.scrollTop;
  }
  var r = { x: el.offsetLeft - sLeft, y: el.offsetTop - sTop };
  if (el.offsetParent) {
    var tmp = PP_autocomplete.absolutePosition(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

/**
 * Return the dimensions of an element on the screen
 */
PP_autocomplete.dimensions = function (el) {
  return { width: el.offsetWidth, height: el.offsetHeight };
};

/**
 *  Returns the position of the mouse cursor based on the event object passed
 */
PP_autocomplete.mousePosition = function(e) {
  return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop };
};

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
PP_autocomplete.parseJson = function (data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : 'Unspecified error' };
  }
  return eval('(' + data + ');');
};

/**
 * Create an invisible iframe for form submissions.
 */
PP_autocomplete.createIframe = function () {
  if ($('#redirect-holder').size()) {
    return;
  }
  // Note: some browsers require the literal name/id attributes on the tag,
  // some want them set through JS. We do both.
  window.iframeHandler = function () {};
  var div = document.createElement('div');
  div.id = 'redirect-holder';
  $(div).html('<iframe name="redirect-target" id="redirect-target" class="redirect" onload="window.iframeHandler();"></iframe>');
  var iframe = div.firstChild;
  $(iframe)
    .attr({
      name: 'redirect-target',
      id: 'redirect-target'
    })
    .css({
      position: 'absolute',
      height: '1px',
      width: '1px',
      visibility: 'hidden'
    });
  $('body').append(div);
};

/**
 * Delete the invisible iframe
 */
PP_autocomplete.deleteIframe = function () {
  $('#redirect-holder').remove();
};

/**
 * Freeze the current body height (as minimum height). Used to prevent
 * unnecessary upwards scrolling when doing DOM manipulations.
 */
PP_autocomplete.freezeHeight = function () {
  PP_autocomplete.unfreezeHeight();
  var div = document.createElement('div');
  $(div).css({
    position: 'absolute',
    top: '0px',
    left: '0px',
    width: '1px',
    height: $('body').css('height')
  }).attr('id', 'freeze-height');
  $('body').append(div);
};

/**
 * Unfreeze the body height
 */
PP_autocomplete.unfreezeHeight = function () {
  $('#freeze-height').remove();
};

/**
 * Wrapper to address the mod_rewrite url encoding bug
 */
PP_autocomplete.encodeURIComponent = function (item, uri) {
  uri = uri || location.href;
  item = encodeURIComponent(item).replace('%2F', '/');
  return uri.indexOf('?q=') ? item : item.replace('%26', '%2526').replace('%23', '%2523');
};

// Global Killswitch on the <html> element
if (PP_autocomplete.jsEnabled) {
  document.documentElement.className = 'js';
}


// Code Starts Here

/**
 * Attaches the autocomplete behaviour to all required fields
 */
PP_autocomplete.autocompleteAutoAttach = function () {
  var acdb = [];
  $('input.headerautocomplete').each(function () {
    var uri = this.value;
		ActiveAutoCompleteAjaxURL = uri;
    if (!acdb[uri]) {
      acdb[uri] = new PP_autocomplete.ACDB(uri);
    }
    var input = $('#' + this.id.substr(0, this.id.length - 13))
      .attr('autocomplete', 'OFF')[0];
    $(input.form).submit(PP_autocomplete.autocompleteSubmit);
    new PP_autocomplete.jsAC(input, acdb[uri]);
  });
}

/**
 * Prevents the form from submitting if the suggestions popup is open
 * and closes the suggestions popup when doing so.
 */
PP_autocomplete.autocompleteSubmit = function () {
  return $('#autocomplete').each(function () {
    this.owner.hidePopup();
  }).size() == 0;
}

/**
 * An AutoComplete object
 */
PP_autocomplete.jsAC = function (input, db) {
  var ac = this;
  this.input = input;
  this.db = db;

  $(this.input)
    .keydown(function (event) { return ac.onkeydown(this, event); })
    .keyup(function (event) { ac.onkeyup(this, event) })
    .blur(function () { ac.hidePopup(); ac.db.cancel(); });

};

/**
 * Handler for the "keydown" event
 */
PP_autocomplete.jsAC.prototype.onkeydown = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 40: // down arrow
      this.selectDown();
      return false;
    case 38: // up arrow
      this.selectUp();
      return false;
    default: // all other keys
      return true;
  }
}

/**
 * Handler for the "keyup" event
 */
PP_autocomplete.jsAC.prototype.onkeyup = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 16: // shift
    case 17: // ctrl
    case 18: // alt
    case 20: // caps lock
    case 33: // page up
    case 34: // page down
    case 35: // end
    case 36: // home
    case 37: // left arrow
    case 38: // up arrow
    case 39: // right arrow
    case 40: // down arrow
      return true;

    case 9:  // tab
    case 13: // enter
    case 27: // esc
      this.hidePopup(e.keyCode);
      return true;

    default: // all other keys
      if (input.value.length > 0){
        this.populatePopup();
	  }
      else{
        this.hidePopup(e.keyCode);
		 $('#ul_lst').remove();
	$('#People_hd').remove();
	document.getElementById('frame1').style["display"]="none";
	  }
      return true;
  }
}

/**
 * Puts the currently highlighted suggestion into the autocomplete field
 */
PP_autocomplete.jsAC.prototype.select = function (node) {
  window.location.href = node.autocompleteValue;
}

 /**
 * Highlights the next suggestion
 */
PP_autocomplete.jsAC.prototype.selectDown = function () {
  if (this.selected && this.selected.nextSibling) {
    this.highlight(this.selected.nextSibling);
  }
  else {
    var lis = $('li', this.popup);
    if (lis.size() > 0) {
      this.highlight(lis.get(0));
    }
  }
}

/**
 * Highlights the previous suggestion
 */
PP_autocomplete.jsAC.prototype.selectUp = function () {
  if (this.selected && this.selected.previousSibling) {
    this.highlight(this.selected.previousSibling);
  }
}

/**
 * Highlights a suggestion
 */
PP_autocomplete.jsAC.prototype.highlight = function (node) {
  if (this.selected) {
    $(this.selected).removeClass('selected');
  }
  $(node).addClass('selected');
  this.selected = node;
}

/**
 * Unhighlights a suggestion
 */
PP_autocomplete.jsAC.prototype.unhighlight = function (node) {
	
  $(node).removeClass('selected');
  this.selected = false;
}

/**
 * Hides the autocomplete suggestions
 */
PP_autocomplete.jsAC.prototype.hidePopup = function (keycode) {
	document.getElementById('frame1').style["display"]="none";
  //Hack :: Enter Key Issue Fixed
  if (this.selected) {
    PP_autocomplete.jsAC.prototype.select(this.selected);
  }
  
  // Select item if the right key or mousebutton was pressed
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    //this.input.value = this.selected.autocompleteValue;
  }
  // Hide popup
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function() { $(popup).remove(); });
  }
  this.selected = false;
  
  //document.getElementById('compose_to').value = '';
}

/**
 * Positions the suggestions popup and starts a search
 */
PP_autocomplete.jsAC.prototype.populatePopup = function () {
  // Show popup
 
  this.selected = false;
  this.popup = document.createElement('div');
  this.popup.id = 'headerautocomplete';
  this.popup.owner = this;
  var offsetHeight_iframe = this.input.offsetHeight;
  
  $(this.popup).css({
    marginTop: offsetHeight_iframe +2+ 'px',
    /*width: (this.input.offsetWidth - 4) +'px',*/
    width:'312px',
    display: 'none',
	marginLeft:'10px',
	border:'none'
	
  });
  $(this.input).before(this.popup);
  // Do search
  this.db.owner = this;
  this.db.search(this.input.value);
}

/**
 * Fills the suggestion popup with any matches received
 */
PP_autocomplete.jsAC.prototype.found = function (matches) {
  // If no value in the textfield, do not show the popup.
  if (!this.input.value.length) {
    return false;
  }


		
    $('#ul_lst').remove();
	$('#People_hd').remove();
	document.getElementById('frame1').style["display"]="none";
	  
  // Prepare matches
  var ul = document.createElement('ul');
ul.id = 'ul_lst';
  var ac = this; 
  var nummatches = 0;
  for (key in matches) {
    nummatches++;
  }
  if(nummatches){  
    var divhd = document.createElement('div');
	divhd.id="People_hd"; 
    divhd.style.background = '';
    $(divhd).html('<div style="height:100%; padding:3px 7px;background:#f4f4f4 url(./Themes/Release/images/arrow.jpg) no-repeat 97% 6px ; text-align:left;font-size:11px; color:#9b9172; ">People from your contact list.......</div>');
    //$(ul).append(li);
  }
  for (key in matches) {
    var li = document.createElement('li');
    $(li)
      .html('<div style="height:100%; padding:0px;">'+ matches[key] +'</div>')
      .mousedown(function () { ac.select(this); })
      .mouseover(function () { ac.highlight(this); })
      .mouseout(function () { ac.unhighlight(this); });
      li.autocompleteValue = key;      
    $(ul).append(li);
  }

  
  // Show popup with matches, if any
  if (this.popup) {
	  var ifrm=document.getElementById('frame1');
	  $(ul).css({'border-left':'2px solid #cecece',
				'border-bottom':'2px solid #cecece',
				'border-right':'2px solid #cecece'				
				});
	  $(divhd).css({'border-left':'2px solid #cecece',
				'border-top':'2px solid #cecece',
				'border-right':'2px solid #cecece'				
				});
    if (ul.childNodes.length > 0) {
	$(this.popup).empty().append(divhd);
      $(this.popup).append(ul).show();
	  ifrm.style["display"]="block";
		ifrm.style.height=(this.popup).offsetHeight+6;
		
  }
    else {
   $(this.popup).css({visibility: 'hidden'});
    this.hidePopup();
		   $(this.popup).css({'display':'none'});
		  
 		
	   
    }
  }
}

PP_autocomplete.jsAC.prototype.setStatus = function (status) {
  switch (status) {
    case 'begin':
      $(this.input).addClass('throbbing');
      break;
    case 'cancel':
    case 'error':
    case 'found':
      $(this.input).removeClass('throbbing');
      break;
  }
}

/**
 * An AutoComplete DataBase object
 */
PP_autocomplete.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 300;
  this.cache = {};
}
/**
 * Performs a cached and delayed search
 */
PP_autocomplete.ACDB.prototype.search = function (searchString) {
  // HACK for adding multiple values
  frexr_string = searchString.split(",");
  frexr_string_length = frexr_string.length;
  searchString = trim(frexr_string[frexr_string_length - 1]);

  var db = this;
  this.searchString = searchString;
	db.uri = ActiveAutoCompleteAjaxURL;
  // See if this key has been searched for before
  if (this.cache[searchString]) {
    //return this.owner.found(this.cache[searchString]);
  }
  
  if (this.cache['%']) {
    //return this.owner.found(this.cache['%']);
  }

  // Initiate delayed search
  if (this.timer) {
    clearTimeout(this.timer);
  }
	if(ActiveAutoCompleteAjaxURL.length > 5){
  this.timer = setTimeout(function() {
    db.owner.setStatus('begin');

    // Ajax GET request for autocompletion
    $.ajax({
      type: "GET",
      url: db.uri +'&string='+ PP_autocomplete.encodeURIComponent(searchString),
      success: function (data) {
        // Parse back result
        var matches = PP_autocomplete.parseJson(data);
        if (typeof matches['status'] == 'undefined' || matches['status'] != 0) {
          db.cache[searchString] = matches;
          //db.cache['%'] = matches;
          // Verify if these are still the matches the user wants to see
          if (db.searchString == searchString) {
            db.owner.found(matches);
          }
          db.owner.setStatus('found');
        }
      },
      error: function (xmlhttp) {
        //alert('An HTTP error '+ xmlhttp.status +' occured.\n'+ db.uri);
      }
    });
  }, this.delay);
	}
}
/**
 * Cancels the current autocomplete request
 */
PP_autocomplete.ACDB.prototype.cancel = function() {
  if (this.owner) this.owner.setStatus('cancel');
  if (this.timer) clearTimeout(this.timer);
  this.searchString = '';
}

// Global Killswitch
if (PP_autocomplete.jsEnabled) {
  $(document).ready(PP_autocomplete.autocompleteAutoAttach);
}
