/**********************************************************************
   Page load
 *********************************************************************/

function doPageLoad() {
   rolloverInit();
   preloadGlobalImages();
   //setTimeout('setColumnHeights()', 100);
}


/**********************************************************************
   Image rollovers
 *********************************************************************/

function isDefined(property) {
  return (typeof property != 'undefined');
}

var rolloverInitialized = false;
function rolloverInit() {
   if (!rolloverInitialized && isDefined(document.images)) {
      
      // get all images (including all <input type="image">s)
      // use getElementsByTagName() if supported
      var images = new Array();
      if (isDefined(document.getElementsByTagName)) {
         images = document.getElementsByTagName('img');
         var inputs = document.getElementsByTagName('input');
         for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == 'image') {
               images[images.length] = inputs[i];
            }
         }
      }
      
      // otherwise, use document.images and document.forms collections
      // remove if not supporting IE4, Opera 4-5
      else {
         images = document.images;
         inputs = new Array();
         for (var formIndex = 0; formIndex < document.forms.length; formIndex++) {
            for (var elementIndex = 0; elementIndex < document.forms.elements.length; elementIndex++) {
               if (isDefined(document.forms.elements[i].src)) {
                  inputs[inputs.length] = document.forms.elements[i];
               }
            }
         }
      }
      
      // get all images with '_off.' in src value
      for (var i = 0; i < images.length; i++) {
         if (images[i].src.indexOf('_off.') != -1) {
            var image = images[i];
            
            // store the off state filename in a property of the image object
            image.offImage = new Image();
            image.offImage.src = image.src;
            
            // store the on state filename in a property of the image object
            // (also preloads the on state image)
            image.onImage = new Image();
            image.onImage.imageElement = image;
            
            // add onmouseover and onmouseout event handlers once the on state image has loaded
            // Safari's onload is screwed up for off-screen images; temporary fix
            if (navigator.userAgent.toLowerCase().indexOf('safari') != - 1) {
               image.onmouseover = function() {
                  this.src = this.onImage.src;
               };
               image.onmouseout = function() {
                  this.src = this.offImage.src;
               };
            }
            else {
               image.onImage.onload = function() {
                  this.imageElement.onmouseover = function() {
                     this.src = this.onImage.src;
                  };
                  this.imageElement.onmouseout = function() {
                     this.src = this.offImage.src;
                  };
               };
            }
            
            // set src of on state image after defining onload event handler
            // so cached images (that load instantly in IE) will trigger onload
            image.onImage.src = image.src.replace(/_off\./, '_over.');
         }
      }
   }
   rolloverInitialized = true;
}


/**********************************************************************
   Preload Images
 *********************************************************************/

function preloadGlobalImages() {
   var imageURLs = [];
   for (var imageIndex = 0; imageIndex < imageURLs.length; imageIndex++) {
      (new Image()).src = imageURLs[imageIndex];
   }
}


/**********************************************************************
   Make all columns the same height
 *********************************************************************/

function setColumnHeights() {
   
   // column references
   var left = document.getElementById('listingDetail');
   var right = document.getElementById('listingPics');
   
   // reset all heights to auto (needed when calling this function after swapping content)
   if (left) {
      left.style.height = 'auto';
   }
   right.style.height = 'auto';

   // find longest column
   if (left) {
      var leftHeight = left.offsetHeight;  // + (leftCallOut ? leftCallOut.offsetHeight : 0);
   }
   var rightHeight = right.offsetHeight;  // + (rightCallOut ? rightCallOut.offsetHeight : 0);
   var longestColumnLength = rightHeight;
   if (leftHeight > rightHeight) {
      longestColumnLength = leftHeight;
   }
   
   // set all columns to the height of the longest one
   if (left) {
      left.style.height = longestColumnLength + 'px';
   }
   right.style.height = longestColumnLength + 'px';
}


/**********************************************************************
   Content swapper
 *********************************************************************/

var currentContent;

