isIE = navigator.appName.indexOf("Microsoft") != -1;
isIE5 = navigator.userAgent.indexOf('MSIE 5.0') > 0;
isIE55 = navigator.userAgent.indexOf('MSIE 5.5') > 0;
isIE70 = navigator.userAgent.indexOf('MSIE 7.0') > 0;


function ylib_Browser()
{
	d=document;
	this.agt=navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
	this.dom=(d.getElementById)?1:0;
	this.ns=(d.layers);
	this.ns4up=(this.ns && this.major >=4);
	this.ns6=(this.dom&&navigator.appName=="Netscape");
	this.op=(window.opera? 1:0);
	this.ie=(d.all);
	this.ie4=(d.all&&!this.dom)?1:0;
	this.ie4up=(this.ie && this.major >= 4);
	this.ie5=(d.all&&this.dom);
	this.win=((this.agt.indexOf("win")!=-1) || (this.agt.indexOf("16bit")!=-1));
	this.mac=(this.agt.indexOf("mac")!=-1);
};

var oBw = new ylib_Browser();

function ylib_getObj(id,d)
{
	var i,x;  if(!d) d=document;
	if(!(x=d[id])&&d.all) x=d.all[id];
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][id];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=ylib_getObj(id,d.layers[i].document);
	if(!x && document.getElementById) x=document.getElementById(id);
	return x;
};

function ylib_getH(o) { return (oBw.ns)?((o.height)?o.height:o.clip.height):((oBw.op&&typeof o.style.pixelHeight!='undefined')?o.style.pixelHeight:o.offsetHeight); };
function ylib_setH(o,h) { if(o.clip) o.clip.height=h; else if(oBw.op && typeof o.style.pixelHeight != 'undefined') o.style.pixelHeight=h; else o.style.height=h; };
function ylib_getW(o) { return (oBw.ns)?((o.width)?o.width:o.clip.width):((oBw.op&&typeof o.style.pixelWidth!='undefined')?w=o.style.pixelWidth:o.offsetWidth); };
function ylib_setW(o,w) { if(o.clip) o.clip.width=w; else if(oBw.op && typeof o.style.pixelWidth != 'undefined') o.style.pixelWidth=w; else o.style.width=w; };
function ylib_getX(o) { return (oBw.ns)?o.left:((o.style.pixelLeft)?o.style.pixelLeft:o.offsetLeft); };
function ylib_setX(o,x) { if(oBw.ns) o.left=x; else if(typeof o.style.pixelLeft != 'undefined') o.style.pixelLeft=x; else o.style.left=x; };
function ylib_getY(o) { return (oBw.ns)?o.top:((o.style.pixelTop)?o.style.pixelTop:o.offsetTop); };
function ylib_setY(o,y) { if(oBw.ns) o.top=y; else if(typeof o.style.pixelTop != 'undefined') o.style.pixelTop=y; else o.style.top=y; };
function ylib_getPageX(o) { var x=0; if(oBw.ns) x=o.pageX; else { while(eval(o)) { x+=o.offsetLeft; o=o.offsetParent; } } return x; };
function ylib_getPageY(o) { var y=0; if(oBw.ns) y=o.pageY; else { while(eval(o)) { y+=o.offsetTop; o=o.offsetParent; } } return y; };
function ylib_getZ(o) { return (oBw.ns)?o.zIndex:o.style.zIndex; };
function ylib_moveTo(o,x,y) { ylib_setX(o,x);ylib_setY(o,y); };
function ylib_moveBy(o,x,y) { ylib_setX(o,ylib_getPageX(o)+x);ylib_setY(o,ylib_getPageY(o)+y); };
function ylib_setZ(o,z) { if(oBw.ns)o.zIndex=z;else o.style.zIndex=z; };
function ylib_show(o,disp) { (oBw.ns)? '':(!disp)? o.style.display="inline":o.style.display=disp; (oBw.ns)? o.visibility='show':o.style.visibility='visible'; };
function ylib_hide(o,disp) { (oBw.ns)? '':(arguments.length!=2)? o.style.display="none":o.style.display=disp; (oBw.ns)? o.visibility='hide':o.style.visibility='hidden'; };
function ylib_setStyle(o,s,v) { if(oBw.ie5||oBw.dom) eval("o.style."+s+" = '" + v +"'"); };
function ylib_getStyle(o,s) { if(oBw.ie5||oBw.dom) return eval("o.style."+s); };
function ylib_addEvt(o,e,f,c){ if(o.addEventListener)o.addEventListener(e,f,c);else if(o.attachEvent)o.attachEvent("on"+e,f);else eval("o.on"+e+"="+f) };
function ylib_writeHTML(o,h) { if(oBw.ns){var doc=o.document;doc.write(h);doc.close();return false;} if(o.innerHTML)o.innerHTML=h; };

function showDateToEnterCalendar() {
    show_calendar('document.forms[0].elements[\'entity.dateToEnterAsString\']', document.forms[0].elements['entity.dateToEnterAsString'].value)
}

function cancel() {
    window.close();
}

function save() {
    if (validate()) {
        document.forms['websiteForm'].elements['action'].value = 'Save';
        document.forms['websiteForm'].submit();
        return true;
    } else {
        return false;
    }
}

