/**
* --------------------------------------------------------------------
* jQuery-Plugin "pngFix"
* Version: 1.1, 11.09.2007
* by Andreas Eberhard, andreas.eberhard@gmail.com
*                      http://jquery.andreaseberhard.de/
*
* Copyright (c) 2007 Andreas Eberhard
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Changelog:
*    11.09.2007 Version 1.1
*    - removed noConflict
*    - added png-support for input type=image
*    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
*    31.05.2007 initial Version 1.0
* --------------------------------------------------------------------
* @example $(function(){$(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready
*
* jQuery(function(){jQuery(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready when using noConflict
*
* @example $(function(){$('div.examples').pngFix();});
* @desc Fixes all PNG's within div with class examples
*
* @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
* @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
* --------------------------------------------------------------------
*/

(function($)
{

	jQuery.fn.pngFix = function(settings)
	{

		// Settings
		settings = jQuery.extend({
			blankgif: 'blank.gif'
		}, settings);

		var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
		var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

		if (jQuery.browser.msie && (ie55 || ie6))
		{

			//fix images with png-source
			jQuery(this).find("img[@src$=.png]").each(function()
			{

				jQuery(this).attr('width', jQuery(this).width());
				jQuery(this).attr('height', jQuery(this).height());

				var prevStyle = '';
				var strNewHTML = '';
				var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
				var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
				var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
				var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
				var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
				var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
				if (this.style.border)
				{
					prevStyle += 'border:' + this.style.border + ';';
					this.style.border = '';
				}
				if (this.style.padding)
				{
					prevStyle += 'padding:' + this.style.padding + ';';
					this.style.padding = '';
				}
				if (this.style.margin)
				{
					prevStyle += 'margin:' + this.style.margin + ';';
					this.style.margin = '';
				}
				var imgStyle = (this.style.cssText);

				strNewHTML += '<span ' + imgId + imgClass + imgTitle + imgAlt;
				strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;' + imgAlign + imgHand;
				strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
				strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
				strNewHTML += imgStyle + '"></span>';
				if (prevStyle != '')
				{
					strNewHTML = '<span style="position:relative;display:inline-block;' + prevStyle + imgHand + 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;' + '">' + strNewHTML + '</span>';
				}

				jQuery(this).hide();
				jQuery(this).after(strNewHTML);

			});

			// fix css background pngs
			jQuery(this).find("*").each(function()
			{
				var bgIMG = jQuery(this).css('background-image');
				if (bgIMG.indexOf(".png") != -1)
				{
					var iebg = bgIMG.split('url("')[1].split('")')[0];
					jQuery(this).css('background-image', 'none');
					jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
				}
			});

			//fix input with png-source
			jQuery(this).find("input[@src$=.png]").each(function()
			{
				var bgIMG = jQuery(this).attr('src');
				jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
				jQuery(this).attr('src', settings.blankgif)
			});

		}

		return jQuery;

	};

})(jQuery);

$(document).ready(function()
{
	$(document).pngFix();
});

jQuery.fn.numeric = function(decimal, callback)
{
	callback = typeof callback == "function" ? callback : function(){};
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if(decimal && key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
				{
					allow = false;
				}
				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if(decimal && key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)
				{
					allow = true;
				}
			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function()
		{
			var val = jQuery(this).val();
			if(val != "")
			{
				var re = decimal ? new RegExp("^\\d+$|\\d*" + decimal + "\\d+") : new RegExp("^\\d+$");
				if(!re.exec(val))
				{
					callback.apply(this);
				}
			}
		}
	);
	return this;
}

jQuery.fn.datepicker = function()
{
	var _calendarFormat = "%m/%d/%Y";
	var obj = this.get(0);
	obj.readOnly = true;

	var table = document.createElement("table");
	table.cellPadding = 0;
	table.cellSpacing = 0;
	table.appendChild(document.createElement("tbody"));
	table.tBodies[0].appendChild(document.createElement("tr"));

	var td = document.createElement("td");
	td.appendChild(obj.cloneNode(true));
	table.rows[0].appendChild(td);

	var td = document.createElement("td");
	td.innerHTML = "&nbsp;";
	table.rows[0].appendChild(td);

	td = document.createElement("td");
	var img = document.createElement("img");
	img.src = "/Content/Design1/Images/calendar.gif";
	img.style.cursor = "pointer";
	img.onclick = function(ev)
	{
		return showCalendar(obj.id, _calendarFormat);
	}
	td.appendChild(img);
	table.rows[0].appendChild(td);

	var td = document.createElement("td");
	td.innerHTML = "&nbsp;";
	table.rows[0].appendChild(td);

	td = document.createElement("td");
	img = document.createElement("img");
	img.src = "/Content/Design1/Images/delete.gif";
	img.style.cursor = "pointer";
	img.onclick = function(ev)
	{
		document.getElementById(obj.id).value = "";
	}
	td.appendChild(img);
	table.rows[0].appendChild(td);

	obj.parentNode.appendChild(table);
	obj.parentNode.removeChild(obj);
}