function initContentSwapper() {
   var imageURLs = [];
   for (var argumentIndex = 0; argumentIndex < initContentSwapper.arguments.length; argumentIndex++) {
      var argument = initContentSwapper.arguments[argumentIndex];
      var linkId = argument.linkId;
      var contentId = argument.contentId;
      
      // attach event handlers to links that show related content
      var linkElement = document.getElementById(linkId);
      linkElement.content = document.getElementById(contentId);
      linkElement.onclick = function() {
         if (currentContent && currentContent != this.content) {
            currentContent.style.display = 'none';
         }
         this.content.style.display = 'block';
         currentContent = this.content;
         
         // fix column heights
         setColumnHeights();
         
         // prevent link from being followed
         return false;
      };
      
      if (argumentIndex == 0) {
         currentContent = document.getElementById(contentId);
      }
   }
   
   var contentToShow = query['content'];
   if (contentToShow && document.getElementById(contentToShow)) {
      setTimeout("swapContent(query['content'])", 100);
   }
}

function swapContent(id) {
   
   // get reference to content to show
   var contentToShow = document.getElementById(id);

   // swap content
   if (currentContent && currentContent != contentToShow) {
      currentContent.style.display = 'none';
   }
   contentToShow.style.display = 'block';
   currentContent = contentToShow;
   
   // fix column heights
   setColumnHeights();
   
   // prevent link from being followed
   return false;
}


/**********************************************************************
   Store name/value pairs from query string as an array
 *********************************************************************/

function getSearchAsArray() {
   var searchQuery = new Array;
   var pair;
   var temp;
   var search = location.search;
   
   // replace all '+'s with ' 's because unescape() doesn't do it
   search = search.replace(/\+/g, ' ');
   
   // for each pair, separate, unescape and place into the associate array
   var split = 1;
   while (split > 0) {
      split = search.lastIndexOf('&');
      if (split == -1) split = 0;
      pair = search.substring(split + 1, search.length);
      
      // multiple select values should be placed in an array
      if (searchQuery[unescape(pair.substring(0, pair.indexOf('=')))] != null) {
         temp = searchQuery[unescape(pair.substring(0, pair.indexOf('=')))];
         searchQuery[unescape(pair.substring(0, pair.indexOf('=')))] = new Array(temp, unescape(pair.substring(pair.indexOf('=') + 1)));
      }
      
      // all other form elements have a one-to-one name and value relationship
      else searchQuery[unescape(pair.substring(0, pair.indexOf('=')))] = unescape(pair.substring(pair.indexOf('=') + 1));
      
      search = search.substring(0, split);
   }
   return searchQuery;
}
var query = getSearchAsArray();


/******************************************************************************
	Adding event listeners
 *****************************************************************************/

function addEventListenerToElement(element, eventType, functionValue, capture) {
	if (element.addEventListener) element.addEventListener(eventType, functionValue, capture);
	else if (element.attachEvent) element.attachEvent("on" + eventType, functionValue);
   else {
      if (!element['on' + eventType]) {
         element['on' + eventType] = function(e) {
            if (!e) e = event;
            var functionArray = eval('this.' + e.type + 'Handler');
            for (var index = 0; index < functionArray.length; index++) {
               if (functionArray[index] != null) {
                  functionArray[index](e);
               }
            }
         };
         element[eventType + 'Handler'] = new Array();
         // element[eventType + 'Handler'].element = this;
      }
      var index = 0;
      while (element[eventType + 'Handler'][index] != null) {
         index++;
      }
      element[eventType + 'Handler'][index] = functionValue;
   }
}

function addEventListenerToDescendants(element, eventType, functionValue, capture) {
   addEventListenerToElement(element, eventType, functionValue, capture);
   var childNodes = element.childNodes;
   for (var childIndex = 0; childIndex < childNodes.length; childIndex++) {
      var childNode = childNodes[childIndex]
      if (childNode.nodeType == 1) {
         addEventListenerToDescendants(childNode, eventType, functionValue, capture);
      }
   }
}


