/* cre-common.js */
var CRE = new Class.create();

Object.extend(CRE, {C_AJAX_SEARCH_REGIONAL: '/includes/ajax/search-regional-listings.ajax.asp'});


CRE.Search = Class.create();

CRE.Search.prototype = {

	initialize : function()
	{
		// STUB
	},

	sort : function (obj) {
		if (obj.form) { obj.form.submit(); }
	}

}

CRE.prototype = {
    initialize: function (components) {
        if (components) {
            if (components.SRCH) {
                this.srch = new CRE.Search();
            }

            if (components.ADDS) {
                this.ads = new CRE.AdManager(components.ADDS);
            }

            if (components.BOOKMARKS) {

                this.bookmarks = new CRE.Bookmarks();
                this.bookmarks.Configure();
            }

            if (components.MAP) {
                this.gmap = new CRE.GMap(components.MAP);
            }
        }
    },

    bindMaps: function () {
        var elms = $A(document.getElementsByTagName('AREA'));
        var o = this;
        elms.each(function (elm) { elm.onclick = o.showRegion.bindAsEventListener(elm); });
    },

    showRegion: function (item) {

        var fm = $('searchForm');
        if (!fm) { alert('A list component could not be found!'); return false; }
        var it = (item.target) ? item.target : ((item.srcElement) ? item.srcElement : item);
        if (it.id.substring(0, 2) == 'r_') {
            $('hdnRegionID').value = it.id.substring(2);
            fm.action = "/searchmap"
            fm.submit();
        }
        else {

            var sel = $('selCity');
            if (sel) {
                while (sel.options.length > 0) { sel.options[sel.options.length - 1] = null }
            }

            var h = $('hdnRegionID'); if (h) h.value = it.id;
            //var pt = $('hdnListingArea'); if(pt) {if(pt.value=='BUSINESS') { fm.submit();return false;}};
            sel.options[0] = new Option("-- All of " + ((it) ? it.title : item) + " --");

            var searchAJ = new Ajax.Request(
				CRE.C_AJAX_SEARCH_REGIONAL,
				{
				    method: 'get',
				    parameters: Form.serialize(fm) + "&rs=" + it.id,
				    onSuccess: CRE.prototype.fillList

				});

        }
        return false;

    },

    upRegion: function () {
        var fm = $('searchForm'); var $hdn = $('hdnRegionID');
        if (fm) { fm.action = "/searchmap"; $hdn.value = ""; fm.submit() };
    },

    fillList: function (resp) {
        var sel = $('selCity');
        if (!sel) { alert('Cannot find list to fill with results!'); return false; }
        while (sel.options.length > 1) { sel.options[sel.options.length - 1] = null }
        var json = eval('(' + resp.responseText + ')');
        json.rows.each(function (item) {
            var o = new Option(item.groupname, item.regiongroupid);
            sel.options[sel.options.length] = o;
        });
        return false;
    },

    /* advanced searchh*/
    showCategories: function (p) {
        if (p == 'Buildings') { $('divBuildings').show(); $('divLand').hide(); }
        if (p == 'Land') { $('divBuildings').hide(); $('divLand').show(); }
        this.checkOccupancy();
    },

    checkOccupancy: function () {
        var Leased = $('radOccupancyLeased');
        var Vacant = $('radOccupancyVacant');
        var Building = $('divBuildings');
        var Land = $('divLand');
        if (Element.visible(Building)) { $('divBuildingArea').show() } else { $('divBuildingArea').hide() }
        if (Element.visible(Land)) { $('divLandArea').show() } else { $('divLandArea').hide() }
    },

    checkLease: function (fld) {
        var ot = $('otLEASE');
        if (fld.value == 'INVESTMENT') {
            ot.checked = false;
            Form.Element.enable(ot);
            var l = $('lblAR'); if (l) l.innerHTML = '<strong>ANNUAL RETURN</strong>';
        } else {
            Form.Element.disable(ot);
            var l = $('lblAR'); if (l) l.innerHTML = '<strong>ANNUAL RENTAL</strong>';
        }
        return true;
    },

    SaveSearchCriteria: function () {
        var oSCWindow = window.open("/SaveCurrentSearch.asp", "SSWindow", "addressbar=0, scrollbars=1, width=400, height=550", true);
        oSCWindow.focus();
    }
}

