var pos;
var posXword;
var posYword;
var posXbtn;
var posYbtn;

$(document).ready(function() {

  if($.jqURL.qs()) {
    // There is a querystring, so this is an auto-search.

    var searchText  = $.jqURL.get("txt").replace(/\+/g,' ');
    $('#s_word').val("");

    // Make the mouse pointer image visible.
    $("#mousepointer").animate({ 
      opacity: 1
    }, 10 );

    // Get the positions of the input and button.
    pos        = $("#s_word").position();
    posXword   = pos.left + 10; 
    posYword   = pos.top + 10;

    pos            = $("#btn").position();
    posXbtn = pos.left + 30; 
    posYbtn = pos.top + 10;

    // Move to search text.
    $("#mousepointer").animate({ 
      left: posXword+'px',
      top:  posYword+'px'
    }, 2000, function() {
      // Set the search text.
      $("#s_word").val(searchText);
    });

    // Move to button.
    $("#mousepointer").animate({ 
      left: posXbtn+'px',
      top:  posYbtn+'px'
    }, 2000, function() {
      // Show the auto-search message.
      fnMessage();
    });
  }
});


function fnMessage() {
  // Show auto search message.
  $('#family_db').before('<div id="message"><p style="font-weight:bold; font-size:15pt">Now you know how to search the documentation at <a href="http://tahiti.oracle.com">http://tahiti.oracle.com</a>.</p></div>'); 

  // Use animate to pause before click. It's not really animating anything.
  $("#mousepointer").animate({
    left: posXbtn+'px',
    top:  posYbtn+'px'
  }, 3000, function() {
    // Click the button.
    $("#btn").click();
  });
}


function fnSubmit(form) {
  // Decide if this is an auto-click or manual.
  if($.jqURL.qs()) {
    form.submit();
  } else {
    fnSearch(form);
  }
}

function fnSearch(form) {
  // Display the auto-URL
  var doc_url = "http://www.oracle-base.com/search/?txt=" + form.s_word.value.replace(/ /g, '+');

  getTinyURL(doc_url, function(tinyurl){
    $('#family_db').before('<div id="auto_url_div"><p>' +
      '<br />'+
      'Use the following URL to provide someone with an automated search.<br />'+
      '<form class="searchform"><input id="tiny_auto_url" type="text" name="auto_url" size="40" value="'+tinyurl+'" /><br />'+
      '<input id="go" type="button" value="Go Now" onclick="javascript:fnGo()" /></form><br />'+
      '</p></div>');
  });
}
 
function fnGo() {
  $('#searchform').submit();
}

function getTinyURL(longURL, success) {
 
    var API = 'http://json-tinyurl.appspot.com/?url=',
        URL = API + encodeURIComponent(longURL) + '&callback=?';
 
	$.getJSON(URL, function(data){
    	success && success(data.tinyurl);
    });
 }