/**********************************************************************
   Cleaning the DOM (for Mozilla)
   (see http://www.codingforums.com/showthread.php?t=7028)
 *********************************************************************/

var notWhitespace = /\S/;

function cleanWhitespace(node) {
   for (var x = 0; x < node.childNodes.length; x++) {
      var childNode = node.childNodes[x];
      
      // remove any whitespace text nodes
      if ( childNode.nodeType == 3 && !notWhitespace.test(childNode.nodeValue) ) {
         node.removeChild(node.childNodes[x]);
         x--;
      }
      
      // recurse thru any element nodes removing whitespace
      if (childNode.nodeType == 1) {
         cleanWhitespace(childNode);
      }
   }
}

// zebra striped tables

  // this function is needed to work around 
  // a bug in IE related to element attributes
  function hasClass(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
  }   

 function stripe(id) {

    // the flag we'll use to keep track of 
    // whether the current row is odd or even
    var even = false;
  
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#fff";
    var oddColor = arguments[2] ? arguments[2] : "#eee";
  
    // obtain a reference to the desired table
    // if no such table exists, abort
    var table = document.getElementById(id);
    if (! table) { return; }
    
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // &lt;tbody&gt;s 
    var tbodies = table.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
    
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

        // avoid rows that have a class attribute
        // or backgroundColor style
        if (! hasClass(trs[i]) &&
            ! trs[i].style.backgroundColor) {
 		  
          // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
        
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {
        
            var mytd = tds[j];

            // avoid cells that have a class attribute
            // or backgroundColor style
            if (! hasClass(mytd) &&
                ! mytd.style.backgroundColor) {
        
              mytd.style.backgroundColor =
                even ? evenColor : oddColor;
            
            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
  }
  
  // Window opener functions  v1.0.6
// documentation: http://www.dithered.com/javascript/window/index.html
// license: http://creativecommons.org/licenses/by/1.0/
// code by Chris Nott (chris[at]dithered[dot]com)


/*******************************************************************************
   Popup Window openers
*******************************************************************************/

var winReference = null;


// Open a window at a given position on the screen
function openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName) {
   
   // ie 4.5 and 5.0 mac - windows are 2 pixels too short; if a statusbar is used, the window will be an additional 15 pixels short
   var agent = navigator.userAgent.toLowerCase();
   if (agent.indexOf("mac") != -1 && agent.indexOf("msie") != -1 && (agent.indexOf("msie 4") != -1 || agent.indexOf("msie 5.0") != -1) ) {
      height += (status) ? 17 : 2;
   }

   // Adjust width if scrollbars are used (pc places scrollbars inside the content area; mac outside) 
   width += (scrollbars != '' && scrollbars != null && agent.indexOf("mac") == -1) ? 16 : 0;

   var properties = 'width=' + width + ',height=' + height + ',screenX=' + x + ',screenY=' + y + ',left=' + x + ',top=' + y + ((status) ? ',status' : '') + ',scrollbars' + ((scrollbars) ? '' : '=no') + ((moreProperties) ? ',' + moreProperties : '');
   var reference = openWindow(url, name, properties, openerName);
   
   // resize window in ie if we can resize in ns; very messy
   // commented out because openPositionedWindow() doesn't set the resizable attribute
   // left in for reference
   /*if (resizable && agent.indexOf("msie") != -1) {
      if (agent.indexOf("mac") != -1) {
         height += (status) ? 15 : 2;
         if (parseFloat(navigator.appVersion) > 5) width -= 11;
      }
      else {
         height += (status) ? 49 : 31;
         width += 13;
      }
      setTimeout('if (reference != null && !reference.closed) reference.resizeTo(' + width + ',' + height + ');', 150);
   }*/

   return reference;
}


// Open a window at the center of the screen
function openCenteredWindow(url, name, width, height, status, scrollbars, moreProperties, openerName) {
   var x, y = 0;
   if (screen) {
      x = (screen.availWidth - width) / 2;
      y = (screen.availHeight - height) / 2;
   }
   if (!status) status = '';
   if (!openerName) openerName = '';
   var reference = openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName);
   return reference;
}   


// Open a window at the center of the parent window
function openCenteredOnOpenerWindow(url, name, width, height, status, scrollbars, moreProperties, openerName) {
   var centerX = 0;
   var centerY = 0;
   if (window.screenX != null && window.outerWidth) {
      centerX = window.screenX + (window.outerWidth / 2);
      centerY = window.screenY + (window.outerHeight / 2);
   }
   else if (window.screenLeft) {
      if (document.documentElement) {
         centerX = window.screenLeft + (document.documentElement.offsetWidth / 2);
         centerY = window.screenTop + (document.documentElement.offsetHeight / 2);
      }
      else if (document.body && document.body.offsetWidth) {
         centerX = window.screenLeft + (document.body.offsetWidth / 2);
         centerY = window.screenTop + (document.body.offsetHeight / 2);
      }
   }
   
   if (centerX == 0) {
      openCenteredWindow(url, name, width, height, status, scrollbars, moreProperties, openerName);
   }
   var x = parseInt(centerX - (width / 2));
   var y = parseInt(centerY - (height / 2));
   if (!status) status = '';
   if (!openerName) openerName = '';
   var reference = openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName);
   return reference;
}   


