var isIE, isMozilla, isSafari, isOpera = false;
var theAddressFields = [];

function lookup_postcode(theButton,theForm,thePostcode,myAddressFields,theLabel) {
   var webservice = '/cms/calculator/postcodelookup?';
   var storedButtonValue = theButton.value;  
   myRequest = sendRequest(webservice+'postcode='+thePostcode.value,'','get','','ByPostcode');
   theAddressFields = myAddressFields;
   var theLabelID = theLabel+theForm.id+'MessageLabel';

   setErrorMessage(theLabel,'Postcode: ');

   var myPopUp = document.getElementById("pcaResultContainer");
   if (!myPopUp) {
       myPopUp = document.createElement("div");
       myPopUp.id = "pcaResultContainer";
       myPopUp.className = "pcaResultContainer";
       document.getElementsByTagName("body")[0].appendChild(myPopUp);
   }
   else {
       while (myPopUp.childNodes.length > 0) {
          myPopUp.removeChild(myPopUp.childNodes[myPopUp.childNodes.length - 1]);
       }
   }
   myPopUp.style.display = 'none';
   div1 = document.createElement("div");
   div1.innerHTML ='Searching for address, please wait a moment.';
   div1.className = "pcaResultHeader";
   myPopUp.appendChild(div1);
   showMenuAtElement(document,'pcaResultContainer', thePostcode, 1, 4);
   myPopUp.style.position = 'absolute';
   myPopUp.style.display='block';
   myPopUp.style.zIndex = '99999';

   if (myRequest.readyState == 4) {
      var my_postcodes = myRequest.responseXML.getElementsByTagName("Item");

      while (myPopUp.childNodes.length > 0) {
          myPopUp.removeChild(myPopUp.childNodes[myPopUp.childNodes.length - 1]);
      }

      if ( my_postcodes.length && 
           my_postcodes[0].getAttribute('error_number') && 
           my_postcodes[0].getAttribute('message') ) {
           myPopUp.style.display = 'none';
           setErrorMessage(theLabel,'Lookup failed - please enter a full postcode',document.getElementById(theLabelID)); 
           theButton.value = storedButtonValue;
           return 0;
      }
      if ( my_postcodes.length ) {
         // Create floating div
         
         var img1 = document.createElement("img");
         img1.src = "/global/images/toolbar/minus.gif";
         img1.alt = "close";
         img1.title = "close";
         img1.className = "lookupImgClose";
         img1.onclick = Function("document.getElementById('"+theButton.id+"').value = '"+storedButtonValue+"';document.getElementById('pcaResultContainer').style.display = 'none';");

         div1 = document.createElement("div");
         div1.appendChild(img1);
         
         text1 = document.createTextNode('Please choose an address from the list.');
         div1.appendChild(text1);
         div1.className = "pcaResultHeader";
         myPopUp.appendChild(div1);
         div1 = document.createElement("div");
         div1.id = 'pcaResult';
         div1.className = 'pcaResult';
         myPopUp.appendChild(div1);
         for (i = 0; i < my_postcodes.length; i++) {
            addLookUpItem(div1,
                        'pca_'+i,
                        '#pca',
                        my_postcodes[i].getAttribute('description'),
                        '',
                        myPopUp.style.width,
                        Function("fetchAddress('"+theForm.id+"','"+my_postcodes[i].getAttribute('id')+"');") );
         }
         showMenuAtElement(document,'pcaResultContainer', thePostcode, 1, 4);
         myPopUp.style.position = 'absolute';
         myPopUp.style.display='block';
         myPopUp.style.zIndex = '99999';
         theButton.value = storedButtonValue;
         return 1;
      }
      else {
         document.getElementById('pcaResultContainer').style.display = 'none';
         setErrorMessage(theLabel,'Lookup failed - please enter a full valid postcode.',document.getElementById(theLabelID));
      }
   }
}

function addLookUpItem(myPopUp, id, href, title, menuclassName, width, onclick) {
    if ( !menuclassName ) {
       menuclassName = 'popupItem';
    }
    containerDiv = document.createElement("div");

    containerDiv.setAttribute("style", "position:relative;float:left;clear:both;width:97%;height:auto;display:block;vertical-align:middle;margin:0px;padding:0px;");

    myPopUp.appendChild(containerDiv);

    span1 = document.createElement("span");

    if ( isIE ) {
       span1.setAttribute("style","width:96%;height:auto;position:relative;float:left;margin:0px;padding:0px;cursor:pointer;display:block;");
    }
    else {
       span1.setAttribute("style","width:100%;height:auto;position:relative;float:left;margin:0px;padding:0px;cursor:pointer;display:block;");
    }
    anchor1 = document.createElement("a");
    anchor1.setAttribute("href", href);
    anchor1.id = id;
    text1 = document.createTextNode(title);
    anchor1.className = 'popupItem';
           if ( isIE ) {
              anchor1.style.width = '100%';
           }
           else {
              anchor1.style.width = '96%';
           }

    if ( onclick ) {
       anchor1.onclick = onclick;
    }

    anchor1.appendChild(text1);
    span1.appendChild(anchor1);
    containerDiv.appendChild(span1);
}