CRE.AdManager = new Class.create();

Object.extend(CRE.AdManager, {

    Params: {
    	Bust: function() { return Math.floor(1000000*Math.random())},
    	Site: 'onl.comreal',
    	URL: 'http://ad-apac.doubleclick.net/adi'
    },

	Ads: {
		Masthead: {
			Height: 60,	Width: 468,	AdSpace: '468x60'
		},
		Sponsor: {
			Height: 20,	Width: 140,	AdSpace: '140x20'
		},
		Skyscraper: {
			Height: 600, Width: 160, AdSpace: '160x600'
		},
		InResult: {
			Height: 60, Width: 468, AdSpace: '468x60'
		},
		Tail: {
			Height: 60, Width: 468, AdSpace: '468x60'
		},
		Island: {
			Height: 250, Width: 300, AdSpace: '300x250'
		}
	}

});

CRE.AdManager.prototype = {
    initialize: function(c) {
        var tile = 1;
        var cacheBuster = Math.floor(Math.random() * (999999999 - 10000000 + 1)) + 10000000;
        for (i in c.ads) { this.display(c.ads[i].dest, c.ads[i].item, c, c.ads[i].loc, tile++, cacheBuster); }
        for (i in c.visible) { this.showAdFrame(c.visible[i].dest, c.visible[i].show); }
    },

    display: function(destination, item, components, loc, tile, cachBuster) {
        var dest = $(destination);
        if (dest) {
            var locale = (components.locale && components.locale != "") ? ";locstate=" + components.locale.replace(/%20|\s|\+/gi, "_").replace(/[&\/\-\,\(\)]/gi, "").toLowerCase() : "";
            var suburb = (components.suburb && components.suburb != "") ? ";locsuburb=" + components.suburb.replace(/%20|\s|\+/gi, "_").replace(/[&\/\-\,\(\)]/gi, "").toLowerCase() : "";
            var area = (components.area && components.area != "") ? ";locarea=" + components.area.replace(/%20|\s|\+/gi, "_").replace(/[&\/\-\,\(\)]/gi, "").toLowerCase() : "";
            var categories = (components.categories && components.categories != "") ? ";proptype=" + components.categories.toLowerCase() : "";
            var tile = (tile) ? tile : "1";
            var pos = (loc) ? ";pos=" + loc : ";pos=1";
            var dcOpt = tile == 1 ? ";dcopt=ist" : "";

            var srcValue = CRE.AdManager.Params.URL + "/" + CRE.AdManager.Params.Site + "/" + components.cat.toLowerCase() +
                           locale + suburb + area + categories + pos + ";tile=" + tile + ";sz=" + item.AdSpace +
                           dcOpt + ";ord=" + cachBuster + "?";

            dest.innerHTML = "<iframe width=" + item.Width + " height=" + item.Height + " marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no bordercolor='#000000' src='" + srcValue + "'><\/iframe>";
        }
        dest = null;
    },

    // Used for sponsored links
    showAdFrame: function(destination, show) {
        var dest = $(destination);
        if (dest) { if (show) { Element.show(dest); } else { Element.hide(dest); } }
        dest = null;
    }
};

CRE.Bookmarks = new Class.create();
Object.extend(CRE.Bookmarks, {
	// placeholder
});