function goToRentals(){
    document.forms['confirmationForm'].action = 'rentals.html';
    document.forms['confirmationForm'].submit();
}
function validate() {
    var missingFields = false;

    refreshFieldStyles();

    if( document.forms['websiteForm'].elements['entity.serviceRequestContactName'].value.trim() == '') {
        document.forms['websiteForm'].elements['entity.serviceRequestContactName'].style.border = '1px solid red';
        missingFields = true;
    }
    if( document.forms['websiteForm'].elements['entity.serviceRequestContactPhone'].value.trim() == '') {
        document.forms['websiteForm'].elements['entity.serviceRequestContactPhone'].style.border = '1px solid red';
        missingFields = true;
    }
    if( document.forms['websiteForm'].elements['entity.serviceRequestContactEmail'].value == '') {
        document.forms['websiteForm'].elements['entity.serviceRequestContactEmail'].style.border = '1px solid red';
        missingFields = true;
    }

    if( document.forms['websiteForm'].elements['entity.serviceRequestContactEmail'].value.indexOf('@') <= 0) {
        document.forms['websiteForm'].elements['entity.serviceRequestContactEmail'].style.border = '1px solid red';
        missingFields = true;
    }

    if( document.forms['websiteForm'].elements['entity.serviceRequestBuilding'].value.trim() == '') {
        document.forms['websiteForm'].elements['entity.serviceRequestBuilding'].style.border = '1px solid red';
        missingFields = true;
    }
     if( document.forms['websiteForm'].elements['entity.dateToEnterAsString'].value.trim() != '' && !checkdate(document.forms['websiteForm'].elements['entity.dateToEnterAsString'].value.trim()) ) {
        document.forms['websiteForm'].elements['entity.dateToEnterAsString'].style.border = '1px solid red';
        missingFields = true;
    }

    if (missingFields) {
        var errorsDiv = document.getElementById('errors');
        errorsDiv.innerHTML = '<span>Make sure you have entered valid information in the required fields(<font color="Red">*</font>).</span>';
        errorsDiv.style.display = 'block';
        return false;
    } else {
        return true;
    }

}

function checkdate(val){
    var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    if (!validformat.test(val))
        return false;
    else{ //Detailed check for valid date ranges
        var monthfield = val.split("/")[0]
        var dayfield = val.split("/")[1]
        var yearfield = val.split("/")[2]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
            return false;
        else
            return true;
   }
}

function formatPhone(field) {
    //alert(field.value)
    field.value = field.value.replace(' ','');

    var ov = field.value;
    var v = "";
    var x = -1;
    // is this phone number 'escaped' by a leading plus?
    if (0 < ov.length && '+' != ov.charAt(0)) { // format it
        // count number of digits
        var n = 0;
        if ('1' == ov.charAt(0)) {  // skip it
            ov = ov.substring(1, ov.length);
        }
        for (i = 0; i < ov.length; i++) {
            var ch = ov.charAt(i);

            // build up formatted number
            if (ch >= '0' && ch <= '9') {
                if (n == 0) v += "(";
                else if (n == 3) v += ") ";
                else if (n == 6) v += "-";
                v += ch;
                n++;
            }
            // check for extension type section;
            // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
            if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
                x = i;
                break;
            }
        }
        // add the extension
        if (x >= 0) v += " " + ov.substring(x, ov.length);
        // if we recognize the number, then format it
        if (n == 10 && v.length <= 40) {
            //alert(v);
            field.value = v
        };
    }
    return true;
}

