<!-- Javascript for general use throughout the ASPC site -->

// For pages that belong in a frameset.  Check that we're in one,
// and if not, re-direct to the front page, or (maybe some day)
// something else that will put us into an appropriate frameset.



function forceIntoFrame() {
  if (parent.location.href == self.location.href){
    window.location.href = 'http://www.aspc.co.uk/ASPC/index.html'
  }
}


// New generic popup function.

var parentFrameOther;
var aspcPopupWindows;

var popupParams = [];

popupParams["aspcleaflet"]        = 'width=700,height=500,resizable=yes,scrollbars=no';
popupParams["aspcleaflettext"]    = 'width=400,height=300,resizable=yes,scrollbars=yes';
popupParams["aspcleaflettextbig"] = 'width=600,height=550,resizable=yes,scrollbars=yes';
popupParams["aspchelp"]           = 'width=280,height=300,resizable=yes,scrollbars=yes';
popupParams["aspchelptall"]       = 'width=280,height=545,resizable=yes,scrollbars=yes';
popupParams["myaspchelp"]         = 'width=400,height=480,resizable=yes,scrollbars=yes';
popupParams["aspcproperty"]       = 'width=750,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes';
popupParams["homecard"]           = 'width=600,height=600,resizable=yes,scrollbars=yes';
popupParams["register"]           = 'width=400,height=350,resizable=yes,scrollbars=yes';
popupParams["soldetails"]         = 'width=450,height=500,resizable=yes,scrollbars=yes';
popupParams["external"]           = 'width=700,height=500,resizable=yes,scrollbars=yes';
popupParams["homebuilders"]       = popupParams["external"];
popupParams["myaspcSession"]      = 'width=700,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes';
popupParams["myaspcAdmin"]        = 'width=700,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes';
popupParams["myaspcAdminExtra"]   = 'width=700,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes';
// David: lets try adding parameters for gallerys, tours and location maps
//popupParams["gallery"]            = 'width=750,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,screenx=25,screeny=25';
popupParams["Gallery"]            = 'width=750,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,screenx=25,screeny=25';
popupParams["tour"]               = 'width=750,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,screenx=25,screeny=25';
popupParams["LocationMaps"]       = 'width=770,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,screenx=25,screeny=25';
popupParams["homereport"]         = 'width=770,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,screenx=25,screeny=25';
popupParams["floorplan"]         = 'width=770,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,screenx=25,screeny=25';

// This is revamp
popupParams["aspcsearch"]         = 'width=1000,height=700,menubar=yes,resizable=yes,scrollbars=yes,status=yes,location=yes';

// If anything is specified, make sure *all* features are on.
// No params gives us the default size for the user with all features on.
popupParams["aspcmain"]           = '';

// Note this is shared, so for 200ms another call to this function in
// this window will effectively cancel the focus on the previous one.

var popupWin;

function aspcpopup(link, params)
{
  return aspcpopup_int(link.target, link.href, params);
}


function find_popup(type)
{
  // try and find the the relevant pop-up window
  if (parentFrameOther != null && aspcPopupWindows == null)
    aspcPopupWindows = [];
  else if (parent.aspcPopupWindows == null)
    parent.aspcPopupWindows = [];

  var popupWin = parentFrameOther != null? 
    aspcPopupWindows[type] : 
    parent.aspcPopupWindows[type];

  return popupWin && !popupWin.closed? popupWin : null;
}

  /* Need to modify this so:
  - if the window already exists, leave it where it is, else
  - check for a cookie showing the user's preferred position 
    for windows of that type, and 
  - if there is one, it open the window in the relevant place.
  - if there is no position cookie, behave as now
    (i.e. leave the OS to choose the position).
 
  */
function aspcpopup_int_new(type, url, params)
{
  var popupWin = find_popup(type);
  
  if (popupWin)
  { // the popup window already exists
    if (url != null)
      popupWin.location.href = url;
  } 
  else
  { // we need to open a new popup
   

    // append the default popup params for the requested 
    // window type to params
    var defaults = popupParams[type]; 
    if (defaults==null)
      alert("Don't understand window type '"+type+"'");


    // does the user have a preferred window geometry for this type?
    var pos = GeometryIndex.retrieve(type);

    // combine the three sets of paramters into one
    var merged = GeometryAdapter.mergeParams(defaults, pos, params);
    
    popupWin = window.open( url==null? "/blank.html" : url, 
                            type, 
                            merged );
// Hack for IE: we try to reposition the window after opening, using apply(),
// as IE's window.open() uses different coords (yet again) and doesn't quite
// get the position right.
//
// ..and we have to initialise GeometryAdapter *after* the document has loaded.
// ..and this STILL doesn't work, because the onload property seems to get wiped, 
// So ... er I've shelved this hack pending a solution which works.
//    if (params == null && pos)
//    {
//      popupWin.onload = function() { 
//              alert("here");
//        var wingeom = new GeometryAdapter(popupWin);
//        pos.apply(wingeom); 
//      };
//    }

    // keep track of this pop-up
    if (parentFrameOther != null)
      aspcPopupWindows[type] = popupWin;
    else
      parent.aspcPopupWindows[type] = popupWin;
  }

  // Put focus on the new window via a timeout (which is required to
  // ensure the window has actually been created before it is given
  // focus, otherwise disaster ensues).
  setTimeout(function(){popupWin.focus()}, 500);
  
  return false;
}


