﻿function IsSilverlightInstalled()
{
//    var isSilverlightInstalled = false;
//    try
//    {
//        //check on IE
//        try
//        {
//            var slControl = new ActiveXObject('AgControl.AgControl');
//            isSilverlightInstalled = true;
//        }
//        catch (e)
//        {
//            //either not installed or not IE. Check Firefox
//            if (navigator.plugins["Silverlight Plug-In"])
//            {
//                isSilverlightInstalled = true;
//            }
//        }
//    }

//    catch (e) { }

	//    return isSilverlightInstalled;
	return true;
}

function CloseSilverlightAlert()
{
	document.getElementById("divSilverlightAlert").style.display = 'none';
	createCookie("SilverlightAlertClosed", "true");
}

function IsSilverlightAlertVisible()
{
	var cookie = readCookie("SilverlightAlertClosed");
	if(cookie && cookie == "true")
		return false;
		
	return true;
}

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 var 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;
}

function showSelectionMap(ddlid, url)
{
	var div = document.createElement('div');
	div.id = 'divMapContainer';
	div.style.width = '640px';
	div.style.height = '507px';
	div.style.position = 'absolute';
	div.style.border = '1px solid #CCC';
	div.style.backgroundColor = '#FFF';
	div.style.top = '150px';
	div.style.left = (screen.width - parseFloat(div.style.width)) / 2 + 'px';
	div.setAttribute('ddl', ddlid);

	var img = document.createElement('img');
	img.src = '/Content/Design2/Images/close_map.png';
	img.style.marginTop = '5px';
	img.style.marginRight = '5px';
	img.style.cursor = 'pointer';
	img.style.styleFloat = 'right';
	img.style.cssFloat = 'right';
	img.onclick = function(ev)
	{
		document.body.removeChild(document.getElementById('divMapContainer'));
	};
	div.appendChild(img);

	var divmsg = document.createElement('div');
	divmsg.id = 'divMapMessage';
	divmsg.style.styleFloat = 'left';
	divmsg.style.cssFloat = 'left';
	divmsg.style.marginTop = '5px';
	divmsg.style.marginLeft = '5px';
	divmsg.style.color = '#7F0000';
	divmsg.style.fontWeight = 'bold';
	div.appendChild(divmsg);
		
	var ifr = document.createElement('iframe');
	ifr.style.width = '640px';
	ifr.style.height = '480px';
	ifr.setAttribute('frameborder', '0');
	ifr.frameBorder = 0;
	ifr.style.border = '0px none';
	ifr.style.marginTop = '5px';

	ifr.src = url + '?mapState=' + _mapState;

	div.appendChild(ifr);

	document.body.appendChild(div);

	$("#divMapContainer").scrollIntoView();
}

function appendNewOption(ddlID, text, value, objID)
{
	var newOption = document.createElement('option');
	newOption.text = text;
	newOption.value = value;
	var select = document.getElementById(ddlID);

	try
	{
		select.add(newOption, null); // standards compliant; doesn't work in IE
	}
	catch (ex)
	{
		select.add(newOption); // IE only
	}

	if (objID)
	{
		var obj = document.getElementById(objID);
		if (obj.value == '')
			obj.value = value;
		else
			obj.value = obj.value + "," + value;
	}
}

function setSelectionMapMessage(msg)
{
	var divmsg = document.getElementById('divMapMessage');
	if (divmsg)
		divmsg.innerHTML = msg;
}

var _mapState;

function setSelectionMapMessageZipList(zipList, mapState)
{
	_mapState = mapState;
	
	var div = document.getElementById('divMapContainer');
	if (div)
	{
		var ddlid = div.getAttribute('ddl');
		if (ddlid)
		{
			var html = $('#' + ddlid).html();
			for (var i = 0; i < zipList.length; i++)
			{
				html += '<option value="' + zipList[i] + '">' + zipList[i] + '</option>';
			}

			$('#' + ddlid).html(html);

			var valobj = document.getElementById(ddlid + 'Value');
			if (valobj)
			{
				var strzips = valobj.value == "" ? "" : valobj.value + ",";
				for (var i = 0; i < zipList.length; i++)
					strzips += i == 0 ? zipList[i] : ',' + zipList[i];
				
				valobj.value = strzips;
			}
		}
	}

	document.body.removeChild(document.getElementById('divMapContainer'));
}

