// allows Flash to update the browser URL without reloading page
function flashPutHref(href) { location.href = href; }
function flashPutTitle(title) { document.title = title; }

// append a function to the window.onunload event
function AddUnloadEvent(func) { 
	var oldonunload = window.onunload; 
	if (typeof window.onunload != 'function'){ 
		window.onunload = func
	} else { 
		window.onunload = function() {
			oldonunload();
			func();
		}
	}
}

//get browser window width & height
function GetWindowSize() {
  var w = 0;
  var h = 0;

  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    w = window.innerWidth;
    h = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    w = document.documentElement.clientWidth;
    h = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    w = document.body.clientWidth;
    h = document.body.clientHeight;
  }
  return ([w, h]);
}

//get element's x & y position relative to the page document
function GetPosition(el) {
  var x = 0;
  var y = 0;
  if (el.offsetParent) {
		while(1) {
			x += el.offsetLeft;
			y += el.offsetTop;
			if (!el.offsetParent) break;
			el = el.offsetParent;
		}
  } else if (el.x) {
    x += el.x;
    y += el.y;
  }
  return ({x:x, y:y});
}


// cookie functions

function CreateCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function ReadCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

// string checker
function IsEmpty(s) {
  return (s == "" || s == null);
}


// browser sniffer class
function UA () {
  var ua = navigator.userAgent.toLowerCase(); 
  this.ua = ua;
  
	this.isIE = ( (ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1) );
	this.isSafari = (ua.indexOf("safari") != -1); 

	// browser version
	this.ver = parseFloat(navigator.appVersion); 


  // operating system
	this.isWin   = (ua.indexOf('win') != -1 && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1) );
	this.isMac   = (ua.indexOf('mac') != -1);
	this.isUnix  = (ua.indexOf('unix') != -1 || ua.indexOf('linux') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)

	// correct version number for IE4+ 
	if (this.isIE && this.ver >= 4) {
		this.ver = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
	}
	
	this.isIE5 = (this.isIE && this.ver >= 5 && this.ver < 5.5);
	this.isIE55 = (this.isIE && this.ver >= 5.5 && this.ver < 6);
	this.isIE6 = (this.isIE && this.ver >= 6 && this.ver < 7);
}



// initialize global object $G
var $G = {};
$G.UA = new UA(); // init browser sniffer
$G.FX = [] // page effects collection;





/* stylesheet switcher functions - begin */

function setActiveStyleSheet(title) {
  if (document.getElementsByTagName) {
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
      if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
        a.disabled = true;
        if(a.getAttribute("title") == title) a.disabled = false;
      }
    }

		toggleFontSize(title);
  }
}

function getActiveStyleSheet() {
  if (document.getElementsByTagName) {
    var i, a;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
      if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
    }
    return null;
  }
}

function getPreferredStyleSheet() {
  if (document.getElementsByTagName) {
    var i, a;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
      if(a.getAttribute("rel").indexOf("style") != -1
         && a.getAttribute("rel").indexOf("alt") == -1
         && a.getAttribute("title")
         ) return a.getAttribute("title");
    }
  }
  return null;
}

function saveStyleSheetCookie() {
  var title = getActiveStyleSheet();
  CreateCookie("style", title, 365);
}

function initStyleSheet() {
  // SING - added to stylesheet link event handler
  if ($) {
    if ($("nav_utils_fontsize_increase")) {
      $("nav_utils_fontsize_increase").onclick = function () {
        setActiveStyleSheet('largetext');
        return false;
      };
    }
    if ($("nav_utils_fontsize_decrease")) {
      $("nav_utils_fontsize_decrease").onclick = function () {
        setActiveStyleSheet('default');
        return false;
      };
    }
    
		toggleFontSize(title);
    if ($("nav_utils")) $("nav_utils").style.display = "block";
  }
  
}


