/**
 * Contact Link functions (C) 2009, Absent Oy
 */
 
var isWorking   = false
var callbackUrl = "";
var requestUrl  = "";
var request     = null;
var targetId    = null;
var linkId      = null;
var imageRequestUrl  = "";
var imageTargetId    = null;

/**
 * Function initializes a request object which has already been constructed.
 * Parameters:
 *  requestType    - HTTP request type: GET or POST.
 *  url            - The URL of the handler script.
 *  asynchronous   - Boolean: use asynchronous connection or not.
 *  responseHandle - The name of the function that will handle the response.
 */
function initRequest( requestType, url, asynchronous, responseHandle ) {
  try {
      // Set the callback function
      request.onreadystatechange = responseHandle;

      // Try to open connection
      request.open( requestType, url, asynchronous );

      if( requestType.toLowerCase() == "post" ) {
        request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" );
        request.send( arguments[4] );
      } else {
        request.send( null );
      }

  } catch (errv) {
    isWorking = false;
    alert(  "The application cannot contact the server at the moment.\n"+
            "Please try again in a few seconds.\n" );
  }
}

/**
 * Function constructs a Request object. Handles both Mozilla-based
 * browsers and Microsoft-browsers.
 * Parameters:
 *  requestType    - HTTP request type: GET or POST.
 *  url            - The URL of the handler script.
 *  asynch         - Boolean: use asynchronous connection or not.
 *  responseHandle - The name of the function that will handle the response.
 *  Note:
 *  Any fifth parameters represented as arguments[4] are the data a
 *  POST request is designed to send.
 */
function httpRequest( requestType, url, asynch, responseHandle ) {
  try
  {
    // Firefox, Opera 8.0+, Safari
    request=new XMLHttpRequest();
  }
  catch (e)
  {
    // Internet Explorer
    try
    {
    request=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        request=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert("Selaimesi ei tue AJAX-toiminnallisuuksia.");
        return false;
      }
    }
  }

  // Test for a null request if neither ActiveXObject was initialized
  if ( request ) {
    if( requestType.toLowerCase() != "post" ) {
      initRequest( requestType, url, asynch, responseHandle );
    } else {
      //the POSTed data
      var args = arguments[4];
      if( args != null && args.length > 0 ){
        initRequest( requestType, url, asynch, responseHandle, args );
      }
    }
  }
}

/**
 * Function initializes the handler. This must be called first as
 * the page using these functions loads up.
 * Parameters:
 *  urlStr - The URL of the handler script. If this string doesn't
 *           include the question mark it is added to its end.
 */
function initHandler( urlStr, targetDivId ) {
  if ( urlStr.indexOf("?") == -1 )
    urlStr = urlStr + "?";

  requestUrl = urlStr;
  targetId 	= targetDivId;
}

// Detect if the browser is IE or not.
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)

// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;

var tempX = 0
var tempY = 0

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  

  return true;
}

function showContactInfo( id, targetWord, searchWord )
{
  if( !isWorking && requestUrl != "" )
  {
    linkId = id;
    isWorking = true;
    var url  = requestUrl + "&cs=" + targetWord + "&css=" + searchWord;

    var anchor = document.getElementById( linkId );
    //var contents = document.getElementById( 'pageReferencePoint' );
    //var top = anchor.offsetTop;
    //var lft = anchor.offsetLeft - 100;
    var top = tempY;
    var lft = tempX;

    //var pageLeft = contents.offsetLeft;
    var div = document.getElementById( targetId );
    div.style.top = top;
    //div.style.left = lft + pageLeft + 250;
    div.style.left = lft - 200;
    div.style.width = "auto";
    div.style.height = "auto";
    div.style.visibility = "visible";
    div.style.display = "inline";

    var oldData = document.getElementById("ajaxContents");
    
    if ( oldData != null )
      oldData.parentNode.removeChild( oldData );

    httpRequest( "get", url, true, showContactInfo_cb );
  }
}

function showContactInfo_cb() {
  if( typeof request == "object" && request.readyState == 4 && targetId != "" )
  {
		var data = request.responseText;

		if( data.length > 0 )
		{
      var div = document.getElementById( targetId );
      var newDiv = document.createElement("div");
      newDiv.setAttribute("id","ajaxContents");
      newDiv.innerHTML = data;
      div.appendChild(newDiv);
    }
  }

  isWorking = false;
}

function hideAjaxPopup() {
  setTimeout( "hide();", 500 );
}

function hide() {
  var div = document.getElementById( 'ajaxPopup' );
  div.style.top = 0;
  div.style.left = 0;
  div.style.width = 0;
  div.style.height = 0;
  div.style.visibility = "hidden";
  div.style.display = "none";

  var oldData = document.getElementById("ajaxContents");

  if ( oldData != null )
    oldData.parentNode.removeChild( oldData );
}

function hideAjaxImagePopup() {
  setTimeout( "hideImage();", 500 );
}

function hideImage() {
  var div = document.getElementById( 'ajaxImagePopup' );
  div.style.visibility = "hidden";
  div.style.display = "none";

  var oldData = document.getElementById("ajaxContents");

  if ( oldData != null )
    oldData.parentNode.removeChild( oldData );
}

function initImageHandler( urlStr, targetDivId ) {
  if ( urlStr.indexOf("?") == -1 )
    urlStr = urlStr + "?";

  imageRequestUrl = urlStr;
  imageTargetId 	= targetDivId;
}

function showImage( id, imageUrl )
{
  if( !isWorking && imageRequestUrl != "" )
  {
    linkId = id;
    isWorking = true;
    var url  = imageRequestUrl + "&image=" + imageUrl;

    var div = document.getElementById( imageTargetId );
    div.style.visibility = "visible";
    div.style.display = "inline";

    var oldData = document.getElementById("ajaxContents");

    if ( oldData != null )
      oldData.parentNode.removeChild( oldData );

    httpRequest( "get", url, true, showImage_cb );
  }
}

function showImage_cb() {
  if( typeof request == "object" && request.readyState == 4 && targetId != "" )
  {
		var data = request.responseText;

		if( data.length > 0 )
		{
      var div = document.getElementById( imageTargetId );
      var newDiv = document.createElement("div");
      newDiv.setAttribute("id","ajaxContents");
      newDiv.innerHTML = data;
      div.appendChild(newDiv);
    }
  }

  isWorking = false;
}