CRE.Bookmarks.prototype = {
    initialize: function() {
		this.asCurrentBookmarkItems = new Array();
		this.lBookmarkCounter = 0;
		this.objUserCookie = null;
    },

	Configure: function () {
		this.objUserCookie = this.ReadUserBookmarks('BookmarkedProperties');
	},

	ReadUserBookmarks: function(CookieName) {
		var bFoundCookieInfo = false

		if (document.cookie) {
			var asCookieInfo = document.cookie.split('; ');

			for (var iLoop=0; iLoop<asCookieInfo.length; iLoop++) {
				var asCrumbInfo = asCookieInfo[iLoop].split('=');
				if (asCrumbInfo[0] == CookieName) {
					if (asCrumbInfo[1]) {
						var sAllValueString = unescape(asCrumbInfo[1]);
						var asAllValues = sAllValueString.split(',')

						for (var iAddItem = 0; iAddItem < asAllValues.length; iAddItem++) {
							this.asCurrentBookmarkItems[this.lBookmarkCounter] = asAllValues[iAddItem];
							this.lBookmarkCounter++;
							bFoundCookieInfo = true;
						}
					}
				}
			}
		}

		if (!bFoundCookieInfo) {
			this.asCurrentBookmarkItems[0] = '';
			this.lBookmarkCounter = 0;
		} else {
			this.CheckBookmarkedProperties();
		}
	},

	CheckBookmarkedProperties: function() {
		for (var iCheckIt = 0; iCheckIt < this.asCurrentBookmarkItems.length; iCheckIt++) {
			if (document.getElementById('bmLink_' + this.asCurrentBookmarkItems[iCheckIt])) {
				document.getElementById('bmLink_' + this.asCurrentBookmarkItems[iCheckIt]).innerHTML = 'Drop this saved listing';
			}
		}
		for (var iCheckIt = 0; iCheckIt < this.asCurrentBookmarkItems.length; iCheckIt++) {
			if (document.getElementById('bm2Link_' + this.asCurrentBookmarkItems[iCheckIt])) {
				document.getElementById('bm2Link_' + this.asCurrentBookmarkItems[iCheckIt]).innerHTML = 'Remove from Shortlist';
				document.getElementById('bm2Link_' + this.asCurrentBookmarkItems[iCheckIt]).setAttribute("class", "iconStarFull")
			}
		}
	},

	IsBookmarked: function(PropertyID) {
		var bRetVal = false;
		var lCheckLoop;

		// Look through our array to see if the item exists
		for (lCheckLoop = 0; lCheckLoop < this.lBookmarkCounter; lCheckLoop++) {
			if (parseInt(this.asCurrentBookmarkItems[lCheckLoop]) == parseInt(PropertyID)) {
				bRetVal = true;
				break;
			}
		}

		return bRetVal;
	},

	GetBookmarkSubscript: function(PropertyID) {
		var lRetVal = -1;
		var lCheckLoop;

		// Look through our array to see if the item exists
		for (lCheckLoop = 0; lCheckLoop < this.lBookmarkCounter; lCheckLoop++) {
			if (parseInt(this.asCurrentBookmarkItems[lCheckLoop]) == parseInt(PropertyID)) {
				lRetVal = lCheckLoop;
				break;
			}
		}

		return lRetVal;
	},

	SetBookmarkItem: function(PropertyID) {
		// Check to see if this item is already in the list
		if (!this.IsBookmarked(PropertyID)) {
			// Does not already exist, so, tack it onto the end of the array
			this.asCurrentBookmarkItems[this.lBookmarkCounter] = PropertyID;
			this.lBookmarkCounter++;

			// Write the cookie away again to be safe
			this.WriteUserBookmarks();
		}
	},

	RemoveBookmarkItem: function(PropertyID) {
		// Does this item exist in our list of bookmarked items?
		if (this.IsBookmarked(PropertyID)) {
			// Get the index of the item
			var lItemSubscript = this.GetBookmarkSubscript(PropertyID)

			// Blank this item out
			this.asCurrentBookmarkItems[lItemSubscript] = '';

			// Shuffle all of the following items up one subscript
			var iShuffle;

			for (iShuffle = lItemSubscript + 1; iShuffle < this.lBookmarkCounter; iShuffle++) {
				if (this.asCurrentBookmarkItems[iShuffle]) {
					this.asCurrentBookmarkItems[iShuffle - 1] = this.asCurrentBookmarkItems[iShuffle];
				}
			}

			// Remove the final subscript
			this.asCurrentBookmarkItems.length--;
			this.lBookmarkCounter--;

			// Write away the new details
			this.WriteUserBookmarks();
		}
	},

	ChangeBookmarkState: function(PropertyID) {
		var s = $('bmLink_'+PropertyID);
		if (document.cookie) {
			if (!this.IsBookmarked(PropertyID)) {
				this.SetBookmarkItem(PropertyID);
				if(s) s.innerHTML = 'Remove from shortlist';
			} else {
				this.RemoveBookmarkItem(PropertyID);
				if(s) s.innerHTML = 'Add to shortlist';
			}
		} else {
			// No cookies enabled.
			this.DisplayErrorAlert();
		}
	},
	
	ChangeBookmarkStateDetail: function(PropertyID) {
		var s = $('bm2Link_'+PropertyID);
		if (document.cookie) {
			if (!this.IsBookmarked(PropertyID)) {
				this.SetBookmarkItem(PropertyID);
				if(s) {
					s.innerHTML = 'Remove from Shortlist';
					s.setAttribute("class", "iconStarFull")
				}
			} else {
				this.RemoveBookmarkItem(PropertyID);
				if(s) {
					s.innerHTML = 'Add to Shortlist';
					s.setAttribute("class", "iconStarEmpty")
				}
			}
		} else {
			// No cookies enabled.
			this.DisplayErrorAlert();
		}
	},

	ChangeSingleBookmark: function(p_PropertyID) {
		var s = $('singleSave');
		if (document.cookie) {
			if (!this.IsBookmarked(p_PropertyID)) {
				this.SetBookmarkItem(p_PropertyID);
				if (s) s.innerHTML = 'Remove from Shortlist';
				       s.setAttribute("class", "iconStarFull")
			} else {
				this.RemoveBookmarkItem(p_PropertyID);
				if (s) s.innerHTML = 'Add to Shortlist';
				       s.setAttribute("class", "iconStarEmpty")
			}
		} else {
			// No cookies enabled.
			this.DisplayErrorAlert();
		}
	},

	WriteUserBookmarks: function()
	{
		var sBookmarkList
		if (this.lBookmarkCounter > 0) {
			sBookmarkList = this.asCurrentBookmarkItems.join(',');
		} else {
			sBookmarkList = ''; // No items in the list
		}

		var dCookieExpiry = new Date();

		dCookieExpiry.setTime(dCookieExpiry.getTime() + (1000*60*60*24*365)) // One year from today
		document.cookie = 'BookmarkedProperties=' + escape(sBookmarkList) + ';expires=' + dCookieExpiry.toGMTString() + ';path=/;';
	},

	DisplayErrorAlert: function()
	{
		var sCookieErrorText

		sCookieErrorText = 'Attention.\n\======\nThis function requires cookies to be enabled. We have been unable to confirm that cookies are enabled in your web browser.';
		sCookieErrorText += '\n\nPlease enable cookies before attempting to use this function.\n\nFor information on enabling cookies, please refer to your browser\'s help material or contact your system administrator.';
		sCookieErrorText += '\n\nWe apologise for any inconvenience this may cause.';

		alert(sCookieErrorText);
	}
}