// Open a full-screen window (different from IE's fullscreen option)
function openMaxedWindow(url, name, scrollbars, openerName) {
   var x, y = 0;
   var width  = 600;
   var height = 800;
   if (screen) {
      if (screen.availLeft) {
         x = screen.availLeft;
         y = screen.availTop;
      }
      width  = screen.availWidth - 6;
      height = screen.availHeight - 29;
   }
   var reference = openPositionedWindow(url, name, width, height, x, y, false, scrollbars, openerName);
   return reference;
}


// Open a full-chrome (all GUI elements) window
// This is like using a target="_blank" in a normal link but allows focussing the window
function openFullChromeWindow(url, name, openerName) {
   return openWindow(url, name, 'directories,location,menubar,resizable,scrollbars,status,toolbar');
}


// Open a sized full-chrome (all GUI elements) window 
function openSizedFullChromeWindow(url, name, width, height, openerName) {
   return openCenteredWindow(url, name, width, height, true, true, 'directories,location,menubar,resizable,toolbar', openerName)
}


// Core utility function that actually creates the window and gives focus to it
function openWindow(url, name, properties, openerName) {

   // ie4.x pc can't give focus to windows containing documents from a different domain
   // in this case, initially load a local interstisial page to allow focussing before loading final url
   var agent = navigator.userAgent.toLowerCase();
   if (agent.indexOf("msie") != -1 && parseInt(navigator.appVersion) == 4 && agent.indexOf("msie 5") == -1 && agent.indexOf("msie5") == -1 && agent.indexOf("win") != -1 && url.indexOf('http://') == 0) {
      winReference = window.open('about:blank', name, properties);
      
      setTimeout('if (winReference && !winReference.closed) winReference.location.replace("' + url + '")', 300);
   }
   else {
      winReference = window.open(url, name, properties);
   }

   // ie doesn't like giving focus immediately (to new window in 4.5 on mac; to existing ones in 5 on pc)
   setTimeout('if (winReference && !winReference.closed) winReference.focus()', 200);
   
   if (openerName) self.name = openerName;
   return winReference;
}


/*******************************************************************************
   Modal Dialog controls
*******************************************************************************/

// Close a dialog
// Call from onunload event handler of any page that can create a dialog
function closeDialog(dialog) {
   if (dialog && dialog.closed != true) dialog.close();
}


// Close parent popup
// Call from onload event handler of any page that could be created from a dialog
function closeParentDialog() {
   if (top.opener && isWindowPopup(top.opener)) {
      root = top.opener.top.opener;
      top.opener.close();
      top.opener = root;
   }
}


// Check if a window is a popup
function isWindowPopup(win) {
   return ((win.opener) ? true : false);
}