function getXMLHTTPObject(){
    //instantiate new XMLHTTP object
    var objhttp=(window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
    if(!objhttp){return};
    // assign event handler
    
    if (navigator.userAgent.indexOf('MSIE') != -1)
        isIE = true;
    else if (navigator.userAgent.indexOf('Safari') != -1)
        isSafari = true;
    else if (navigator.userAgent.indexOf('Opera') != -1)
        isOpera = true;
    else
        isMozilla = true;

    return objhttp;
};

// function sendRequest
function sendRequest(url,data,method,header,calltype){
    // get XMLHTTP object
    objhttp=getXMLHTTPObject();
    //alert('KMG '+objhttp);
    
    if ( !isIE ) { 
       objhttp.onreadystatechange = processReqChange(objhttp,calltype);
    }
 
    // set default values
    if(!url){url='/cms/calculator/auth'};
    if(!data){data=''}; 
    if(!method){method='get'};
    if(!header){header='Content-Type:text/html; charset=iso-8859-1'};
    // open socket connection in asyncronous mode
    objhttp.open(method,url,false);
    // send header
    objhttp.setRequestHeader(header.split(':')[0],header.split(':')[1]);
    // send data
    objhttp.send(null);
    // return xmlhttp object
    return objhttp;
};

function processReqChange(req,calltype) {
    // only if req shows "loaded"
    if (req.readyState == 4) {

    }
};

function fetchAddress(theFormID,theID) {
   var webservice = '/cms/calculator/postcodelookup?';

   myRequest = sendRequest(webservice+'id='+theID,'','get','','fetch');

   if (myRequest.readyState == 4) {
      var my_address = myRequest.responseXML.getElementsByTagName("Item");
      //alert(my_address);
      if (my_address.length && my_address.length == 1) {
         if ( theAddressFields[0] ) {
            if ( my_address[0].getAttribute('line1') ) {
               theAddressFields[0].value = my_address[0].getAttribute('line1');
            }
            else {
               theAddressFields[0].value = ''; 
            }
         }
         if ( theAddressFields[1] ) {
            if ( my_address[0].getAttribute('line2') ) {
               theAddressFields[1].value = my_address[0].getAttribute('line2');
               if ( my_address[0].getAttribute('line3') ) {
                  theAddressFields[1].value = theAddressFields[1].value+','+my_address[0].getAttribute('line3');
               }
               if ( my_address[0].getAttribute('line4') ) {
                  theAddressFields[1].value = theAddressFields[1].value+','+my_address[0].getAttribute('line4');
               }
            }
            else {
               theAddressFields[1].value = '';
            }

         }
         if ( theAddressFields[2] ) {
            if ( my_address[0].getAttribute('post_town') ) {
               theAddressFields[2].value = my_address[0].getAttribute('post_town');
            }
            else {
               theAddressFields[2].value = '';
            }
         }
         if ( theAddressFields[3] ) {
            if ( my_address[0].getAttribute('county') ) {
               theAddressFields[3].value = my_address[0].getAttribute('county');
            }
            else {
               theAddressFields[3].value = '';
            }
         }
         if ( theAddressFields[4] ) {
            if ( my_address[0].getAttribute('postcode') ) {
               theAddressFields[4].value = my_address[0].getAttribute('postcode');
            }
            else {
               theAddressFields[4].value = '';
            }
         }


      }
   }
   document.getElementById("pcaResultContainer").style.display = 'none';
}


function clearErrorMessage(labelID,theLabel) {
   if ( theLabel ) {
      theLabel.innerHTML = '';
   }

   if ( labelID ) {
      var messageLabelID = labelID+'MessageLabel';
      if ( document.getElementById(messageLabelID) ) {
        document.getElementById(messageLabelID).innerHTML = '';
      }
   }
        // Generic message to point out quote submission failed
        if ( document.getElementById('quoteStatusMessage') ) {
             document.getElementById('quoteStatusMessage').innerHTML = mySpacer;
        }
}

function setErrorMessage(labelID,message,theLabel,warningOnly) {
   if ( labelID && message) {
      var messageLabelID = labelID+'MessageLabel';
      if ( theLabel || document.getElementById(messageLabelID) ) {
        if ( theLabel ) {
           theLabel.innerHTML = message;
        }
        else {
           document.getElementById(messageLabelID).innerHTML = message;
        }
        // Generic message to point out quote submission failed
        if ( document.getElementById('quoteStatusMessage') && !warningOnly) {
             document.getElementById('quoteStatusMessage').innerHTML = 'There were errors in the information provided, please review the page and re-submit where appropriate to obtain an accurate '+calcType+'.';
        }
      }

      else {
        alert('Did not find object with ID '+messageLabelID);
      }
   }
}


function showMenuAtElement(d,popup, el, addOffSet,moveUp) {
  var p = getAbsolutePos(el);
  var y_coord = p.y + el.offsetHeight+2;
  if ( addOffSet == 0 ) {
     y_coord = p.y;
  }
  var x_coord = p.x+1;
  if ( moveUp) {
     y_coord = y_coord+moveUp;
  }
  showPopUpAt(d, popup, el,x_coord, y_coord);
}