function deleteSelectedValue(id)
{
	var obj = document.getElementById(id);
	if (obj.selectedIndex >= 0)
		obj.remove(obj.selectedIndex);

	var valobj = document.getElementById(id + 'Value');
	if (valobj)
	{
		var strvals = '';
		for (var i = 0; i < obj.options.length; i++)
			strvals += i == 0 ? obj.options[i].value : ',' + obj.options[i].value;

		valobj.value = strvals;
	}
}

function RefreshImage(img, url)
{
	$.ajax({
			url: url,
			type: 'POST',
			data: {},
			success: function(data, textStatus) 
			{
				document.getElementById(img).src = data;
			}
		});
	}

function GetModuleBlockBounds()
{
	var ret = '';

	$("[BlockID]").each(
		function(index)
		{
			var b = $(this).bounds();
			ret += (ret == '' ? '' : '|') + $(this).attr("BlockID") + "=" + b.x + "," + b.y + "," + b.width + "," + b.height;
		});

	return ret;
}

function getClientHeight()
{
	var myHeight = 0;
	//Non-IE
	if (typeof (window.innerWidth) == 'number')
		myHeight = window.innerHeight;
	else
		//IE 6+ in 'standards compliant mode' 
		if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
			myHeight = document.documentElement.clientHeight;
		else
			//IE 4 compatible
			if (document.body && (document.body.clientWidth || document.body.clientHeight))
				myHeight = document.body.clientHeight;

	return myHeight;
}

function getClientWidth()
{
	var myWidth = 0;
	//Non-IE
	if (typeof (window.innerWidth) == 'number')
		myWidth = window.innerWidth;
	else
		//IE 6+ in 'standards compliant mode' 
		if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
			myWidth = document.documentElement.clientWidth;
		else
			//IE 4 compatible
			if (document.body && (document.body.clientWidth || document.body.clientHeight))
				myWidth = document.body.clientWidth;

	return myWidth;
}

function OnAjaxRequestBegin(request)
{
	if (typeof (_validateFormOnAjaxRequestBegin) != 'undefined' && _validateFormOnAjaxRequestBegin)
	{
		if (!ValidateForm())
		{
			return false;
		}
	}

	if (queryString("SearchRequest"))
	{
		var url = request.get_request().get_url();
		url = url + (url.indexOf("?") < 0 ? "?" : "&");

		var qs = window.location.search.substring(1).split('&');
		for (i = 0; i < qs.length; i++)
		{
			var param = qs[i].split('=');
			if (param[0].toLowerCase() != "searchrequest" &&
				param[0].toLowerCase() != "pagenumber" &&
				param[0].toLowerCase() != "isajaxrequest" && 
				param.length == 2)
			{
				url = url + param[0] + '=' + param[1] + '&';
			}
		}
		url = url.substring(0, url.length - 1);

		request.get_request().set_url(url);
	}

	var scrollTop = document.all ? document.documentElement.scrollTop : window.pageYOffset;
	var ajaxLoader = document.getElementById('Loading');
	var bounds = $('#' + request.get_updateTarget().id).bounds();
	ajaxLoader.style.position = 'absolute';
	if (bounds.width == 0)
	{
		bounds.width = getClientWidth();
	}
	ajaxLoader.style.left = (bounds.x + (bounds.width / 2) - (ajaxLoader.offsetWidth / 2)) + 'px';
	ajaxLoader.style.top = scrollTop + (screen.height / 2 - 200) - (ajaxLoader.offsetHeight / 2) + 'px';
	ajaxLoader.style.display = document.all ? 'inline' : ajaxLoader.tagName.toLowerCase() == 'table' ? 'table' : 'block';

	// Update browser history - For AJAX Pagination
	var searchFor = "pageNumber=";
	var pageNumber = getPageNumber(searchFor, request.get_request()._url);
	if (pageNumber != "")
	{
		var windowLocation = window.location.href.toString();
		if (windowLocation.indexOf("#") >= 0)
			windowLocation = windowLocation.substring(0, windowLocation.indexOf("#"));

		window.location.href = windowLocation + "#pageNumber=" + pageNumber;
	}
}

function getPageNumber(searchFor, requesturl)
{	
	var pnindex = requesturl.toString().indexOf(searchFor);
	if (pnindex < 0)
		return "";

	var pageNumber = requesturl.toString().substring(pnindex + searchFor.length, requesturl.toString().length);
	if (pageNumber.indexOf("&") >= 0)
		pageNumber = pageNumber.substring(0, pageNumber.indexOf("&"));
	if (isNaN(pageNumber))
		return "";

	return pageNumber;
}