/* Save the dimensions of a popup window in a cookie as the default for popups 
   of type 'type' */
function aspcpopup_save(type, popup)
{
  if (!popup)
  {
    popup = find_popup(type);
    if (popup ==  null) return alert("Can't find popup window for "+type);
  }
  GeometryIndex.saveWindow(type, popup);
}

function aspcpopup_int(type, url, params)
{
  var defaults = popupParams[type];
  var ps = [];

  if (params != null)
    ps[ps.length] = params;

  if (defaults==null)
    alert("Don't understand window type '"+type+"'");
  else
    ps[ps.length] = defaults;

  params = ps.join(",");

  if (parentFrameOther != null && aspcPopupWindows == null)
      aspcPopupWindows= [];
  else if (parent.aspcPopupWindows == null)
      parent.aspcPopupWindows = [];

  popupWin = parentFrameOther!=null?aspcPopupWindows[type]:parent.aspcPopupWindows[type];

  if (popupWin != null && !popupWin.closed)
      { 
	  if (url != null)
	      popupWin.location.href=url;
      }
  else
      {
	  popupWin = window.open(url==null?"/blank.html":url, type, params);

	  if (parentFrameOther!=null)
	      aspcPopupWindows[type] = popupWin;
	  else
	      parent.aspcPopupWindows[type] = popupWin;
      }

  setTimeout('popupWin.focus();', 500);

  return false;
}





function aspcMainOrPopup (link, params)
{
    if (opener != null && opener.top != null && opener.top.aspcsite != null) {
	// alert (link.href + " " + opener.top.aspcsite);
	opener.top.aspcsite.document.location = link.href;
	// Original window seems to lose opener after this.
	return false;
    } else {
	// alert ("popup");
	return aspcpopup_int(link.target, link.href, params);
    }
}



// Stuff for popping particulars up in a standard window
// and focusing it to expose it


function opendescwin(params) {

  aspcpopup_int("aspcproperty", null, params);

  return(true);
}

// And the same for help...

function openhelpwin(params) {alert("old help function called!");}

function helpDisplay(url, params) {alert("Still using helpDisplay!");}

// And for search registration

function registerwin (params)
{

    if (parent.left.criteria_changed) {
	if ( !confirm("Warning!\nYou are about to register the last search that you ran -- the one that produced the results you have seen.  If you have changed the search options and you want to register a search based on the current settings, you should cancel this operation, run the search, and then start to register again\n\nDo you want to proceed to register the last search you ran?"))
	{ return(false) }
    }

    aspcpopup_int("myaspcSession", "/blank.html", params);

    return true;
}

// and for myaspc

function myaspcwin (params) {
    aspcpopup_int ("myaspcSession", null, params);

    return (true);
}

// And let's have a registration button...

function regbutton()
{
    document.write('<font size="2" face="verdana, arial, sans-serif" color="white"><a class="inHeading" href="Save Search" onClick="return(form_submit())"><b>Save Search &nbsp;</A></font></a>');
}

// Close button

var redirect_them = true;   // Redirect them to front page if true

function writeclosebutton(closebutton) {
    var cbutton = closebutton;
    if ( window.name.search(/^[0-9]+$/) >= 0) {
      // If we have a window name which is a number then record the fact (cf home.co.uk)
       var now = new Date;
       var rightnow = now.getTime();
       var info = "closewindow.gif?WNAME=" + window.name + "&TIME=" + rightnow;
       cbutton = closebutton.replace(/closewindow.gif/, info);
       if( redirect_them && ( rightnow - window.name < 100000 ) ){
	 // If the number is within 100 seconds of now, then redirect back to front page
	 window.location.href = 'http://www.aspc.co.uk';
       }
    }
    document.write(cbutton);
}

// Window status for links
function windowStatus (message)
{
    window.status = message;
    return true;
}

///
// Stuff to do with the search form

function search_form_frame_is()
{
    return parent.right;	
}

function remember_search_form()
{
    var search_form_frame = search_form_frame_is();

    if (search_form_showing()) {
	parent.remember_forms(search_form_frame.document);
    }
}

function remember_double_form()
{
    parent.remember_forms(document);
    remember_search_form();
}


/////////////////////
// Shuffling headers and the like

function loadLHeader (f)
{
    if (parent.leftheader &&
        parent.leftheader.location.pathname != f) {
        parent.leftheader.location.href = f;
    }
}

// Modified by David to fix GNATS bug 198 ( sniffer got interrupted by doing a non-map search)

