/*

 (c) 2007 The Company Merchant Limited, All rights reserved.
 
 You are given the right to modify the postcodedisplay.html file for configuring
 display output
 
 No attempt shall be made
 to modify any routine which interfaces with our service for the purposes of gaining
 access to postcode lookups without paying for and using those lookups. Immediate 
 cancellation of service with no refund and possible legal action  will be taken against 
 any such person or organisation attempting to modify the functionality or lookup
 tracking on this system.

*/
var lookupToken="";
var PCCversion=3.0;
var popuplayout="";
var tokenarray=new Object();
var target_x = 10;
var target_y = 10;

url=TCMinstallpath+"/postcodedisplay.html";
var oXmlHttpRes = zXmlHttp.createRequest();

oXmlHttpRes.open("get", url, true);
oXmlHttpRes.onreadystatechange = function () {
  if (oXmlHttpRes.readyState == 4) {
	if (oXmlHttpRes.status == 200) {
		if (oXmlHttpRes.responseText)
		{
		   popuplayout=oXmlHttpRes.responseText;
		}
	}
  }
}
oXmlHttpRes.send(null);

function getElementById_PCC(id)
{
	var obj = null;
	obj = document.getElementById
    ? document.getElementById(id)
    : document.all
      ? document.all[id]
      : document.layers[id];
	return obj;
}


var has_inner = typeof(window.innerWidth) == 'number';
var has_element = document.documentElement && document.documentElement.clientWidth;

var tcmDiv;


var tcm_shift_x, tcm_shift_y, tcm_next_x, tcm_next_y;

function move_tcmbox()
{
    if (document.layers)
    {
        tcmDiv.left = tcm_next_x;
        tcmDiv.top = tcm_next_y;
    }
    else
    {
        tcmDiv.style.left = tcm_next_x + 'px';
        tcmDiv.style.top = tcm_next_y + 'px';
    }
}

function calculate_shift_position()
{
    tcm_shift_x = has_inner
        ? pageXOffset
        : has_element
          ? document.documentElement.scrollLeft
          : document.body.scrollLeft;
    if (target_x < 0)
        tcm_shift_x += has_inner
            ? window.innerWidth
            : has_element
              ? document.documentElement.clientWidth
              : document.body.clientWidth;

    tcm_shift_y = has_inner
        ? pageYOffset
        : has_element
          ? document.documentElement.scrollTop
          : document.body.scrollTop;
    if (target_y < 0)
        tcm_shift_y += has_inner
            ? window.innerHeight
            : has_element
              ? document.documentElement.clientHeight
              : document.body.clientHeight;
}

function float_tcmbox()
{
    var step_x, step_y;

    calculate_shift_position();

    step_x = (tcm_shift_x + target_x - tcm_next_x) * .07;
    if (Math.abs(step_x) < .5)
        step_x = tcm_shift_x + target_x - tcm_next_x;

    step_y = (tcm_shift_y + target_y - tcm_next_y) * .07;
    if (Math.abs(step_y) < .5)
        step_y = tcm_shift_y + target_y - tcm_next_y;

    if (Math.abs(step_x) > 0 ||
        Math.abs(step_y) > 0)
    {
        tcm_next_x += step_x;
        tcm_next_y += step_y;
        move_tcmbox();
    }

    setTimeout('float_tcmbox()', 20);
};

function showPCBox(content,status,funcname,pcid,xpos,ypos)
{
    tcmDiv=getElementById_PCC("TCMPCClookup");

    calculate_shift_position();

	if (document.layers)
	{
		// Netscape 4 cannot perform init move
		// when the page loads.
		tcm_next_x = 0;
		tcm_next_y = 0;
	}
	else
	{
		tcm_next_x = tcm_shift_x + target_x;
		tcm_next_y = tcm_shift_y + target_y;
		move_tcmbox();
	}

   tcmDiv.style.display="block";
   tcmDiv.innerHTML=popuplayout;
   if (status=="startup")
   {
      u=TCMinstallpath+"/postcodecheckwaiting.gif";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.backgroundImage="url(u)";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.height="132px";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.width="300px";
	  
      tcmBodyDiv=getElementById_PCC("TCMbody").innerHTML=content;
      tcmStatusDiv=getElementById_PCC("TCMstatus").innerHTML="Initialising ...";

       if (isNaN(parseInt(xpos)))
 	   {  
		  target_x = 30;
		  target_y = 30;
       }
	   else
	   {
		  target_x = xpos;
		  target_y = ypos;
	   }
	   float_tcmbox();
   }
   else if (status=="retrieve")
   {
      u=TCMinstallpath+"/searching.gif";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.backgroundImage="url(u)";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.height="132px";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.width="300px";
      tcmBodyDiv=getElementById_PCC("TCMbody").innerHTML=content;
      tcmStatusDiv=getElementById_PCC("TCMstatus").innerHTML="Retrieving data ... please wait";
   }
   else if (status=="select")
   {
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.height="132px";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.width="300px";
      tcmBodyBackgroundDiv=getElementById_PCC("TCMbodybackground").style.backgroundImage="";
      
	  funcname='"'+funcname+'"';
	  pcid='"'+pcid+'"';
	  buttoncontent = "<br><div align=right><input type=button id=tcmpostcodebutton name=tcmpostcodebutton value='Select' onclick='TCMgetAddress("+funcname+","+pcid+");'></div>";
	  tcmBodyDiv=getElementById_PCC("TCMbody").innerHTML=content;
	  tcmBodyDiv=getElementById_PCC("TCMbodybutton").innerHTML=buttoncontent;
	  
      tcmStatusDiv=getElementById_PCC("TCMstatus").innerHTML="Done ...";
   }
   else if (status=="complete")
   {
      tcmBodyDiv=getElementById_PCC("TCMbody").innerHTML=content;
      tcmStatusDiv=getElementById_PCC("TCMstatus").innerHTML="Closing ...";
   }

   tcmDiv.style.visibility="visible";
}