var _objectRequestID;
var _mapWidth = 640;
jQuery.fn.ajaxify = function(ajaxLoaderID, updatePanelID)
{
	//if(this.get(0).tagName.toLowerCase() != "form")
	//	return;

	this.submit
	(
		function(e)
		{
			try
			{
				_objectRequestID = this.id;
				var ajaxRequest = document.createElement("input");
				ajaxRequest.name = "AjaxRequest";
				ajaxRequest.type = "hidden";
				ajaxRequest.value = "true";
				this.appendChild(ajaxRequest);

				var form = $("#" + this.id);
				var bounds = form.bounds();

				if (ajaxLoaderID)
				{
					var scrollTop = document.all ? document.documentElement.scrollTop : window.pageYOffset;
					var ajaxLoader = document.getElementById(ajaxLoaderID);
					ajaxLoader.style.position = 'absolute';
					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';
				}

				$.post(
					this.action,
					form.serialize(),
					function(resp)
					{
						var toUpdateObj = updatePanelID ? $("#" + updatePanelID) : $("#" + _objectRequestID).parent();

						// the response is a google map
						if (resp.toString().match("^GMAP"))
						{
							_estateData = eval("[" + resp.toString().replace(/GMAP/g, "") + "]");
							pageOnLoad();

							if (!document.getElementById("mapLayer"))
							{
								toUpdateObj.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>');
							}
						}
						else
						{
							toUpdateObj.html(resp);
						}

						if (ajaxLoaderID)
						{
							var ajaxLoader = document.getElementById(ajaxLoaderID);
							ajaxLoader.style.display = 'none';
						}
					},
					'html'
				);

				return false;
			}
			catch (e) { return true; }
		}
	);
}

jQuery.fn.bounds = function()
{
	var e = this.get(0);
	var height = this.height();
	var width = this.width();

	var left = 0;
	var top = 0;

	try
	{
		while (e.offsetParent)
		{
			left += e.offsetLeft;
			top += e.offsetTop;
			e = e.offsetParent;
		}
	}
	catch (e) { }

	left += e.offsetLeft;
	top += e.offsetTop;

	return { x: left, y: top, height: height, width: width };
}

function Validator()
{
	var ObjectID;
	var Text;
	var Type;
	var Regex;
	var Group;
	var Disabled;
};

var _validators = [];
jQuery.fn.requestValidation = function(text, type, regex, group)
{
	var val = new Validator();
	val.ObjectID = this.get(0).id;
	val.Text = text;
	val.Type = type;
	val.Regex = regex;
	val.Group = group;
	if(group)
		val.Disabled = true;
	_validators.push(val);
	
	this.get(0).onblur = function()
	{
		var val = GetValidator(this.id);
		if(val)
		{
			if(Validate($("#" + this.id), val) == '')
				this.style.borderColor = '';
		}
	}
}

function EnableValidationGroup(group)
{
	for(var i = 0; i < _validators.length; i++)
		if(_validators[i].Group == group)
			_validators[i].Disabled = false;
}

function DisableValidationGroup(group)
{
	for(var i = 0; i < _validators.length; i++)
		if(_validators[i].Group == group)
			_validators[i].Disabled = true;
}

function GetValidator(objID)
{
	for(var i = 0; i < _validators.length; i++)
	{
		if(objID == _validators[i].ObjectID)
			return _validators[i];
	}
	
	return null;
}