function loadRHeader (f) {
  if (parent.rightheader &&
      parent.rightheader.location.pathname != f) {
    //alert("loadRHeader (aspc.js) is changing right header: pathname = '"+
    //	  parent.rightheader.location.pathname+"'");
    if(  parent.rightheader.location.pathname.match(/snifferheader.html/) ||
	 ( parent.rightheader.location.pathname.match(/snifferheader2.html/) &&
	   parent.map_search_allowed == null )
	 ){
      // Right frame currently contains the sniffer, and its not finished
      // Try again in a while
      setTimeout("loadRHeader(\""+f+"\");",100);
    } else {
      parent.rightheader.location.href = f;
    }
  }
}

function loadMyHeader (f) 
{
         if (window.name.match(/right/)) { loadRHeader(f); }
    else if (window.name.match(/right/)) { loadLHeader(f); }
    else { alert("HELP! Can't identify my header!"); }
}

function checkNumeric(n) {
    if (n.match(/^\d{5,6}$/)) {
        return(true);
    }
    else {
	alert("Enter ASPC's 5- or 6-digit property ID for the property you wish to see.");
	return(false);
    }
}


// Some functions to stretch things to suitable widths.
// Most used in the RH frame, which is of variable width

var winW = 350, winH = 450;   // Conservative defaults

var textW = 320;  // How wide should we make text?
var linW = 320;   // How wide should we make lines?

if (parseInt(navigator.appVersion)>3) { // Try to get the real values
 if (navigator.appName=="Netscape" || navigator.appName.indexOf("Opera")!=-1) {
  winW = window.innerWidth;
  winH = window.innerHeight;
 }
 if (navigator.appName.indexOf("Microsoft")!=-1 && document != null && document.body != null) {
  winW = document.body.offsetWidth;
  winH = document.body.offsetHeight;
 }
}

if (winW > 350) {
    if (winW > 550) {
       textW="500";
       linW="500";
    }
    else {
       textW=Math.floor(winW*0.9);
       linW=Math.floor(winW*0.9);
    }
}


// Header for a "full width" table

function tablehead(border)
{
    if (!border) {
        border = 0;
    }

    document.write('<table width="' + textW + '" cellspacing="0" cellpadding="0" border="' + border + '">');
}

// functions to handle interlocking within property selectors
// on the search forms

var criteria_changed = 1;

function change_criterion() {
    parent.left.criteria_changed = 1;
}

function criteria_good() {
    parent.left.criteria_changed = 0;
}


function clickedflat() {
    var form = document.forms[0];
    var enabled = form.DwellingTypeFlat.checked;
    var val = !enabled;
    form.DwellingLevelBasement.disabled = val;
    form.DwellingLevelGround.disabled = val;
    form.DwellingLevelFirst.disabled = val;
    form.DwellingLevelSecond.disabled = val;
    form.DwellingLevelThird.disabled = val;
    form.DwellingLevelTop.disabled = val;
    change_criterion();
}

function clickedhouse() {
    var form = document.forms[0];
    var enabled = form.DwellingTypeDetached.checked || form.DwellingTypeNonDetached.checked;
    var val = !enabled;
    form.DwellingLevelMultiple.disabled = val;
    form.DwellingLevelSingle.disabled = val;
    change_criterion();

}

//// Check for good address words

var valid_char_regexp = new RegExp ("[-A-Za-z0-9'*]");

function validateAddressWords (form, what)
{
    var addrWords = form.AddressPlus.value;



    // Check for at least some word characters...

    if (! addrWords.match(valid_char_regexp)) {
	alert ("You must enter at least one word that should appear in the address of the " + what);
	return (false);
    }

    // Check for bad wildcard patterns...

    if (addrWords.match(/\*/)) {    
	if (addrWords.match(/\*\S/) ||
	       addrWords.match(/^[-A-Za-z0-9']{0,2}\*/) ||
	       addrWords.match(/\s[-A-Za-z0-9']{0,2}\*/)) {
	    alert ("Wildcards are allowed only at the end of a prefix at least 3 letters long");
	    return(false);
	}
    }

    return(true);
}


////////////////////////////////////////////////////////////////////////
// Reference requests for ASPC properties
// 
// If it has the right form for an ASPC reference, we
// create the window for it.
// Inside the centre, we also consider HomeCards...

function handleRefRequest(formField, bgcol) {
    var ID = formField.value;
    if (ID.match(/^\d{5,6}$/)) { // It is a plausible ASPC reference
	aspcpopup_int("aspcproperty", null, null);
        return(true);
    }
    else {
	alert("You must enter ASPC's 5- or 6-digit property ID for the property you wish to see.");
	return(false);
    }
}

////////////////////////////////////////////////////////////////////////
// Inside ASPC, we provide access to the contents of a HomeCard...
//
// What looks like a HomeCard ID?
function basketRef(ID) {
   return(ID.match(/^[0-9A-F]{8,10}$/));
}

function showBasket(ID, bgcol) {
    alert("HomeCards are not supported outside ASPC Chapel Street");
}






// what we know about web browsers

var reasonableAgents = [];
var problematicAgents = [];
var brokenAgents = [];

// problematicAgents["Safari"] = [ "Safari", "safari sometimes locks up" ];

brokenAgents["Mac_"] = "macie";