function TCMgetAddress(funcname,id)
{
	var selObj = getElementById_PCC('tcmpostcodelookup');
	var selIndex = selObj.selectedIndex;

    RoyalMailID = selObj.options[selIndex].value;

   showPCBox(sResp,"complete",funcname,id);

	
   url=TCMinstallpath+"/proxy."+scripttype+"?action=pcretrieve&address="+RoyalMailID+"&funcname="+funcname+"&outputtype="+outputtype+"&token="+tokenarray[id]+"&uniq="+today.getUTCMilliseconds( );
	
    var oXmlHttpRes = zXmlHttp.createRequest();
	
	oXmlHttpRes.open("get", url, true);
	oXmlHttpRes.onreadystatechange = function () {

      if (oXmlHttpRes.readyState == 4) {
			if (oXmlHttpRes.status == 200) {
				if (oXmlHttpRes.responseText)
				{
				   sResp=oXmlHttpRes.responseText;
				   //aResp=sResp.split("~");
				   if (sResp=="N")
				   {
					   hidePCBox();
				   }
				   else
				   {
					   // call users function
					   hidePCBox();
					   eval(sResp);
				   }
				}
			} 
		}    
	}
	
	oXmlHttpRes.send(null);
    hidePCBox();
}

function hidePCBox()
{
   tcmDiv=getElementById_PCC("TCMPCClookup");
   tcmDiv.style.display="block";
   tcmDiv.style.visibility="hidden";
   tcmDiv.style.display="none";
}
// this function can either be called in the onkeypress event handler
// of the postcode entry box, or the onclick of a lookup button

function ChoosePostcode(id,funcname,accesspoint,xpos,ypos)
{
    var oXmlHttpRes = zXmlHttp.createRequest();
	
	today = new Date( ); 
	pccVal=escape(getElementById_PCC(id).value);
	calledfrom=location.href;

    if (pccVal.length <5) 
	    return;

    showPCBox("","startup",funcname,id,xpos,ypos);

	gotkey=false;				
    for(key in tokenarray) 
    {  
       if (key==id) gotkey=true;
    }					
   
	if (!gotkey)
	{
		getToken(id,accesspoint);
	}

    if (isNaN(parseInt(tokenarray[id])))
	{
		alert("Sorry, there was a problem talking to the postcode database. Please try again in a few minutes.");
        hidePCBox();
        return;
	}
	

    showPCBox("","retrieve",funcname,id,xpos,ypos);

url=TCMinstallpath+"/proxy."+scripttype+"?action=pclookup&outputtype="+outputtype+"&postcode="+pccVal+"&accesspoint="+accesspoint+"&jsver="+PCCversion+"&calledfrom="+encodeURIComponent(calledfrom)+"&token="+tokenarray[id]+"&uniq="+today.getUTCMilliseconds( );
	oXmlHttpRes.open("get", url, true);
	oXmlHttpRes.onreadystatechange = function () {
		if (oXmlHttpRes.readyState == 4) {
			if (oXmlHttpRes.status == 200) {
				if (oXmlHttpRes.responseText)
				{
				   sResp=oXmlHttpRes.responseText;
				   //aResp=sResp.split("~");
				   if (sResp=="N")
				   {
					   hidePCBox();
				   }
				   else
				   {
                       showPCBox(sResp,"select",funcname,id,xpos,ypos);
				   }
				}
			} 
		}    
	}		
	oXmlHttpRes.send(null);
}

function getToken(id,accesspoint)
{
	var oXmlHttpRes = zXmlHttp.createRequest();
	
	today = new Date( ); 
	calledfrom=location.href;

    url=TCMinstallpath+"/proxy."+scripttype+"?action=gettoken&accesspoint="+accesspoint+"&jsver="+PCCversion+"&calledfrom="+encodeURIComponent(calledfrom);
	oXmlHttpRes.open("get", url, false);
	oXmlHttpRes.send(null);
	if (oXmlHttpRes.status == 200) 
	{
		if (oXmlHttpRes.responseText)
		{
		   tokenarray[id] = oXmlHttpRes.responseText;
		   lookupToken=oXmlHttpRes.responseText;
		}
	} 
}