function Validate(obj, val)
{
	if(val.Disabled)
		return '';

	var message = '';
	
	if(val.Type == "RF")
	{
		if(obj.attr("value") == '' || (obj.attr("value") == '0' && obj.get(0).tagName.toLowerCase() == 'select'))
		{
			message += val.Text + "\n";
			obj.css("border-color", "#FF0000");
		}
	}
	else
		if(val.Type == "RE")
		{
			if(!obj.attr("value").match(val.Regex))
			{
				message += val.Text + "\n";
				obj.css("border-color", "#FF0000");
			}
		}
		else
			if (val.Type == "RC")
			{
				var msg = '';
				if ((obj.attr("value") == '' && obj.get(0).tagName.toLowerCase() != 'select') ||
					(obj.attr("value") == '0' && obj.get(0).tagName.toLowerCase() == 'select') ||
					(obj.get(0).tagName.toLowerCase() == 'select' && obj.attr('multiple') && obj.children().length == 0))
				{
					var otherobj = $("#" + val.Regex);
					if (otherobj)
					{
						if (otherobj.attr("value") == '' || (otherobj.attr("value") == '0' && otherobj.get(0).tagName.toLowerCase() == 'select'))
						{
							msg += val.Text + "\n";
							obj.css("border-color", "#FF0000");
							otherobj.css("border-color", "#FF0000");
						}
					}
					else
					{
						msg += val.Text + "\n";
						obj.css("border-color", "#FF0000");
					}
				}

				if (msg == '')
				{
					obj.css("border-color", "");
					var otherobj = $("#" + val.Regex);
					if (otherobj)
						otherobj.css("border-color", "");
				}
				else
					message += msg;
			}
		
	return message;
}

jQuery.fn.validate = function ()
{
	this.submit(
		function ()
		{
			return ValidateForm();
		}
	);
}

function ValidateForm()
{
	var message = '';
	var fobj = null;

	for (var i = 0; i < _validators.length; i++)
	{
		if (!_cancelValidation || _validators[i].ObjectID == "CaptchaCode")
		{
			var obj = $("#" + _validators[i].ObjectID);
			if (!obj)
			{
				continue;
			}

			var msg = Validate(obj, _validators[i]);
			if (msg != '' && !fobj)
			{
				fobj = obj;
			}
			message += msg;
		}
	}

	_cancelValidation = false;

	if (message != '')
	{
		alert(message);
		fobj.focus();
		return false;
	}

	return true;
}

var _cancelValidation = false;

jQuery.fn.removeValidatation = function ()
{
	_cancelValidation = true;
};

var _isIE6 = navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.toLowerCase().indexOf("msie 6.") > -1;

jQuery.fn.createSlideShow = function(maxWidth, maxHeight, slideText, moreDetailsID, textContainerID, minHeightTextContainer)
{
	var containerID = this.attr("id");

	this.css("width", maxWidth);
	this.css("height", maxHeight);
	this.attr("class", "slideshow");

	$('#' + containerID + ' IMG').css("position", "absolute").css("top", "0px").css("left", "0px").css({ opacity: 0.0 });
	$('#' + containerID + ' IMG:first').css({ opacity: 1.0 }).attr("class", "active");

	var supportsFade = true;
	if (_isIE6)
		supportsFade = false;

	if (slideText)
	{
		var imgs = $('#' + containerID + ' IMG');
		if (supportsFade)
		{
			for (var i = 0; i < imgs.length; i++)
			{
				$('#' + imgs.get(i).id.replace(/img/g, "sp")).css("position", "absolute").css("top", "0px").css("left", "0px").css({ opacity: 0.0 });
			}

			if (imgs.length > 0)
				$('#' + imgs.get(0).id.replace(/img/g, "sp")).css({ opacity: 1.0 });
		}
		else
		{
			for (var i = 0; i < imgs.length; i++)
				$('#' + imgs.get(i).id.replace(/img/g, "sp")).css("position", "absolute").css("top", "0px").css("left", "0px").css("display", "none");

			if (imgs.length > 0)
				$('#' + imgs.get(0).id.replace(/img/g, "sp")).css("display", "inline");
		}

		for (var i = 0; i < imgs.length; i++)
		{
			$('#' + imgs.get(i).id.replace(/img/g, "spCity")).css("display", "none");
			$('#' + imgs.get(i).id.replace(/img/g, "spType")).css("display", "none");
			$('#' + imgs.get(i).id.replace(/img/g, "spPrice")).css("display", "none");
		}

		if (imgs.length > 0)
		{
			$('#' + imgs.get(0).id.replace(/img/g, "spCity")).css("display", "inline");
			$('#' + imgs.get(0).id.replace(/img/g, "spType")).css("display", "inline");
			$('#' + imgs.get(0).id.replace(/img/g, "spPrice")).css("display", "inline");
		}

		if (textContainerID && minHeightTextContainer)
		{
			var height = 0;

			for (var i = 0; i < imgs.length; i++)
			{
				var textHeight = $('#' + imgs.get(i).id.replace(/img/g, "sp")).get(0).offsetHeight;
				if (height < textHeight)
					height = textHeight;
			}

			if (height > minHeightTextContainer)
			{
				if (_isIE6)
					$("#" + textContainerID).css("height", height + "px");
				else
					$("#" + textContainerID).css("min-height", height + "px");
			}
			else
				if (_isIE6)
				$("#" + textContainerID).css("height", minHeightTextContainer + "px");
		}
	}

	setInterval("slideSwitch('" + containerID + "', " + slideText + ", '" + moreDetailsID + "', " + supportsFade + ")", 3000);
}