function OnAjaxRequestComplete(response)
{
	// The list is a Google Map
	if (response.get_data().match("^GMAP"))
	{
		if (!document.getElementById("mapLayer"))
		{
			$('#' + response.get_updateTarget().id).html('<div id="mapLayer" style="position: relative; font-family: Arial; font-size: 14px;"><div id="options" style="width: ' + _mapWidth + 'px; height: 480px;"></div><div id="map" style="width: ' + _mapWidth + 'px; height: 480px;"></div></div>');
		}
	
		_estateData = eval("[" + response.get_data().replace(/GMAP/g, "").replace(/,\\/g, ",") + "]");
		pageOnLoad();

		response.set_response(null);
	}
		
	var ajaxLoader = document.getElementById('Loading');
	ajaxLoader.style.display = 'none';

	if (typeof (window.onload) == 'function')
	{
		setTimeout('executeWindowOnLoad()', 300);
	}

	if (document.getElementById("ListContainer"))
	{
		$("#ListContainer").scrollIntoView();
	}
}

function executeWindowOnLoad()
{
	var execute = true;

	var listContainer = document.getElementById('ListContainer');
	if (!listContainer)
		return;
	
	// Check if every image has loaded
	var listImages = listContainer.getElementsByTagName("img");
	for(var i = 0; i < listImages.length; i++)
	{
		if (!listImages[i].complete)
			execute = false;
	}

	if (execute)
		window.onload();
	else
		setTimeout('executeWindowOnLoad()', 200);
}

String.prototype.visualLength = function()
{
	var ruler = document.getElementById('ruler');
	ruler.whiteSpace = 'nowrap';
	ruler.innerHTML = this;
	return ruler.offsetWidth;
}

String.prototype.minVisualLength = function()
{
	var ruler = document.getElementById('ruler');
   	ruler.whiteSpace = 'normal';
   	ruler.innerHTML = this;
   	return ruler.offsetWidth;
}

function fixDesign2Menu()
{
	fixMenu(925, 500, 800);
}

function fixDesign3Menu()
{
	fixMenu(657, 500, 655);
}

function fixMenu(width, stretchToWidthMin, stretchToWidthMax)
{
	var padding = 10;
	
	// Set container widths depending on the width of the string it contains
	var totalStringWidth = 0;
	var totalMenuItems = 0;
	var totalWidth = width;
	var totalLetters = 0;

	$(".MenuItemContainer").each(function(i)
	{
		var html = $(this).children("span:first").children("a:first").html();
		if (html != null)
		{
			totalLetters += html.length;
			
			totalStringWidth += html.visualLength();

			totalMenuItems++;
		}
	});

	totalWidth -= 2 * totalMenuItems;

	$(".MenuItemContainer").each(function(i)
	{
		var html = $(this).children("span:first").children("a:first").html();
		if (html != null)
		{
			var width = parseInt(html.visualLength() * totalWidth / totalStringWidth) + 1;
			var minWidth = html.minVisualLength() + 1;

			$(this).css("width", (parseInt(minWidth > width ? minWidth : width)) + "px");
		}
	});
	
	$(".MenuItemContainer").each(function(i)
	{
		var currentPadding = this.offsetWidth - $(this).children("span:first").children("a:first,table:first").get(0).offsetWidth;

		if (currentPadding > padding)
		{
			this.style.width = (this.offsetWidth - currentPadding + padding) + 'px';
		}
	});
	
	// Force the menu to stretch depending on the number of letters in it's items
	var stretchToWidth;
	if (totalLetters < 55)
		stretchToWidth = stretchToWidthMin;
	else
		stretchToWidth = stretchToWidthMax;
	var filledWidth = 0;
	totalWidth = width;
	$(".MenuItemContainer").each(function(i)
	{
		if (this.id != "MenuFiller")
			filledWidth += this.offsetWidth;
	});
	
	var verticalPadding = parseInt((stretchToWidth - filledWidth) / totalMenuItems);
	
	filledWidth = 0;
	$(".MenuItemContainer").each(function(i)
	{
		if (this.id != "MenuFiller")
		{
			this.style.width = (this.offsetWidth + verticalPadding) + 'px';
			filledWidth += this.offsetWidth;
		}
	});
	
	var filler = document.getElementById("MenuFiller");
	filler.style.width = (totalWidth - filledWidth - totalMenuItems) + 'px';
	
	// Calculate maximum height of the text
	var maxHeight = 20;
	
	$(".MenuItemTextContainer").each(function(i)
	{
		var bounds = $(this).bounds();

		if (bounds.height > maxHeight)
			maxHeight = bounds.height;
	});
	
	// Set the height on the containers
	$(".MenuItemContainer").each(function(i)
	{
		$(this).css("height", (maxHeight + padding) + "px");		
	});

	$(".MenuItemContainer").each(function(i)
	{
		$(this).children("img:first").css("height", $(this).css("height"));
		$(this).children("img:first").css("width", $(this).css("width"));
	});
	
	// Set the text in the middle, or whereever the "text-align" property may request
	$(".MenuItemTextContainer").each(function(i)
	{
		var obj = $(this);
		var height = obj.bounds().height;
		var parentWidth = obj.parent().bounds().width;
		var width = obj.bounds().width;
		
		if (obj.css("text-align"))
		{			
			if (obj.css("text-align") == "right")
				obj.css("left", (parentWidth - width) + "px");

			if (obj.css("text-align") == "center")
				obj.css("left", ((parentWidth - width) / 2) + "px");

			if (obj.css("text-align") == "left")
				obj.css("left", "0px");
		}
		else
			obj.css("left", ((parentWidth - width) / 2) + "px");

		obj.css("top", parseInt((maxHeight - height) / 2 + (padding / 2)) + "px");
	});	

	if (typeof (posmg) == 'function')
	{
		posmg();
	}
}