function formatCurrency(item) {
    var num = item.value;
    num = num.toString().replace(/\$|\,|\./g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    item.value = (((sign)?'':'-') + '$' + num + '.' + cents);
}

function refreshFieldStyles() {
    document.forms['websiteForm'].elements['entity.serviceRequestContactName'].style.border = '';
    document.forms['websiteForm'].elements['entity.serviceRequestContactPhone'].style.border = '';
    document.forms['websiteForm'].elements['entity.serviceRequestContactEmail'].style.border = '';
    document.forms['websiteForm'].elements['entity.serviceRequestBuilding'].style.border = '';
    document.forms['websiteForm'].elements['entity.dateToEnterAsString'].style.border = '1px solid black';
}


//////////////////////////////////////////////////
//	<JavaScript RSS Reader>			//
// 	(c) 2003 Premshree Pillai		//
//	Written on: 07/06/03 (dd/mm/yy)		//
//	http://www.qiksearch.com/		//
//////////////////////////////////////////////////

function readRSS(URI) {
	if(window.ActiveXObject) {
		var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		while(xmlDoc.readyState!=4) document.write('Loading...');
	}
	else if(document.implementation&&document.implementation.createDocument)
		xmlDoc=document.implementation.createDocument("","",null);
	xmlDoc.load(URI);
	items=xmlDoc;

	function verify() {if(xmlDoc.readyState!=4) return false;}

	function formatRSS() {
		var items_count= items.getElementsByTagName('item').length;
		var pubDate=new Array(), date=new Array, link=new Array(), title=new Array(), description=new Array(), guid=new Array();


		if (items_count > 3) {
		    items_count = 3;
		}

		for(var i=0; i<items_count; i++) {
			if(items.getElementsByTagName('item')[i].getElementsByTagName('pubDate').length==1)
				pubDate[i]=items.getElementsByTagName('item')[i].getElementsByTagName('pubDate')[0];
			if(items.getElementsByTagName('item')[i].getElementsByTagName('dc:date').length==1)
				date[i]=items.getElementsByTagName('item')[i].getElementsByTagName('dc:date')[0];
			if(items.getElementsByTagName('item')[i].getElementsByTagName('link').length==1)
				link[i]=items.getElementsByTagName('item')[i].getElementsByTagName('link')[0];
			if(items.getElementsByTagName('item')[i].getElementsByTagName('guid').length==1)
				guid[i]=items.getElementsByTagName('item')[i].getElementsByTagName('guid')[0];
			if(items.getElementsByTagName('item')[i].getElementsByTagName('title').length==1)
				title[i]=items.getElementsByTagName('item')[i].getElementsByTagName('title')[0];
			if(items.getElementsByTagName('item')[i].getElementsByTagName('description').length==1)
				description[i]=items.getElementsByTagName('item')[i].getElementsByTagName('description')[0];
		}

		if((description.length==0)&&(title.length==0)) return false;

		//document.write('<html><head><title>'+xmlDoc.getElementsByTagName('title')[0].firstChild.nodeValue+'</title></head><body>');
		//document.write('<span style="font-family:verdana,arial,helvetica; font-size:8pt">');
		//document.write('<center><a href="rss-reader.htm"><h3>[Go Back]</h3></a></center>');
		//document.write('<center><a href="'+xmlDoc.getElementsByTagName('link')[0].firstChild.nodeValue+'"><h2>'+xmlDoc.getElementsByTagName('description')[0].firstChild.nodeValue+'</h2></a></center>');
		document.write('<ul>');
		var ws=/\S/;

		for(var i=0; i<items_count; i++) {
			var pubDate_w, title_w, link_w;
			pubDate_w=(pubDate.length>0)?pubDate[i].firstChild.nodeValue:"<i>Date NA</i>";
			if(document.all)
				title_w=(title.length>0)?title[i].text:"<i>Untitled</i>";
			else
				title_w=(title.length>0)?title[i].firstChild.nodeValue:"<i>Untitled</i>";

			link_w=(link.length>0)?link[i].firstChild.nodeValue:"";
			if(link.length==0) link_w=(guid.length>0)?guid[i].firstChild.nodeValue:"";
			if(title.length>0) title_w=(!ws.test(title_w))?"<i>Untitled</i>":title_w;
			if(pubDate.length==0) pubDate_w=(date.length>0)?date[i].firstChild.nodeValue:"<i>Date NA</i>";
			document.write('<li><a href="'+link_w+'"><b>'+title_w+'</b></a> </li>');
			//if(description.length>0)
				//document.write('<font size="-1">'+description[i].firstChild.nodeValue+'</font><hr noshade><br />');
		}
		document.write('</ul>');
		//document.write('</span></body></html>');
	}

	if(typeof(xmlDoc)!="undefined") {
		if(window.ActiveXObject) formatRSS();
		else xmlDoc.onload=formatRSS;
	}
}

function checkString() {
	var loc=document.location.href.split("?")
	if(loc.length>1) {
		URI=loc[1].split("=");
		if(URI.length>1) {
			var retURI="";
			for(var i=1; i<URI.length; i++) retURI+=URI[i];
			try {readRSS(unescape(retURI));}
			catch(e) {}
		}
	}
}

function hideAllSelectsFromIE() {
    if (isIE) {
        for(var i=0; i < document.forms.length; i++) {
            for(var k=0; k < document.forms[i].elements.length; k++) {
                if (document.forms[i].elements[k].type == 'select-one' ||
                    document.forms[i].elements[k].type == 'select-multiple') {
                    document.forms[i].elements[k].style.visibility = 'hidden';
                }
            }
        }
    }
}
/*
var myrules = {
    'table.list tr' : function(element) {
        var bgcolor = element.style.backgroundColor;
        element.onmouseover = function(){
            if (this.marked2Delete != true && this.marked2Add != true && this.isSelected != true) {
                this.style.backgroundColor = '#F8F8F7';
            }
        }
        element.onmouseout = function() {
            if (this.marked2Delete != true && this.marked2Add != true && this.isSelected != true) {
                this.style.backgroundColor = bgcolor;
            }
        }
    }

};
Behaviour.register(myrules);
*/

function AjaxAction(actionFormName, actionURL) {
    var formName = actionFormName;
    var url = actionURL;
    var debug = false;
    var usePost = false;
    var async = true;

    this.setAction = function( action ) {
        document.forms[formName].action.value = action;
        return this;
    }

    this.setUsePost = function() {
        this.usePost = true;
        return this;
    }

    this.setAsync = function (pAsync) {
        this.async = pAsync;
        return this;
    }

    this.send = function() {
        try {
            document.forms[formName].ajaxMode.value = true;
            var ajaxRequest = new AjaxRequest(url);
            if (this.debug) ajaxRequest.setEchoDebugInfo();
            ajaxRequest.addFormElementsById(formName +'.action');
            ajaxRequest.addFormElementsById(formName +'.ajaxMode');

            if (document.getElementById(formName +'.entityID') != null) {
                ajaxRequest.addFormElementsById(formName +'.entityID');
            }

            for ( i = 0; i < arguments.length; i++){
                ajaxRequest.addFormElementsById(arguments[i]);
            }
            ajaxRequest.setAsync(this.async);
            ajaxRequest.sendRequest();
        } catch (e)  {
            this.handleAjaxException(e);
        }
    }

    this.sendArray = function(arg) {
        try {
            document.forms[formName].ajaxMode.value = true;
            var ajaxRequest = new AjaxRequest(url);
            if (this.debug) ajaxRequest.setEchoDebugInfo();
            ajaxRequest.addFormElementsById(formName +'.action');
            ajaxRequest.addFormElementsById(formName +'.ajaxMode');
            for ( i = 0; i < arg.length; i++){
                var elemId = arg[i];
                ajaxRequest.addFormElementsById(elemId);
            }
            ajaxRequest.setAsync(this.async);
            ajaxRequest.sendRequest();
        } catch (e)  {
            this.handleAjaxException(e);
        }
    }

    this.sendAll = function() {
/*
        try {
*/
            document.forms[formName].ajaxMode.value = true;
            var ajaxRequest = new AjaxRequest(url);
            if (this.debug) ajaxRequest.setEchoDebugInfo();
            if (this.usePost) ajaxRequest.setUsePOST();
            ajaxRequest.addFormElements(formName);
            ajaxRequest.setAsync(this.async);
            ajaxRequest.sendRequest();
/*
        } catch (e)  {
            this.handleAjaxException(e);
        }
*/
    }

    this.handleAjaxException = function(e) {
        alert('Error:' + e);
    }
}

var guestAjaxAction = new AjaxAction('guestCardForm', '/pw/marketing/website.do');

function newGuest(sid, uid) {
    document.location.href = '/pw/marketing/website.do?action=ca&sid='+sid+'&uid='+uid;
}
function newApplication(sid, uid) {
    document.location.href = '/pw/marketing/website.do?action=ta&sid='+sid+'&uid='+uid;
}

function cancelGuest() {
    guestAjaxAction.setAction('cg').sendAll();
}

function saveGuest() {
    guestAjaxAction.setAction('sg').sendAll();
}

function showMask() {
    var oMask = document.getElementById('popupMask');
    if (oMask == null) {
        oMask = document.createElement("div");
        oMask.setAttribute("id", "popupMask");
        document.getElementById("theBody").appendChild(oMask);
    }

    var fullHeight = ylib_getH(document.getElementById('content')) + 1000;
    var fullWidth = ylib_getW(document.getElementById('content'));

    //alert(fullHeight+","+ fullWidth);

    var theBody = document.documentElement;

    var scTop = parseInt(theBody.scrollTop,10);
    var scLeft = parseInt(theBody.scrollLeft,10);

    oMask.style.height = fullHeight + "px";
    //oMask.style.width = fullWidth + "px";
    oMask.style.top = scTop + "px";
    oMask.style.left = scLeft + "px";
    if(oMask!=null) {
        oMask.style.display = "block";
    }
    hideAllSelectsFromIE();
    showWait();
    //playSound('open');
}

function hideMask() {
    var oMask = document.getElementById('popupMask');
    if(oMask!=null) {
        oMask.style.display = "none";
    }
    showAllSelectsFromIE();
    hideWait();
    //killAllCalendars();
    //playSound('close');
}

function showWait() {
    var oGlobalWaiting = document.getElementById('globalWaiting');
    if (oGlobalWaiting == null) {
        oGlobalWaiting = document.createElement("div");
        oGlobalWaiting.setAttribute("id", "globalWaiting");
        oGlobalWaiting.setAttribute("class", "pleaseWaitBubble");
        

        var oImg = document.createElement("img");
        oImg.setAttribute("alt", "Please wait...");
        oImg.setAttribute("align", "middle");
        oImg.setAttribute("src", "/pw/images/loadingAnimation2.gif");

        oGlobalWaiting.appendChild(oImg)
        
        document.getElementById("theBody").appendChild(oGlobalWaiting);
    }
    showElement('globalWaiting');
    windowCentered('globalWaiting', 0, 0, false);
}

function hideWait() {
    hideElement('globalWaiting');
}

function showElement(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'block';
}
function hideElement(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'none';
}

function showAllSelectsFromIE() {
    if (isIE) {
        for(var i=0; i < document.forms.length; i++) {
            for(var k=0; k < document.forms[i].elements.length; k++) {
                if (document.forms[i].elements[k].type == 'select-one' ||
                    document.forms[i].elements[k].type == 'select-multiple') {
                    document.forms[i].elements[k].style.visibility = 'visible';
                }
            }
        }
    }
}

function windowCentered() {

    var hide = arguments[3];
    if (hide == null){
        hide = true;
    }

    var htmlID = arguments[0];
    var xOffset = 0;
    var yOffset = 0;
    if (arguments.length > 1) {
        xOffset = arguments[1];
    }
    if (arguments.length > 2) {
        yOffset = arguments[2];
    }

    var theTop = 0;

    if (document.documentElement && document.documentElement.scrollTop)
        theTop = document.documentElement.scrollTop;
    else if (document.body)
        theTop = document.body.scrollTop;

    var obj =  document.getElementById(htmlID);
    if (obj != null) {
        obj.style.left = ((ylib_getW(document.body) - ylib_getW(obj)) / 2) + xOffset;
        var zTop = theTop + (getWindowHeight() - ylib_getH(obj)) / 2;
        if (zTop < 0) {
            zTop = 0;
        }
        if (zTop + yOffset < 0) {
            obj.style.top = 0;
        } else {
            obj.style.top = zTop + yOffset;
        }
//        alert(obj.style.top  );
    }

    if (hide){
        hideWait();
    }

}

function popUp(url, popupWidth, popupHeight) {
    var x, y;
    if(!document.all) {
        x = window.screenX + 400 - (popupWidth/2);
        y = window.screenY + 300 - (popupHeight/2);
    } else {
        x = window.screenLeft + 400 - (popupWidth/2);
        y = window.screenTop + 300 - (popupHeight/2);
        y = y - 65    //IE does not include the top bars of the window in the screenTop value.
    }
    y = y - 16;       //account for the top bar of the popup
    var win = window.open(url, '', 'menubar=yes,toolbar=yes,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+popupWidth+',height='+popupHeight+',screenX='+x+',screenY='+y+',top='+y+',left='+x);
    //win.focus();
}


function init() {
    jQuery('input.date').calendar({dateFormat : 'MDY/', yearRange: '1907:2017'});
}
jQuery(document).ready(function() {init();});

function showElement(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'block';
}

function showTBodyElement(o) {
    if (o != null) {
        if (isIE) {
            o.style.display = 'block';
        } else {
            o.style.display = 'table-row-group';
        }
    }
}

function showTHeadElement(o) {
    if (o != null) {
        if (isIE) {
            o.style.display = 'block';
        } else {
            o.style.display = 'table-header-group';
        }
    }
}

function showTFootElement(o) {
    if (o != null) {
        if (isIE) {
            o.style.display = 'block';
        } else {
            o.style.display = 'table-footer-group';
        }
    }
}

function hideElement(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'none';
}

function showTable(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = '';
}

function hideTable(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'none';
}

function isHidden(elementID) {
    //alert(document.getElementById(elementID).style.display);
    if (document.getElementById(elementID))
        return document.getElementById(elementID).style.display == 'none';
}

function toggleElement(elementID) {
    if (isHidden(elementID)) {
        showElement(elementID);
        return true;
    } else {
        hideElement(elementID);
        return false;
    }
}

function zoom( index, imageID ) {

	var oThumbTable =  document.getElementById('thumbnail_' + index);
	var oZoomDiv =  document.getElementById('imageZoom');

	var oldSrc = document.getElementById('thumbnailIMG_'+index).src;
	var newSrc = oldSrc.substring(0, oldSrc.indexOf("=") + 1) + imageID;

	document.getElementById('imageZoomIMG').src = newSrc;
	showElement('imageZoom');
    verticallyCentered('imageZoom');

}

function verticallyCentered(htmlID) {
    var theTop = 0;
    if (document.documentElement && document.documentElement.scrollTop)
        theTop = document.documentElement.scrollTop;
    else if (document.body)
        theTop = document.body.scrollTop;

    var obj =  document.getElementById(htmlID);
    obj.style.top = theTop + (getWindowHeight() - ylib_getH(obj)) / 2;

}

function getWindowHeight()  {
    return window.innerHeight? window.innerHeight:document.body.clientHeight;
}

function getURLParam( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return unescape(results[1].replace(/\+/g,  " "));
}

function createXMLHttpRequest() {
    var req = false;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {
                req = false;
            }
        }
    }
    return req;
}