function slideSwitch(containerID, slideText, moreDetailsID, supportsFade)
{
    var $active = $('#' + containerID + ' IMG.active');

    if ($active.length == 0) $active = $('#' + containerID + ' IMG:last');

    var $next = $active.next().length ? $active.next() : $('#' + containerID + ' IMG:first');

    $active.addClass('last-active');

    $next.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 1000, function()
        {
            $active.removeClass('active last-active');
        });

    if (slideText)
    {
    	if (supportsFade)
    	{
    		$('#' + $active.attr("id").replace(/img/g, "sp"))
			.animate({ opacity: 0.0 }, 1000, function() { });

    		$('#' + $next.attr("id").replace(/img/g, "sp"))
			.animate({ opacity: 1.0 }, 1000, function() { });
    	}
    	else
    	{
    		$('#' + $active.attr("id").replace(/img/g, "sp")).css("display", "none");
    		$('#' + $next.attr("id").replace(/img/g, "sp")).css("display", "inline");
    	}


    	$('#' + $active.attr("id").replace(/img/g, "spCity")).css("display", "none");
    	$('#' + $next.attr("id").replace(/img/g, "spCity")).css("display", "inline");

    	$('#' + $active.attr("id").replace(/img/g, "spType")).css("display", "none");
    	$('#' + $next.attr("id").replace(/img/g, "spType")).css("display", "inline");
    	
    	$('#' + $active.attr("id").replace(/img/g, "spPrice")).css("display", "none");
    	$('#' + $next.attr("id").replace(/img/g, "spPrice")).css("display", "inline");
    	

    	var cont = $('#' + containerID);
    	if (cont.attr("href") && $next.attr("link"))
    	{
    		cont.attr("href", $next.attr("link"));
    		if (moreDetailsID)
    			$('#' + moreDetailsID).attr("href", $next.attr("link"));
    	}
    }
}

var _ssBreak = false;
var _ssContainer;
var _ssContainerClone;
var _ssContainerWidth;
var _ssContainerCloneWidth;

jQuery.fn.createBeltSlideShow = function ()
{
	_ssContainer = this;

	addOnLoad(function ()
	{
		var containerID = _ssContainer.attr("id");
		var containerClone = _ssContainer.get(0).cloneNode(true);
		containerClone.id = containerID + "Clone";
		containerClone.style.left = '-20000px';
		_ssContainer.after(containerClone);
		_ssContainerClone = $("#" + containerID + "Clone");

		_ssContainer.hover(function () { _ssBreak = true; }, function () { _ssBreak = false; });
		_ssContainerClone.hover(function () { _ssBreak = true; }, function () { _ssBreak = false; });

		_ssContainerWidth = _ssContainer.bounds().width;
		_ssContainerCloneWidth = _ssContainerClone.bounds().width;

		setInterval("slideMove()", 30);
	});
}

function slideMove()
{
	if (_ssBreak)
	{
		return;
	}

    if ((parseInt(_ssContainer.css("left")) * -1) > _ssContainerWidth)
    	_ssContainer.css("left", parseInt(_ssContainerClone.css("left")) + _ssContainerCloneWidth);

    if ((parseInt(_ssContainerClone.css("left")) * -1) > _ssContainerCloneWidth)
    	_ssContainerClone.css("left", parseInt(_ssContainer.css("left")) + _ssContainerWidth);

    _ssContainer.css("left", (parseInt(_ssContainer.css("left")) - 2));
    _ssContainerClone.css("left", (parseInt(_ssContainerClone.css("left")) - 2));
}

jQuery.fn.scrollIntoView = function()
{
	$('html,body').animate({ scrollTop: this.offset().top - 20 }, 500);
}

jQuery.fn.labelTextBox = function ()
{
	var elem = $(this);
	var origValue = elem.attr("value");

	elem.click(function ()
	{
		if (elem.attr("value") == origValue)
		{
			elem.attr("value", "");
		}
	});

	elem.blur(function ()
	{
		if (elem.attr("value") == "")
		{
			elem.attr("value", origValue);
		}
	});
}