CRE.GMap = new Class.create();

CRE.GMap.prototype = {
    initialize: function(args) {
    	this.destination = (args.dest) ? args.dest : "gMap";
    	this.properties = args;

    	Event.observe(window, 'load', this.startMap.bindAsEventListener(this), false);
		Event.observe(window, 'unload', this.endMap, false);
    },

    startMap : function()
    {
    	if (GBrowserIsCompatible()) {
    		if ($(this.destination)) {
    			this.map = new GMap($(this.destination));

				this.map.addControl(new GSmallMapControl());
				this.map.addControl(new GMapTypeControl());
				this.map.addControl(new GOverviewMapControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 10)));

				var point = new GLatLng(this.properties.lat, this.properties.lng)

				this.map.setCenter(point, this.properties.zoom);

				/* get the host name */

				var regex = new RegExp("http://([^/])+/");
				var host = String(regex.exec(window.location)[0]);
				host = host.replace("http:", "");
				while (host.indexOf("/") != -1)
					host = host.replace("/", "");

				this.icon = new GIcon();
				this.icon.image = new String("http://" + host + "/images/gmaps/pin-red.png");
				this.icon.shadow = new String("http://"+host+"/images/gmaps/pin-shadow.png");
				this.icon.iconSize = new GSize(30, 25);
				this.icon.shadowSize = new GSize(30, 31);
				this.icon.iconAnchor = new GPoint(4, 20);

				this.icon.infoWindowAnchor = new GPoint(5, 1);
				var marker = new GMarker(point , {icon:this.icon});

				this.map.addOverlay(marker);
			}
    	}
    },

    endMap : function()
    {
    	GUnload();
    }
}