var apiReq = createXMLHttpRequest();

function outputBuildings(buildings, serverUrl) {
    if (serverUrl == null) serverUrl = "";

    var start = (typeof startItem != 'undefined'? startItem: 1);
    var end = (typeof endItem != 'undefined'? endItem: 20);
    end = (buildings.length < end? buildings.length: end);

    var oResultDiv = document.getElementById('result');
    if (oResultDiv != null) {
        var oTable = document.createElement("table");
        oTable.setAttribute("class", "list");
        oTable.setAttribute("className", "list");
        oTable.setAttribute("width", "90%");
        oTable.setAttribute("border", "0");
        oTable.setAttribute("cellpadding", "2");
        oTable.setAttribute("cellspacing", "0");
        oResultDiv.appendChild(oTable);
        var oTBody = document.createElement("tbody");
        oTable.appendChild(oTBody);
        if(buildings.length == 0){
            var oRown = document.createElement("tr");
            oTBody.appendChild(oRown);
            var oCelln = document.createElement("td");
            oCelln.id = "noPropertiesTag";
            oRown.appendChild(oCelln);
            oCelln.innerHTML = "There are currently no properties available. " +
                               "Fill out the form below to be added to the wait list. " +
                               "Once you are added to the wait list, you will be notified as soon as a property becomes available.";

            // get and show the "wait list" form
            var waitListDiv = document.getElementById( "waitListDiv" );
            waitListDiv.style.display = "block";
            // Remove it so the text is at the top.
            oResultDiv.removeChild( waitListDiv );
            // now we can add it so the table is under the text.
            oResultDiv.appendChild( waitListDiv );


        }
        for (i = start-1; i < end; i ++) {
            var oRow = document.createElement("tr");
            oRow.setAttribute("class", "Row_"+(i%2));
            oRow.setAttribute("className", "Row_"+(i%2));
            oTBody.appendChild(oRow);
            var oCell = document.createElement("td");
            oRow.appendChild(oCell);

            // Div 1
            var oDiv1 = document.createElement("div");
            oDiv1.setAttribute("class", "column_1");
            oDiv1.setAttribute("className", "column_1");
            oCell.appendChild(oDiv1);
            var oPropertyImageDiv = document.createElement("div");
            oPropertyImageDiv.setAttribute("class", "PropertyImage");
            oPropertyImageDiv.setAttribute("className", "PropertyImage");
            if (buildings[i].image != null) {
                oPropertyImageDiv.innerHTML = '<span><img id="featuredImage" name="featuredImage" border="0" src="images/'+buildings[i].image+'"/></span>';
            } else {
                oPropertyImageDiv.innerHTML = '<span><img id="featuredImage" name="featuredImage" border="0" src="'+serverUrl+'/pw/images/no-photo-thumbnail.gif"/></span>';
            }
            oDiv1.appendChild(oPropertyImageDiv);
            oDiv1.appendChild(document.createElement('br'));


            // Div 2
            var oDiv2 = document.createElement("div");
            oDiv2.setAttribute("class", "column_2");
            oDiv2.setAttribute("className", "column_2");
            oCell.appendChild(oDiv2);
            var oPriceRangeDiv = document.createElement("div");
            oPriceRangeDiv.setAttribute("class", "PriceRange");
            oPriceRangeDiv.setAttribute("className", "PriceRange");
            oDiv2.appendChild(oPriceRangeDiv);
            oPriceRangeDiv.appendChild(document.createElement("br"));
            oPriceRangeDiv.appendChild(document.createTextNode("From " + buildings[i].startingRent));
            var oUnitTypes = document.createElement("div");
            oUnitTypes.setAttribute("class", "UnitTypes");
            oUnitTypes.setAttribute("className", "UnitTypes");
            oDiv2.appendChild(oUnitTypes);
            oUnitTypes.appendChild(document.createTextNode(buildings[i].unitTypes));

            // Div 3
            var oDiv3 = document.createElement("div");
            oDiv3.setAttribute("class", "column_3");
            oDiv3.setAttribute("className", "column_3");
            oCell.appendChild(oDiv3);
            var oBuildingAddressDiv = document.createElement("div");
            oBuildingAddressDiv.setAttribute("class", "BuildingAddress");
            oBuildingAddressDiv.setAttribute("className", "BuildingAddress");
            oDiv3.appendChild(oBuildingAddressDiv);
            oBuildingAddressDiv.innerHTML = '<strong class="BuildingName"><a class="link" href="b_'+buildings[i].id+'.html">'+buildings[i].marketingName+'</a></strong>';
            oBuildingAddressDiv.appendChild(document.createElement("br"));
            oBuildingAddressDiv.appendChild(document.createTextNode(buildings[i].address));
            oBuildingAddressDiv.appendChild(document.createElement("br"));
            oBuildingAddressDiv.appendChild(document.createTextNode(buildings[i].city + ", "));
            oBuildingAddressDiv.appendChild(document.createTextNode(buildings[i].state + " "));
            oBuildingAddressDiv.appendChild(document.createTextNode(buildings[i].zip));
            if (buildings[i].neighborhood != null && buildings[i].neighborhood != '') {
                var bold = document.createElement("b");
                bold.appendChild(document.createTextNode("Neighborhood: "));
                oDiv3.appendChild(bold);
                oDiv3.appendChild(document.createTextNode(buildings[i].neighborhood));
            }
            var oMapLink = document.createElement("div");;
            oMapLink.setAttribute("class", "MapLink");
            oMapLink.setAttribute("className", "MapLink");
            oDiv3.appendChild(oMapLink);
            oMapLink.innerHTML ='<a class="button mapButton" href="javascript:popUp(\'http://maps.google.com/maps?q='+buildings[i].address+'%20'+buildings[i].city+'%20'+buildings[i].state+'%20'+buildings[i].zip+'\', 800, 600)"><b><b><b>Map &amp; Directions</b></b></b></a>';


            // Div 4
            var oDiv4 = document.createElement("div");
            oDiv4.setAttribute("class", "column_4");
            oDiv4.setAttribute("className", "column_4");
            oCell.appendChild(oDiv4);
            oDiv4.innerHTML = '<a class="button moreInfoButton" href="b_'+buildings[i].id+'.html"><b><b><b>More Info</b></b></b></a>';

            // Div 5
            var oDiv5 = document.createElement("div");
            oDiv5.setAttribute("class", "column_5");
            oDiv5.setAttribute("className", "column_5");
            oCell.appendChild(oDiv5);
            oDiv5.innerHTML = '<p class="ListingDescription">'+buildings[i].comments+'</p>';

        }
        if(buildings.length > 0){
            var oTFoot = document.createElement("tfoot");
            oTable.appendChild(oTFoot);
            if(!isIE){
                var oRowf = document.createElement("tr");
                oTFoot.appendChild(oRowf);
                var oCellf = document.createElement("th");
                oRowf.appendChild(oCellf);
                //New table
                var oTablef = document.createElement("table");
                oTablef.setAttribute("class", "listingPager");
                oTablef.setAttribute("className", "listingPager");
                oTablef.setAttribute("width", "100%");
                oTablef.setAttribute("border", "0");
                oTablef.setAttribute("cellpadding", "2");
                oTablef.setAttribute("cellspacing", "0");
                oCellf.appendChild(oTablef);
            } else {
                oTablef = oTFoot;
            }
            var oRowt = document.createElement("tr");
            oTablef.appendChild(oRowt);
            var oCellt = document.createElement("th");
            oRowt.appendChild(oCellt);
            oCellt.style.textAlign = 'left';
            oCellt.innerHTML = '<b>Total rental(s) available: ' + buildings.length + '</b>&#160;';
            var oRowt2 = document.createElement("tr");
            oTablef.appendChild(oRowt2);
            var oCellt2 = document.createElement("th");
            oRowt2.appendChild(oCellt2);
            oCellt2.style.textAlign = 'right';
            if(start > 1){
                oCellt2.innerHTML += '<a href="javascript:getPreviousResults()"><b><b><b>&lt;&lt; Previous</b></b></b></a>&#160;';
            }
            if(start > 1 && buildings.length > end){
                oCellt2.innerHTML += '|';
            } 
            if(buildings.length > end){
                oCellt2.innerHTML += '&#160;<a href="javascript:getNextResults()"><b><b><b>Next &gt;&gt;</b></b></b></a>';
            }
        }

    }
}