// toggle stylesheet switch link display
function toggleFontSize(title) {
    switch (title) {
      case "largetext":
        if ($("nav_utils_fontsize_increase")) $("nav_utils_fontsize_increase").style.display = "none";
        if ($("nav_utils_fontsize_decrease")) $("nav_utils_fontsize_decrease").style.display = "block";
        break;
      default:
        if ($("nav_utils_fontsize_increase")) $("nav_utils_fontsize_increase").style.display = "block";
        if ($("nav_utils_fontsize_decrease")) $("nav_utils_fontsize_decrease").style.display = "none";
        break;
    }
}


/* moved setActiveStyleSheet from onload event to parse-time */
var cookie = ReadCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
  

Event.observe(window, 'load', initStyleSheet);
AddUnloadEvent(saveStyleSheetCookie);

/* stylesheet switcher functions - end */








// initialize Utilities navigation
function InitUtils() {
  if ($("nav_utils_print")) {
    $("nav_utils_print").onclick = function () {
      window.print();
      return false;
    };
  }

  if ($("nav_utils_email")) {
    $("nav_utils_email").onclick = function () {
    	email_page();
	return false;
    };
  }

  if ($("nav_utils")) $("nav_utils").style.display = "block";
}

Event.observe(window, 'load', InitUtils);



// resizes Flash photo gallery
function ToggleFlashResize() {
  if ($) {
    var hero = $("hero");
    var flash = $("fsPhotoGallery");
    var content = $("content");
    var container1 = $("container1");
    var container2 =$("container2");
    var logo = $("logo");
    var left = $("col_left");
    var center = $("col_center");
    var right = $("col_right");
    if (hero.offsetWidth == 720) {
      logo.style.display = "none";
      left.style.display = "none";
      center.style.display = "none";
      right.style.display = "none";
      content.style.width = "100%";
      container2.style.paddingLeft = "0";
      hero.style.position = "absolute";
      hero.style.top = "0";
      hero.style.left = "0";
      ResizeFlash("100%", "100%");
      container1.style.height = flash.offsetHeight + "px";
      container1.style.overflow = "hidden";
     } else {
      logo.style.display = "block";
      left.style.display = "block";
      center.style.display = "block";
      right.style.display = "block";
      content.style.width = "720px";
      container2.style.paddingLeft = "235px";
      hero.style.position = "";
      hero.style.top = "";
      hero.style.left = "";
      ResizeFlash("720px", "585px");
      container1.style.height = "";
      container1.style.overflow = "";
     }
  } 
}

function ResizeFlash(w, h) {
  if ($) {
    var hero = $("hero");
    var flash = $("fsPhotoGallery");

    hero.style.width = w;
    hero.style.height = h;
    flash.style.width = w;
    flash.style.height = h;
  }
}


// resize the flash movie to 100% of the browser viewport
function FullScreenFlash() {
  if ($) {
    var flash = $("fsPhotoGallery");
    var container1 = $("container1");

    if (flash && flash.style.height == "100%") {
      container1.style.height = "";
      ResizeFlash("100%", "100%");
      container1.style.height = flash.offsetHeight + "px";
    }
  }
}

Event.observe( window, 'resize', FullScreenFlash);

// placeholder function for residences top level site...
var InitHomepageLeftColumn;








/*=========================================================================================
	email this page		
==========================================================================================*/

var emailFormTop;									// integer used to track position of email form
var emailFormObject;								// html object reference - value is set later
var emailFormID = "emailThisPage";					// html ID of email form
var emailViewerID = "emailThisPageViewer";				// html ID of viewer div surrounding email form
var emailFormInterval;								// timeout variable
var emailScrollIncrements = new Array(40,10,3,1);	// array of scroll increments to create an 'ease out' effect. last item should always be '1'
var emailScrollIncrement = 0;						// index variable to step through the above array