function CheckForRating() {
    var buildingSize = document.getElementById("txtBuildingArea").value
    var nabersRating = document.getElementById("txtNabersRating").value
    if (buildingSize > 2000 & nabersRating <= 0) {
        document.getElementById("txtNabersRating").visible = true;
        alert("A NABERS Rating is required");
    }
}

function RoundValue() {
    var nabersRating = document.getElementById("txtNabersRating").value
    if((nabersRating*10)%5 != 0) 
    {
        if ((nabersRating * 10) % 5 < 3) 
            document.getElementById("txtNabersRating").value = ((nabersRating * 10) - (nabersRating * 10) % 5) / 10;
        else
            document.getElementById("txtNabersRating").value = ((nabersRating * 10) - ((nabersRating * 10) % 5) + 5) / 10;
        alert("NABERS Rating must be an increment of .5 of an integer");     
    }
}

//Enable radio text box after selected radio
//and disable other radio boxes in the same group
function RadioSelected(e) {

    var target ;
    if (!e)
        target = $(event.target);
    else
        target = e.target;

    //if target can not be found via event target, we'll try srcElement (IE)
    if (!target)
        target = $(event.srcElement);
   
   
    var otherRadios = $$('input[name=' + target.readAttribute('name') + ']');
    //Enable text box follows checked item, disable it otherwise
    otherRadios.each(function (element) {            
        //Gather textboxes that need to be enabled/disable
        var textboxes = element.nextSiblings();

        if (element == target) {
            textboxes.each(function (textbox) { textbox.removeAttribute('disabled'); });
        }
        else {
            textboxes.each(function (textbox) { textbox.setAttribute('disabled','disabled'); });
        }
    });
}

// Opens a new window with advanced featurs
function GP_AdvOpenWindow(theURL,winName,features,popWidth,popHeight,winAlign,ignorelink,alwaysOnTop,autoCloseTime,borderless) { //v2.0
  var leftPos=0,topPos=0,autoCloseTimeoutHandle, ontopIntervalHandle, w = 480, h = 340;
  if (popWidth > 0) features += (features.length > 0 ? ',' : '') + 'width=' + popWidth;
  if (popHeight > 0) features += (features.length > 0 ? ',' : '') + 'height=' + popHeight;
  if (winAlign && winAlign != "" && popWidth > 0 && popHeight > 0) {
    if (document.all || document.layers || document.getElementById) {w = screen.availWidth; h = screen.availHeight;}
		if (winAlign.indexOf("center") != -1) {topPos = (h-popHeight)/2;leftPos = (w-popWidth)/2;}
		if (winAlign.indexOf("bottom") != -1) topPos = h-popHeight; if (winAlign.indexOf("right") != -1) leftPos = w-popWidth;
		if (winAlign.indexOf("left") != -1) leftPos = 0; if (winAlign.indexOf("top") != -1) topPos = 0;
    features += (features.length > 0 ? ',' : '') + 'top=' + topPos+',left='+leftPos;}
  if (document.all && borderless && borderless != "" && features.indexOf("fullscreen") != -1) features+=",fullscreen=1";
  if (window["popupWindow"] == null) window["popupWindow"] = new Array();
  var wp = popupWindow.length;
  popupWindow[wp] = window.open(theURL,winName,features);
  if (popupWindow[wp].opener == null) popupWindow[wp].opener = self;
  if (document.all || document.layers || document.getElementById) {
    if (borderless && borderless != "") {popupWindow[wp].resizeTo(popWidth,popHeight); popupWindow[wp].moveTo(leftPos, topPos);}
    if (alwaysOnTop && alwaysOnTop != "") {
    	ontopIntervalHandle = popupWindow[wp].setInterval("window.focus();", 50);
    	popupWindow[wp].document.body.onload = function() {window.setInterval("window.focus();", 50);}; }
    if (autoCloseTime && autoCloseTime > 0) {
    	popupWindow[wp].document.body.onbeforeunload = function() {
  			if (autoCloseTimeoutHandle) window.clearInterval(autoCloseTimeoutHandle);
    		window.onbeforeunload = null;	}
   		autoCloseTimeoutHandle = window.setTimeout("popupWindow["+wp+"].close()", autoCloseTime * 1000); }
  	window.onbeforeunload = function() {for (var i=0;i<popupWindow.length;i++) popupWindow[i].close();}; }
  document.MM_returnValue = (ignorelink && ignorelink != "") ? false : true;
}