function updateSearch(){
    document.forms['searchListings'].startItem.value = 1;
    document.forms['searchListings'].endItem.value = 20;
    document.searchListings.submit();
}

function getPreviousResults(){
    var start = (typeof startItem != 'undefined'? startItem: 21);
    var end = (typeof endItem != 'undefined'? endItem: 40);

    document.forms['searchListings'].startItem.value = new Number(start) -20;
    document.forms['searchListings'].endItem.value = new Number(end) -20;
    document.searchListings.submit();
}

function getNextResults(){
    var start = (typeof startItem != 'undefined'? startItem: 1);
    var end = (typeof endItem != 'undefined'? endItem: 20);

    document.forms['searchListings'].startItem.value = new Number(start) +20;
    document.forms['searchListings'].endItem.value = new Number(end) +20;
    document.searchListings.submit();
}

function outputErrors() {
    var myJSONtext = getURLParam("err");
    if (myJSONtext != null && myJSONtext != '') {
        var result = eval('(' + myJSONtext + ')');
        if (result != null & result != '' && result.errors != null) {
            var oErrorsDiv  = document.getElementById('errors');
            var oH2 = document.createElement("h2");
            oH2.appendChild(document.createTextNode("You must correct the following: "));
            oErrorsDiv.appendChild(oH2);
            var oUl = document.createElement("ul");
            for(i = 0; i < result.errors.length; i++) {
                oUl.innerHTML = oUl.innerHTML + result.errors[i];
            }
            oErrorsDiv.appendChild(oUl);
        }
    }
}