function queryString(ji)
{
	hu = window.location.search.substring(1);
	gy = hu.split('&');
	for (i = 0; i < gy.length; i++)
	{
		ft = gy[i].split('=');
		if (ft[0] == ji)
		{
			return ft[1];
		}
	}
}

function applyGenerateDesignToLinks()
{
	var gd = queryString("generateDesign");
	if (typeof (gd) != 'undefined' && gd != '' && gd == 'false')
	{
		$('a').each(function ()
		{
			if (this.href.toLowerCase().indexOf("javascript:") < 0)
			{
				this.href = this.href.indexOf("?") >= 0 ? this.href + '&generateDesign=false' : this.href + '?generateDesign=false';
			}
		});

		$('form').each(function ()
		{
			if (this.action.toLowerCase().indexOf("generatedesign") < 0)
			{
				this.action = this.action.indexOf("?") >= 0 ? this.action + '&generateDesign=false' : this.action + '?generateDesign=false';
			}
		});
	}
}

function applyWidthToLinks()
{
    var gd = queryString("width");
	if (typeof (gd) != 'undefined' && gd != '')
	{
		$('a').each(function ()
		{
			if (this.href.toLowerCase().indexOf("javascript:") < 0)
			{
				this.href = this.href.indexOf("?") >= 0 ? (this.href + '&width=' + gd) : (this.href + '?width=' + gd);
			}
		});

		$('form').each(function ()
		{
		    if (this.action.toLowerCase().indexOf("width") < 0)
		    {
		        this.action = this.action.indexOf("?") >= 0 ? (this.action + '&width=' + gd) : (this.action + '?width=' + gd);
		    }
		});
	}
}

function applyApplyStyleToLinks()
{
	var gd = queryString("applyStyle");
	if (typeof (gd) != 'undefined' && gd != '' && gd == 'true')
	{
		$('a').each(function ()
		{
			if (this.href.toLowerCase().indexOf("javascript:") < 0)
			{
				this.href = this.href.indexOf("?") >= 0 ? this.href + '&applyStyle=true' : this.href + '?applyStyle=true';
			}
		});

		$('form').each(function ()
		{
			if (this.action.toLowerCase().indexOf("applystyle") < 0)
			{
				this.action = this.action.indexOf("?") >= 0 ? this.action + '&applyStyle=true' : this.action + '?applyStyle=true';
			}
		});
	}
}

function checkListPage()
{
	if (window.location.href.indexOf("#") >= 0)
	{
		// For AJAX Pagination
		var windowLocation = window.location.href.toString();
		windowLocation = windowLocation.replace(/\?pageNumber\=\d*/i, "");
		windowLocation = windowLocation.replace(/\&pageNumber\=\d*/i, "");
		window.location.href = windowLocation.indexOf("?") >= 0 ? windowLocation.replace(/#/g, "&") : windowLocation.replace(/#/g, "?");
	}
}

function addOnLoad(nextOnLoad)
{
	var prevOnLoad = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = nextOnLoad;
	} 
	else
	{
		window.onload = function ()
		{
			prevOnLoad();
			nextOnLoad();
		}
	}
}

var _debug = false;
window.onerror = function (errorMsg, errorUrl, errorLine)
{
	if (_debug)
	{
		alert(errorMsg + '\n' + 'Url: ' + errorUrl + '\n' + 'Line: ' + errorLine);
	}

	return true;
}