/*------------------------------------------------------------
*  Function:  emailThisPage
*  
*  Description:
*  sets position of email form and calls scrolling function
*  called when user clicks email this page button in page tools module
*  
*  Parameters:
*  none
*  
*  Return:
*  none
*------------------------------------------------------------*/
function emailThisPage(page_url, page_name, property_name) {
	// only run if email form isn't already showing
	if ($(emailViewerID).style.visibility != "inherit") 
	{
		// Using prototype.js framework to retrieve confirmation page.
		var ajaxUpdater = new Ajax.Updater(
			$(emailViewerID),
			"/apps/residences/email_this_page/form.weml",
			{
				method:		'get',
				onComplete:	gotEmailForm,
				parameters:     "page_url=" + page_url + "&page_name=" + page_name + "&property_name=" + property_name
			}
		);

		hide_select_boxes("hidden");

	}
}


/*------------------------------------------------------------
*  Function:  gotEmailForm
*  
*  Description:
*  Event handler for successful completion of call to
*  AJAX.Updater that loads the email form into the emailThisPage div. 
*  
*
*  Parameters:
*  none
*  
*  Return:
*  none
*------------------------------------------------------------*/
function gotEmailForm() 
{

	emailFormObject = $(emailFormID);
	//move email form upward out of view
	emailFormTop =  0 - (emailFormObject.offsetHeight + 10);
	emailFormObject.style.top = emailFormTop + "px";

	// line below sets height of viewer div to 10px larger than email form
	// may need to increase this value if error messages are inserted into the form
	// or push it out to a separate function that can be called by the error display function
	$(emailViewerID).style.height = (emailFormObject.offsetHeight + 10) + "px";
	show(emailViewerID);

	scrollEmailForm();

	
}


/*------------------------------------------------------------
*  Function:  scrollEmailForm
*  
*  Description:
*  does the work of scrolling the email form
*  uses an array of scroll increments, defined above, to create an ease-out effect
*  
*  Parameters:
*  none
*  
*  Return:
*  none
*------------------------------------------------------------*/
function scrollEmailForm() {
	var distance = 0 - emailFormTop;

	
	// if distance is less than 3 x current scroll increment, use next increment
	if (distance < emailScrollIncrements[emailScrollIncrement] * 3) {
		emailScrollIncrement++;
	}
	// make sure we don't exceed the bounds
	if (emailScrollIncrement >= emailScrollIncrements.length) emailScrollIncrement = emailScrollIncrements.length - 1;

	
	// Only scroll down if top edge is hidden
	if (emailFormTop < 0) {
		emailFormTop += emailScrollIncrements[emailScrollIncrement];

		// make sure we don't go past zero
		if (emailFormTop > 0) emailFormTop = 0;
		emailFormObject.style.top = emailFormTop + "px";

		// Wait to see if flag is reset. Otherwise, keep scrolling
		emailFormInterval = setTimeout("scrollEmailForm()", 10);
	} else {

		// stop scrolling
		clearTimeout(emailFormInterval);
		emailScrollIncrement = 0;
	}
}




/*------------------------------------------------------------
*  Function:  hideEmailThisPage
*  
*  Description:
*  hides email form when user clicks close window or cancel button
*  
*  Parameters:
*  none
*  
*  Return:
*  none
*------------------------------------------------------------*/
function hideEmailThisPage() {
	hide(emailViewerID);
	
	hide_select_boxes("visible");

}

var pageURL = "";		// Placeholder for URL of page being e-mailed

/*------------------------------------------------------------
*  Function:  submitEmail
*  
*  Description:
*  Submit handler for E-mail this page form.  Provides
*  temporary simulation of an e-mail confirmation.  To be
*  replaced with proper form validation and submission.
*  
*  Parameters:
*  which	object	the e-mail form being submitted
*  formPage	object	the E-mail this form page
*  
*  Return:
*  none
*------------------------------------------------------------*/
function submitEmail(which, formPage) {
	// Retrieve the URL of the page being emailed.
	//pageURL = document.getElementById("pageURL").value;
	
	if(!(the_form = $(emailFormID)))
	{
		alert("Submission failed.\nCould not find form object");
		return;
	}
	
	params = Form.serialize(the_form);
	
	// Using prototype.js framework to retrieve confirmation page.
	var ajaxUpdater = new Ajax.Updater(
		formPage,
		"/apps/residences/email_this_page/submit.weml",
		{
			method:		'post',
			onComplete:	displayURL,
			parameters:     params
		}
	);
}