function validateTenantApplication() {
    var errors = "You must correct the following errors: \n\n";
    var isValid = true;
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.contact.firstName"].value == "") {
        errors += "\n\t* First Name is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.contact.firstName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.contact.lastName"].value == "") {
        errors += "\n\t* Last Name is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.contact.lastName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.contact.email"].value == "") {
        errors += "\n\t* Email is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.contact.email"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.contact.mobilePhone"].value == "") {
        errors += "\n\t* Mobile Phone is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.contact.mobilePhone"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.contact.homePhone"].value == "") {
        errors += "\n\t* Home Phone is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.contact.homePhone"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.application.birthDateAsString"].value == "") {
        errors += "\n\t* Birth Date is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.application.birthDateAsString"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.application.rentalHistoryAddress"].value == "") {
        errors += "\n\t* Residence/Rental History Address is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.application.rentalHistoryAddress"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.application.rentalHistoryCity"].value == "") {
        errors += "\n\t* Residence/Rental History City is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.application.rentalHistoryCity"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.application.rentalHistoryZip"].value == "") {
        errors += "\n\t* Residence/Rental History Zip is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.application.rentalHistoryZip"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.application.referencesName1"].value == "") {
        errors += "\n\t* Reference #1 Name is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.application.referencesName1"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["tenantApplicationForm"].elements["webform.prospect.application.referencesPhone1"].value == "") {
        errors += "\n\t* Reference #1 Phone is required";
        document.forms["tenantApplicationForm"].elements["webform.prospect.application.referencesPhone1"].style.border = "3px solid red"
        isValid = false;
    }
    if (!document.forms["tenantApplicationForm"].elements["webform.applicationAgreementAccepted"].checked) {
        errors += "\n\t* You must check I Agree";
        document.forms["tenantApplicationForm"].elements["webform.applicationAgreementAccepted"].style.backgroundColor = "red"
        isValid = false;
    }




    if (!isValid) {
        alert(errors);
    } else {
        if(getURLParam('uid') != null && document.forms["tenantApplicationForm"].uid != null) {
            document.forms["tenantApplicationForm"].uid.value = getURLParam('uid');
        }
        document.forms["tenantApplicationForm"].action = SUBMIT_APPLICATION_ACTION + "&action=SubmitForm";
        document.forms["tenantApplicationForm"].retUrl.value = RETURN_URL;
        document.forms["tenantApplicationForm"].sid.value =  SID;
    }

    
    return isValid;
}