(function() {

    function listDropdownSplit(list) {
        /* - split list of links so that links marked with the class "more" appear in a 'More' drop-down
        - enable keyboard operation by listening for keyboard tabbing to the 'More' link */

        // we need a controller list item, which contains a 'More' link and an empty (nested) list to hold the contents of the dropdown
        var controller = document.createElement("li"), a = document.createElement("a"), ul = document.createElement("ul");
        controller.className = "controller last";
        a.href = "javascript:void(0);";
        a.innerText = a.textContent = "More";
        controller.appendChild(a);
        controller.appendChild(ul);
        // append the new controller to the end of the original list
        list.appendChild(controller);
        // then append to the nested list within the controller all the items with the class "more"
        var items = list.getElementsByTagName("LI"), toMove = [];
        for (var i = 0, ii = items.length; i < ii; i++) {
            if (items[i].className.match(/(^| )more( |$)/)) {
                // we need to put the items we want to move into a helper array first, because if we moved them directly we'd change the number of items, stuffing up the loop
                toMove.push(items[i]);
            }
        }
        // run the append on all the items that we've previously identified as needing to be moved
        for (var i = 0, ii = toMove.length; i < ii; i++) {
            ul.appendChild(toMove[i]);
        }

        // define function to hide dropdown (once shown by keyboard operation)
        function closeDropdown() {
            controller.className = controller.className.replace(" focus", "");
            // once executed, unbind this handler from the window, as it is no longer required
            if (document.removeEventListener) document.removeEventListener("click", closeDropdown, false);
            else if (document.detachEvent) document.detachEvent("onclick", closeDropdown);
        }

        // enable keyboard operability by adding class "focus" to show dropdown when keyboard tabs to the 'More' link
        // we are looking for the link, which should be the controller first and only child element
        controller.firstChild.onfocus = function() {
            // check if the class "focus" already exists before running this function, because the user may have tabbed into the dropdown and then back to the controller link (in which case the dropdown will still be active)
            if (controller.className.match(/(^| )focus( |$)/)) return;
            controller.className += " focus";
            // then bind handler to watch for click event to close dropdown
            if (document.addEventListener) document.addEventListener("click", closeDropdown, false);
            else if (document.attachEvent) document.attachEvent("onclick", closeDropdown);
            // also listen for keyboard tabbing beyond the last list item
            // we want the last li in the dropdown, and then the link inside that li (it should be the first and only child element)
            var last = controller.getElementsByTagName("LI");
            last = last[last.length - 1].firstChild;
            if (last.addEventListener) {
                last.addEventListener("blur", closeDropdown, false);
            }
            else if (last.attachEvent) {
                last.attachEvent("onblur", closeDropdown);
            }
            // as well as keyboard tabbing back beyond the controller to the previous item
            // the previous item should be second last li in the original list (the last is the controller)
            // the first and only child element inside that previous item should be the link
            var prev = list.children;
            prev = prev[prev.length - 2];
            prev = prev.firstChild;
            if (prev.addEventListener) {
                prev.addEventListener("focus", closeDropdown, true);
            }
            else if (prev.attachEvent) {
                prev.attachEvent("onfocus", closeDropdown);
            }
        }

        // enable hover states in IE 6 (as it doesn't support li:hover CSS)
        // the check for whether the browser is IE 6 is not very accurate, but that's OK because even in other browsers, having these extra classes added won't hurt
        if (navigator.userAgent.match(/MSIE 6/)) {
            controller.onmouseover = function() { this.className += " hover" };
            controller.onmouseout = function() { this.className = this.className.replace(" hover", "") };
        }

        // attach class to indicate script has executed
        list.className += " scripted";

    }

    // run the above function listDropdownSplit on elements that require it
    if (window.addEventListener) {
        window.addEventListener("load", function() {
            listDropdownSplit(document.getElementById("whitestripDropdown"));
        }, false);
    }
    else if (window.attachEvent) {
        window.attachEvent("onload", function() {
            listDropdownSplit(document.getElementById("whitestripDropdown"));
        });
    }

})();