/*------------------------------------------------------------
*  Function:  displayURL
*  
*  Description:
*  Event handler for successful completion of call to
*  AJAX.Updater. Updates URL display in E-mail this page form
*  confirmation based on hidden input field.
*  
*  Parameters:
*  none
*  
*  Return:
*  none
*------------------------------------------------------------*/
function displayURL() {
	// Display the page being emailed.
	$('pageURLdisplay').innerHTML = pageURL;
}	

/*------------------------------------------------------------
*  Function:  show
*  
*  Description:
*  shows an object, if not nested in a hidden object
*  
*  Parameters:
*  which	string/object	ID of object to be shown, or reference to the object itself
*  
*  Return:
*  none
*------------------------------------------------------------*/
function show(which) {
	var obj = $(which);
	if (obj) obj.style.visibility = "inherit";
}

/*------------------------------------------------------------
*  Function:  hideEmailThisPage
*  
*  Description:
*  hides email form when user clicks close window or cancel button
*  
*  Parameters:
*  none
*  
*  Return:
*  none
*------------------------------------------------------------*/
function hideEmailThisPage() {
	hide(emailViewerID);	
	hide_select_boxes("visible");

}

/*------------------------------------------------------------
*  Function:  hide_select_boxes
*  
*  Description:
*  
*  
*  
*  Parameters:
*  visible_style = visible or hidden
*  
*  Return:
*  none
*------------------------------------------------------------*/
function hide_select_boxes(visible_style)
{
	if (typeof(date_selector)!="undefined")
	{
		if(date_selector==true)
		{
			var select_tag_items = document.getElementsByTagName('select');
			for (var i = 0; i < select_tag_items.length; i++)
				if(select_tag_items[i].name!="Guests")
					select_tag_items[i].style.visibility = visible_style;
		}
	}
}

/*------------------------------------------------------------*/
function hide(which) {
	var obj = $(which);
	if (obj) obj.style.visibility = "hidden";
}




/*------------------------------------------------------------
*  Function:  openPopupWindow
*  
*  Description:
*  opens a popup window of a passed width and height
*  and loads the passed URL in it
*  
*  Parameters:
*  url			string		page to load
*  w			integer		width of popup window
*  h			integer		height of popup window
*  features		string		window features - see below for defaults
*  
*  Return:
*  none
*------------------------------------------------------------*/
var popupWindow=null;

function openPopupWindow(url,w,h,features) {
	if (w == null || w=='') w = 400;
	if (h == null || h=='') h = 400;
	if (features == null) features = ",menubar=0,status=0,location=0,directories=0,resizable=1,scrollbars=1";
	
	if (url) {

		if ( (popupWindow!=null) && !popupWindow.closed && popupWindow.location ){
			popupWindow.location.href = url;
			popupWindow.focus();
		} else {
			popupWindow = window.open(url,'popupWindow','width='+w+',height='+h+features);
			popupWindow.focus();
			if (!popupWindow.opener) popupWindow.opener = self;
		}

	}
}




/****** This fixes the center column so it comes down further, if it is short ****/
function fix_content()
{
	col_left_height = Element.getHeight("col_left");
	content_height = Element.getHeight("content");

	if(!col_left_height || !content_height)
		return 0;

	if((col_left_height+350)>content_height)
	{
		if($ && $("content"))
			$("content").style.height= + (col_left_height+350) + "px";
	}

	return content_height;
}