function validateContactAgent() {
    var errors = "You must correct the following errors: \n\n";
    var isValid = true;
    if (document.forms["guestCardForm"].elements["webform.guest.primaryContact.firstName"].value == "") {
        errors += "\n\t* First Name is required";
        document.forms["guestCardForm"].elements["webform.guest.primaryContact.firstName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["guestCardForm"].elements["webform.guest.primaryContact.lastName"].value == "") {
        errors += "\n\t* Last Name is required";
        document.forms["guestCardForm"].elements["webform.guest.primaryContact.lastName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["guestCardForm"].elements["webform.guest.primaryContact.email"].value == "") {
        errors += "\n\t* Email is required";
        document.forms["guestCardForm"].elements["webform.guest.primaryContact.email"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["guestCardForm"].elements["webform.guest.primaryContact.workPhone"].value == "") {
        errors += "\n\t* Day Phone is required";
        document.forms["guestCardForm"].elements["webform.guest.primaryContact.workPhone"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["guestCardForm"].elements["webform.guest.primaryContact.homePhone"].value == "") {
        errors += "\n\t* Eve. Phone is required";
        document.forms["guestCardForm"].elements["webform.guest.primaryContact.homePhone"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["guestCardForm"].elements["webform.guest.cityDesired"].value == "") {
        if((getURLParam('forSale') == 'No') || (getURLParam('forSale') == '')){
            errors += "\n\t* Which city are you most interested in? is required";
            document.forms["guestCardForm"].elements["webform.guest.cityDesired"].style.border = "3px solid red"
            isValid = false;
        }
    }
    if (document.forms["guestCardForm"].elements["webform.guest.unitTypeDesired"].value == "") {
        if((getURLParam('forSale') == 'No') || (getURLParam('forSale') == '')){
            errors += "\n\t* Which type of unit are you most interested in? is required";
            document.forms["guestCardForm"].elements["webform.guest.unitTypeDesired"].style.border = "3px solid red"
            isValid = false;
        }
    }
    if (document.forms["guestCardForm"].elements["webform.guest.numberOfOccupants"].value == "" || isNaN(document.forms["guestCardForm"].elements["webform.guest.numberOfOccupants"].value)) {
        if((getURLParam('forSale') == 'No') || (getURLParam('forSale') == '')){
            errors += "\n\t* How many residents will be occupying the unit? is required";
            document.forms["guestCardForm"].elements["webform.guest.numberOfOccupants"].style.border = "3px solid red"
            isValid = false;
        }
    }
    if (document.forms["guestCardForm"].elements["webform.guest.moveInDateAsString"].value == "") {
        if((getURLParam('forSale') == 'No') || (getURLParam('forSale') == '')){
            errors += "\n\t* Desired move in date? is required";
            document.forms["guestCardForm"].elements["webform.guest.moveInDateAsString"].style.border = "3px solid red"
            isValid = false;
        }
    }
    if (document.forms["guestCardForm"].elements["webform.guest.externalSource"].value == "") {
        errors += "\n\t* How did you hear about us? is required";
        document.forms["guestCardForm"].elements["webform.guest.externalSource"].style.border = "3px solid red"
        isValid = false;
    }


    if (!isValid) {
        alert(errors);
    } else {
        if(getURLParam('uid') != null && document.forms["guestCardForm"].uid != null) {
            document.forms["guestCardForm"].uid.value = getURLParam('uid');
        }
        document.forms["guestCardForm"].action = SUBMIT_APPLICATION_ACTION + "&action=SubmitForm";
        document.forms["guestCardForm"].retUrl.value = RETURN_URL;
        document.forms["guestCardForm"].sid.value =  SID;
    }


    return isValid;
}

function validateContactUs() {
    var errors = "You must correct the following errors: \n\n";
    var isValid = true;
    if (document.forms["contactUsForm"].elements["webform.contact.contact.firstName"].value == "") {
        errors += "\n\t* First Name is required";
        document.forms["contactUsForm"].elements["webform.contact.contact.firstName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["contactUsForm"].elements["webform.contact.contact.lastName"].value == "") {
        errors += "\n\t* Last Name is required";
        document.forms["contactUsForm"].elements["webform.contact.contact.lastName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["contactUsForm"].elements["webform.contact.contact.email"].value == "") {
        errors += "\n\t* Email is required";
        document.forms["contactUsForm"].elements["webform.contact.contact.email"].style.border = "3px solid red"
        isValid = false;
    }


    if (!isValid) {
        alert(errors);
    } else {
        if(getURLParam('uid') != null && document.forms["contactUsForm"].uid != null) {
            document.forms["contactUsForm"].uid.value = getURLParam('uid');
        }
        document.forms["contactUsForm"].action = SUBMIT_APPLICATION_ACTION + '&action=SubmitForm';
        document.forms["contactUsForm"].retUrl.value = RETURN_URL;
        document.forms["contactUsForm"].sid.value =  SID;
    }


    return isValid;
}

function validateWaitListForm() {
    var errors = "You must correct the following errors: \n\n";
    var isValid = true;
    if (document.forms["waitListForm"].elements["webform.contact.contact.firstName"].value.trim() == "") {
        errors += "\n\t* First Name is required";
        document.forms["waitListForm"].elements["webform.contact.contact.firstName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["waitListForm"].elements["webform.contact.contact.lastName"].value.trim() == "") {
        errors += "\n\t* Last Name is required";
        document.forms["waitListForm"].elements["webform.contact.contact.lastName"].style.border = "3px solid red"
        isValid = false;
    }
    if (document.forms["waitListForm"].elements["webform.contact.contact.email"].value.trim() == "") {
        errors += "\n\t* Email is required";
        document.forms["waitListForm"].elements["webform.contact.contact.email"].style.border = "3px solid red"
        isValid = false;
    }


    if (!isValid) {
        alert(errors);
    } else {
        if(getURLParam('uid') != null && document.forms["waitListForm"].uid != null) {
            document.forms["waitListForm"].uid.value = getURLParam('uid');
        }
        document.forms["waitListForm"].action = SUBMIT_APPLICATION_ACTION + '&action=SubmitForm';
        document.forms["waitListForm"].retUrl.value = RETURN_URL;
        document.forms["waitListForm"].sid.value = SID;

        document.getElementById( "cityDesired" ).value = document.getElementById( "city" ).value;
        document.getElementById( "stateDesired" ).value = document.getElementById( "state" ).value;
        document.getElementById( "zipDesired" ).value = document.getElementById( "zip" ).value;
        document.getElementById( "neighborhoodDesired" ).value = document.getElementById( "neighborhood" ).value;
        document.getElementById( "unitTypeDesired" ).value = document.getElementById( "unitType" ).value;
        document.getElementById( "rentMin" ).value = document.getElementById( "min" ).value;
        document.getElementById( "rentMax" ).value = document.getElementById( "max" ).value;
        document.getElementById( "numberBedrooms" ).value = document.getElementById( "bedrooms" ).value;
        document.getElementById( "numberBathrooms" ).value = document.getElementById( "bathrooms" ).value;
    }


    return isValid;
}

