var is_ie6 = (window.external && typeof window.XMLHttpRequest == "undefined");

var do_trace = (location.href.toString().indexOf('debug=trace') > 1);
var trace_div = null;
function trace(msg) {
	if (!do_trace) {
		return;
	}
	if (!trace_div) {
		trace_div = document.createElement('div');
		with (trace_div.style) {
			position = 'absolute';
			width = '200px';
			height = '400px';
			backgroundColor = '#fff';
			fontSize = '10px';
			borderWidth = '1px';
			borderStyle = 'solid';
			borderColor = '#ccc';
			padding = '3px';
			top = '10px';
			right = '10px';
			zIndex = '1010';
			overflow= 'auto';
		}
		document.body.appendChild(trace_div);
	}
	var el = document.createElement('div');
	el.innerHTML = msg;
	trace_div.appendChild(el);
}

function bind(self, method) {
	var __self = self;
	var __method = method;
	return function() {
		__method.apply(__self, arguments);
	}
}

function ie6png(doit) {
	if (!doit) {
		// call the fix only for IE 6
		if (is_ie6) {
			window.setTimeout(function() { ie6png(true); }, 1);
		}
		return;
	}
	node_visitor(ie6png_fix_bg);
}

function node_visitor(fn, node) {
	if (!node) {
		node = document.getElementsByTagName('BODY')[0];
	}
	// not an actual element, but most likely a text node
	if (!node.tagName || node.nodeType == 3) {
		return;
	}
	if (fn(node)) {
		return;
	}
	var children = node.childNodes;
	for(var i = children.length - 1; i > -1; i--) {
		node_visitor(fn, children[i]);
	}
}

function ie6png_fix_bg(node) {
	var bg = null, src = null, method = null;
	var cStyle = node.currentStyle;
	// fix background images
	if (
		cStyle
		&& (bg = cStyle.backgroundImage)
		&& bg.indexOf('.png') > 0
	)
	{
		// strip url("")
		src = bg.substring(5, bg.length - 2);
		var method = (
				cStyle.backgroundRepeat &&
				cStyle.backgroundRepeat.indexOf('repeat-') == 0
			) ? 'scale' : 'crop';
		node.style.backgroundImage = "none";
	}
	// fix images
	if (node.src && node.src.indexOf('.png') > 0) {
		// trace(node.src);
		method = 'crop';
		src = node.src;
		node.src = '/media/layout/blank.gif';
	}
	if (method && src) {
		var filter = " progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src='" + src + "', sizingMethod='" + method + "')";
		// trace(filter);
		node.style.filter = filter;
	}
	return false;
};

function isLoggedIn() {
	return document.cookie.match(/__actstatus=1/) ? true : false;
}  

var with_listing;

function load() {
	if (!document.cookie.match(/__firsturl/)) {
		document.cookie =
			'__firsturl=' + encodeURIComponent(document.location) + '; path=/';
	}
	ie6png();
	createPopupModalDiv();
	createPopupDiv();
	with_listing = location.search.match(/show\=(\d+)/);
	if (with_listing) {
		with_listing = with_listing[1];
	} else {
		with_listing = 0;
	}
	if (location.toString().match(/\/page\/search/)) {
		$.getJSON('/ajax/init', {with_listing: with_listing}, init_properties);
	}
	if (location.toString().match(/\/page\/mortgage_calculator/)) {
		init_calculator();
	}
}

var calculator_data = { pm: 0, i: 0, d: 0, y: 0 };

function init_calculator() {
	trace('init calculator');
	$('#mc_principal,#mc_down_payment,#mc_interest,#mc_duration,#mc_duration').
		keyup(update_calculator).
		change(update_calculator).
		focus(show_calculator_description);
	$('#mc_principal').focus();
}

function show_calculator_description() {
	$('.mc_description').hide(true);
	$('#' + this.id + '_desc').show(true);
}

var calculator_request = null;
function update_calculator() {
	var data = {
		 pm: $('#mc_principal').val(),
		 i: $('#mc_interest').val(),
		 d: $('#mc_down_payment').val(),
		 y: $('#mc_duration').val()
	};
	if (
		calculator_data.pm != data.pm ||
		calculator_data.i != data.i ||
		calculator_data.d != data.d ||
		calculator_data.y != data.y
	) {
		calculator_data = data;
		if (calculator_request) {
			var ex;
			try {
				trace('aborting');
				calculator_request.abort();
				trace('success');
			} catch (ex) {
				// do nothing
			}
		}
		calculator_request = jQuery.ajax({
			url: '/ajax/mortgagecalc', dataType: 'html', data: calculator_data,
			complete: function(res, status) {
				if ( status == "success" || status == "notmodified" ) {
					var price = res.responseText.replace(/<script(.|\s)*?\/script>/g, "");
					$('#mc_home_price').html(price);
					if (price == '$0') {
						$('#mc_search_link').hide();
					} else {
						$('#mc_search_link').show();
						$('#mc_search_link').attr('href', '/page/search?start_price=' + price);
					}
					calculator_request = null;
				}
			}
		});
	}
}

var _properties;

function init_properties(data) {
	if (data) {
		_properties = data;
	}
	applyHover('#save_search');
	applyHover('#sign_in_search');
	setProfileControls();
	map_init();
}

function setProfileControls() {
	if (isLoggedIn()) {
		$('#save_search').unbind().click(saveSearch);
		$('#sign_in_search').hide();
	} else {
		$('#sign_in_search').show();
		$('#sign_in_search').click(function() {
			showPopup('save_search'); });
		$('#save_search').unbind().click(function() {
			showPopup('save_search', true); });
	}
}

function saveSearch() {
	$.getJSON('/ajax/savesearch', {}, saveSearchSuccess);
}

function saveSearchSuccess(data) {
	trace('saveSearchSuccess: ' + data); 
	if (data && data.valid) {
		showHide('#saved_search_message');
	}
}

var show_hide_timeouts = {};

function showHide(selector, custom_timeout) {
	if (!custom_timeout) {
		custom_timeout = 10000;
	}
	if (show_hide_timeouts[selector]) {
		clearTimeout(show_hide_timeouts[selector]);
	}
	$(selector).show('fast');
	show_hide_timeouts[selector] = 
		setTimeout(function() { $(selector).hide('slow'); }, custom_timeout);
}

function getP(key) {
	var val;
	if (val = _properties[key]) {
		return val + '';
	}
	return 0;
}

function applyHover(name) {
	$(name).mouseover(function() { opacity(this, 0.6); });
	$(name).mouseout(function() { opacity(this, 1); });
}

var map_request = null;
var map_obj = null;
var map_node = null;
var base_icon;
var base_icon_top;
var base_size;

function iconFactory(type) {
	var icon = new GIcon();
    /*
	icon.image = is_ie6 ?
		'/media/images/icon_map_home' + type + '_ie6.gif' :
		'/media/images/icon_map_home' + type + '.png';
    */
    icon.image = is_ie6 ?
        '/media/images/icon_map_home_top_ie6.gif' :
        '/media/images/icon_map_home_top.png';
	icon.transparent = null;
	icon.shadow = null;
	size = new GSize(16, 15);
	icon.iconSize = base_size;
	icon.shadowSize = null;
	var anchor = new GPoint(10, 9);
	icon.iconAnchor = anchor;
	icon.infoWindowAnchor = anchor;
	icon.infoShadowAnchor = null;
	return icon; 
}

function map_init() {
	map_node = document.getElementById('search_map');
	// debug
	// return;
	if (map_node && GBrowserIsCompatible()) {
    
		// configure custom icon
		base_icon = iconFactory('');
		base_icon_top = iconFactory('_top');
		
		// create map
		map_obj = new GMap2(map_node);
		map_obj.addControl(new GLargeMapControl3D());
		map_obj.addControl(new GMapTypeControl());
		map_obj.addControl(new GScaleControl());
		map_obj.addControl(new GOverviewMapControl());
		
		map_obj.setCenter(
			new GLatLng(getP('map_center_lat'), getP('map_center_lng')),
			getP('map_zoom') * 1
		);
		GEvent.addListener(map_obj, 'moveend', map_updated);
		GEvent.addListener(map_obj, 'movestart', function() {
			current_id = null;
			$('#map_info_popup').hide(); 
		});
		
		var match;
		if(
			(match = location.href.match(/start_price=([^&]+)/)) &&
			match.length == 2
		) {
			match = match[1].replace(/\D+/g, '');
			if (!match) {
				match = 0;
			} else {
				match = match * 1;
			}
		} else {
			match = null;
		}
		
		$('#price_min').selectOptions(match ? match : getP('price_min'), 1);
		$('#price_max').selectOptions(match ? match : getP('price_max'), 2);
		$('#has_pool').each(
			function() {
				this.checked = (getP('has_pool') == 1 ? true : false);
			}
		);
		$('#has_picture').each(
			function() {
				this.checked = (getP('has_picture') == 1 ? true : false);
			}
		);
		$('#has_garage').each(
			function() {
				this.checked = (getP('has_garage') == 1 ? true : false);
			}
		);
		$('#min_baths').selectOptions(getP('min_baths'));
		$('#min_beds').selectOptions(getP('min_beds'));
		$('#min_sq_ft').selectOptions(getP('min_sq_ft'), 1);
		$('#max_age').selectOptions(getP('max_age'));
		
		var types = getP('types').split(',');
		$.each(types, function() {
			$("input[value*='" + this + "']").get(0).checked = true;
		});
		
		map_obj.clearOverlays();
		map_updated(true);
        
        $('#mc_zoom_in').click(function() { map_obj.zoomIn() });
        $('#mc_zoom_out').click(function() { map_obj.zoomOut() });

        $('#mc_show_satellite').click(function() { 
            map_obj.setMapType(G_HYBRID_MAP);
            $(this).hide();
            $('#mc_show_standard').get(0).style.display = 'block';
        });
        $('#mc_show_standard').click(function() {
            map_obj.setMapType(G_NORMAL_MAP);
            $(this).hide();
            $('#mc_show_satellite').get(0).style.display = 'block';
        });
		
	}
}

function Position(x, y) {
	this.x = x;
	this.y = y;
}
Position.prototype = Position;
Position.prototype.toString =
	function() {
		return '(' + this.x + ', ' + this.y + ')';
	};

function getAbsolutePosition(node, to_node) {
    var y = 0, x = 0;
    if (!to_node) {
    	to_node = null;
    }
    do {
		y += node.offsetTop || 0;
		x += node.offsetLeft || 0;
		node = node.offsetParent;
	} while (node != to_node);
	return new Position(x, y);
}

function safe_unload() {
	if (map_node && GBrowserIsCompatible()) {
		GUnload();
	}
}

function map_updated(is_first_search) {
	trace('called map_updated()');
	if (map_request && !document.all && map_request.abort) {
		map_request.abort();
		map_request = null;
	}
	// delay a bit to wait for all updates
	setTimeout(function() { perform_update(is_first_search) }, 25);
}

function perform_update(is_first_search) {
	trace('called perform_update()');
	current_id = null;
	$('#map_info_popup').hide();
	$.each(handlers, function() { GEvent.removeListener(this); });

	var center = map_obj.getCenter();
	
	var bounds = map_obj.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var lngMin = southWest.lng();
	var lngMax = northEast.lng();
	var latMin = southWest.lat();
	var latMax = northEast.lat();
	
	var priceMin = $('#price_min').val();
	var priceMax = $('#price_max').val();
	
	var hasPicture = $('#has_picture:checked').val() ? 1 : 0;
	var hasPool = $('#has_pool:checked').val() ? 1 : 0;
	var hasGarage = $('#has_garage:checked').val() ? 1 : 0;
	
	var minBaths = $('#min_baths').val();
	var minBeds = $('#min_beds').val();
	
	var minSqFt = $('#min_sq_ft').val();
	var maxAge = $('#max_age').val();
	
	var types = [];
	$("input[name='types']:checked").each(function() {
		types.push(this.value);
	});
	types = types.join(',');
	
	trace('running AJAX request ...');
	map_request = $.getJSON(
		"/ajax/search?",
		{
			lng_min: lngMin, lng_max: lngMax,
			lat_min: latMin, lat_max: latMax,
			price_min: priceMin, price_max: priceMax,
			map_center_lat: center.lat(),
			map_center_lng: center.lng(),
			map_zoom: map_obj.getZoom(),
			has_picture: hasPicture,
			has_pool: hasPool,
			min_baths: minBaths,
			min_beds: minBeds,
			min_sq_ft: minSqFt,
			has_garage: hasGarage,
			max_age: maxAge,
			show_advanced: 1,
			types: types,
			is_first: is_first_search ? '1' : '0' 
		},
		finish_update
	);
}

var handlers = [];
var pic_url = 'http://medialaxe.rapmls.com/tarmls/listingpics/tmbphoto/0';
var ie_first_time = true;

function finish_update(data) {
	trace('... done; called finish_update()');
	map_obj.clearOverlays();

	var msg = '';
	
	trace(' - data.found: ' + data.found);
	if (data.found && data.results) {
    	$('#prop_count').text(data.found);
    	var found = new Number(data.found.replace(/\D+/g, ''));
    	var showing = data.results.length;
    	if (showing < found) {
    		msg = '<span class="small"><br />Only top ' + showing +
    		' shown; make filter more specific or zoom in to match fewer homes.</span>';
    	}
    	if (found < 5) {
			msg = '<span class="small"><br />To see more, change filter below or zoom out.</span>';    	
    	}
    	var top_tier = Math.round(showing / 5 + 0.5);
    	if (top_tier < 1) {
    		top_tier = 1;
    	}
    	var use_icon;
    	var results = data.results;
    	trace(' - results.length: ' + results.length);
    	for(var i = results.length - 1; i > -1; i--) {
    		generateMarker(
    			results[i],
    			(i < top_tier) ? base_icon_top : base_icon
    		);
		}
		trace(' - done adding markers');
		if (document.all && ie_first_time) {
			trace(' - TRYING IE DOUBLE DRAW');
			ie_first_time = false;
			setTimeout(function() { finish_update(data) }, 10);
			return;
		}
    }
    $('#prop_msg').html(msg);

    map_request = null;
}

function generateMarker(result, use_icon) {
	var marker = new GMarker(
		new GLatLng(result[1], result[2]), { icon: use_icon }
	);
	marker._zmls_id = result[0];
	marker._zmls_price = result[3];
	marker._zmls_pictures = 1 * result[4];
	marker._zmls_bedrooms = 1 * result[5];
	marker._zmls_bathrooms = 1 * result[6];
	marker._zmls_sq_ft = result[7];
	marker._zmls_has_pool = 1 * result[8];
	handlers.push(GEvent.addListener(marker, 'mouseover', function(e) {
		schedule_prop_info(result[0], marker, e);
		return false;
	}));
	handlers.push(GEvent.addListener(marker, 'click', function(e) {
		showPropertyDetail(marker);
		return false;
	}));
	if (with_listing == result[0]) {
		with_listing = false;
		setTimeout(function() { showPropertyDetail(marker); }, 10);
	}
	map_obj.addOverlay(marker);
}

var prop_info_popup = null;
var map_info_beds = null;
var map_info_baths = null;
var map_info_sqft = null;
var map_info_has_pool = null;
var actual_image = null;
var current_id = null;
var instruction_msg = null;
var popup_hide_timeout = null;


var prop_info_timeout = null;
function schedule_prop_info(listing_id, marker, e) {
	if (prop_info_timeout) {
		clearTimeout(prop_info_timeout);
	}
	prop_info_timeout =
		setTimeout(function() { update_prop_info(listing_id, marker, e); }, 500);
	return false;
}

function update_prop_info(listing_id, marker, e) {
	if (current_id == listing_id) {
		return;
	}
	current_id = listing_id;
	if (!actual_image) {
		actual_image = document.getElementById('info_image_actual');
	}
	var old_handler = actual_image.onclick;
	delete old_handler;
	if (!prop_info_popup) {
		prop_info_popup = $('#map_info_popup');
		map_info_beds = $('#map_info_beds');
		map_info_baths = $('#map_info_baths');
		map_info_sqft = $('#map_info_sqft');
		map_info_has_pool = $('#map_info_has_pool');
        instruction_msg = $('#instruction_msg');
	}
	
	$(prop_info_popup).
		click(function() { showPropertyDetail(marker); return false; });

	$('#info_price').text('$' + marker._zmls_price);
	
	if (marker._zmls_pictures) {
		var url = marker._zmls_id.toString();
		url = pic_url + url.substring(url.length - 2) + '/' + url + '.jpg'
		clearImageLoaders();
		loadImage(actual_image, url);
		actual_image.style.borderWidth = '1px';
	} else {
		actual_image.src = '/media/images/no_picture.gif';
		actual_image.style.borderWidth = '0px';
	}
	map_info_beds.html(marker._zmls_bedrooms);
	map_info_baths.html(marker._zmls_bathrooms);
	map_info_sqft.html(marker._zmls_sq_ft);
	
	if (marker._zmls_has_pool == 1) {
		$(map_info_has_pool).show();
	} else {
		$(map_info_has_pool).hide();
	}
    
    if (popup_hide_timeout) {
        clearTimeout(popup_hide_timeout);
    }
	
    $(instruction_msg).hide('slow');
	$(prop_info_popup).show('slow');
    
    popup_hide_timeout = setTimeout(function() {
        $(prop_info_popup).hide('slow');
        $(instruction_msg).show('slow');
    }, 25000); 
	
}

var spin_image = null;
var current_loaders = {};

function loadImage(img_node, src) {
	var current;
	if (current = current_loaders[src]) {
		current.onload = null;
		current.src = null;
		delete current_loaders[src];
		delete current;
	}
    
    $(img_node).hide();
    
    /*
	if (!spin_image) {
		spin_image = document.createElement('IMG');
		spin_image.src = '/media/layout/waitspin.gif';
	}
    img_node.src = spin_image.src;
    */
	
	var new_image = document.createElement('IMG');
	
	new_image.onload = function() {
		if (this.src) {
			img_node.src = this.src;
            $(img_node).show();
		}
		delete current_loaders[this.src];
		this.onload = null;
	}
    
	new_image.src = src;
	current_loaders[src] = new_image;
}

function clearImageLoaders() {
	var current, src;
	for(src in current_loaders) {
		if (src && (current = current_loaders[src]) && (current.onload)) {
			current.onload = null;
			delete current_loaders[src];
			delete current;
		}
	}
	current_loaders = {};
}

function showPropertyDetail(marker) {
	showPopup('property_detail', marker);
	return false;
}

var popup_modal_div;
var popup_obj = { container: null, visible: false };

var popup_handlers = {};
var popup_handlers_width = {};

function showPopup(handler_name, data) {
	if (handler_name && popup_handlers[handler_name]) {
		if (popup_handlers_width[handler_name]) {
			popup_obj.content_container.style.width =
				popup_handlers_width[handler_name] + 'px';
		} 
		document.body.appendChild(popup_modal_div);
		if (is_ie6) {
			$('select').hide();
		}
		if (!popup_obj.show_me) {
			popup_obj.show_me = function() {
				$(popup_obj.container).show();
			}
		}
		// updatePopupPos();
		trace('calling popup handler: ' + handler_name);
		popup_handlers[handler_name].handle(popup_obj.content_container, data);  
	}
}

function PopupHandler(name, width) {
	popup_handlers[name] = this;
	popup_handlers_width[name] = width;
}
PopupHandler.prototype.handleInternal = function() {};
PopupHandler.prototype.handle = function(container, data) {
	this._container = container;
	this._data = data;
	this._fields = {};
	trace('data: ' + this._data);
	this.handleInternal(data);
}

var PropertyDetailHandler = new PopupHandler('property_detail', 700);

var load_request = false;

PropertyDetailHandler.handleInternal = function(marker) {
	if (load_request) {
		try {
			load_request.abort();
		} catch (ex) {
			// do nothing
		}
	}
	trace('listing id: ' + marker._zmls_id);
	load_request = $(this._container).load(
		'/ajax/getcontent?template=property_detail&listing=' + marker._zmls_id,
		null, bind(this, this.initializeForm));
}

PropertyDetailHandler.initializeForm = function() {
	applyHover('#ok_button');
	$('#ok_button').click(hidePopup);
	popup_obj.show_me();
	// forcing width for IE
	popup_obj.container.style.width = 800 + 'px';
	updatePopupPos();
	fixIEPopupDrawScrolled();
}

function fixIEPopupDrawScrolled(doit) {
	if (doit) {
		// hack for IE positioning
		var style = popup_obj.container.style;
		style.display = 'none';
		style.display = 'block';
	} else {
		setTimeout(function() { fixIEPopupDrawScrolled(true); }, 100);
	}
}

var UserProfileHandler = new PopupHandler('save_search', 500);

UserProfileHandler.handleInternal = function(doSave) {
	trace('save search when done? ' + doSave);
	$(this._container).load(
		'/ajax/getcontent?template=user_profile', null,
		bind(this, this.initializeForm));
}

UserProfileHandler.initializeForm = function() {
	applyHover('#save_profile');
	applyHover('#sign_in_profile');
	$('#sign_in_profile').click(bind(this, this.doSignIn));
	$('#save_profile').click(bind(this, this.doSaveProfile));
	popup_obj.show_me();
	updatePopupPos();
	fixIEPopupDrawScrolled();
	assignValidator(this, 'profile_email', 'email');
	assignValidator(this, 'profile_password', 'required_password');
	assignValidator(this, 'profile_email_confirm', 'confirm_email', 'profile_email');
	assignValidator(this, 'profile_password_confirm', 'confirm_password', 'profile_password');
	assignValidator(this, 'profile_name', 'name');
	assignValidator(this, 'profile_phone', 'phone');
	var feedback = $('textarea#profile_feedback'); 
	feedback.keyup(function() {
		var value = feedback.val().toString(); 
		if (value.length > 500) {
			feedback.val(value.substring(0, 500));
		}
	});
	this._fields['profile_feedback'] = feedback;
}

UserProfileHandler.doSaveProfile = function() {
	trace('group: ' + this.validateSignInGroup());
	trace('email c: ' + this.isValid('profile_email_confirm'));
	trace('password c: ' + this.isValid('profile_password_confirm'));
	trace('name: ' + this.isValid('profile_name'));
	trace('phone: ' + this.isValid('profile_phone'));
	if (
		this.validateSignInGroup() && this.isValid('profile_email_confirm') &&
		this.isValid('profile_password_confirm') &&
		this.isValid('profile_name') && this.isValid('profile_phone')
	) {
		$.getJSON('/ajax/saveprofile',
			{
				email: this._fields['profile_email'].val(),
				password: this._fields['profile_password'].val(),
				email_confirm: this._fields['profile_email_confirm'].val(),
				password_confirm: this._fields['profile_password_confirm'].val(),
				name: this._fields['profile_name'].val(),
				phone: this._fields['profile_phone'].val(),
				feedback: this._fields['profile_feedback'].val()
			},
			bind(this, this.checkSaveProfile)
		);
	} else {
		alert('Please make sure there are no errors in your input.');
	}
}

UserProfileHandler.checkSaveProfile = function(data) {
	trace(data);
	if (data.valid) {
		setProfileControls();
		hidePopup();
	} else {
		alert(
			'Profile could not be saved.\n' + 
			'Please review your input for errors\n' +
			'and try again.');
	}
}

UserProfileHandler.doSignIn = function() {
	if (this.validateSignInGroup()) {
		$.getJSON('/ajax/signin',
			{
				email: this._fields['profile_email'].val(),
				password: this._fields['profile_password'].val(),
				feedback: this._fields['profile_feedback'].val()
			},
			bind(this, this.checkSignIn)
		);
	} else {
		alert('A valid e-mail address and password are required.');
	}
}

UserProfileHandler.checkSignIn = function(data) {
	trace(data);
	if (data.valid) {
		setProfileControls();
		hidePopup();
	} else {
		alert(
			'E-mail address/password combination unknown.\n' + 
			'If you are a new user, please fill out the New User profile.\n' +
			'If you already registered, please call me so I restore access.');
	}
}

UserProfileHandler.isValid = function(field) {
	return this._fields[field].attr('_xIsValid') == '1';
}

UserProfileHandler.validateSignInGroup = function() {
	return (
		this.isValid('profile_email') &&
		this.isValid('profile_password'));
}

function assignValidator(formHandler, field, validator, other_field) {
	hideValidationIcon(field);
	var input = $('input#' + field);
	var other_input = other_field ? $('input#' + other_field) : null;
	input.attr('_xIsValid', '1');
	formHandler._fields[field] = input;
	if (validator) {
		input.blur(function() {
			$.getJSON('/ajax/validate',
				{
					validator: validator,
					value: input.val(),
					other: other_input ? other_input.val() : ''
				},
				function(data) {
					if (data.valid) {
						input.attr('_xIsValid', '1');
						hideValidationIcon(field);
					} else {
						input.attr('_xIsValid', '0');
						showValidationIcon(field);
					}
				}
			);
		});
	}
}

function showValidationIcon(field) {
	$('img#' + field + '_error').show();
}

function hideValidationIcon(field) {
	$('img#' + field + '_error').hide();
}

function updatePopupPos() {
	if (!popup_obj || !popup_obj.container) {
		return;
	}

	var style = popup_obj.container.style;

	var popup_height = document.body.offsetHeight;

	var client_height =
		(document.documentElement && document.documentElement.clientHeight) ?
			document.documentElement.clientHeight : popup_height;
	if (client_height > popup_height) {
		popup_height = client_height;
	}
	popup_modal_div.style.width = document.body.offsetWidth + 'px';
	popup_modal_div.style.height = popup_height + 'px';
	
	style.zoom = 0.9;
	style.zoom = 1;
	
	style.left =
		Math.max(0, Math.round(
			(document.body.offsetWidth - popup_obj.container.offsetWidth) / 2
			)) + 'px';
			
	var scrollTop =
		(document.body && document.body.scrollTop) ?
			document.body.scrollTop :
		(document.documentElement && document.documentElement.scrollTop) ?
			document.documentElement.scrollTop :
		(window.pageYOffset) ?
			window.pageYOffset : 0;
				 
	style.top = (scrollTop + Math.max(0, Math.round(
			(client_height - popup_obj.container.offsetHeight) / 2
			))) + 'px';
}

function hidePopup() {
	$(popup_obj.container).hide();
	document.body.removeChild(popup_modal_div);
	if (is_ie6) {
		$('select').show();
	}
}

function createPopupModalDiv() {
	popup_modal_div = document.createElement('div');
	with (popup_modal_div.style) {
		position = 'absolute';
		backgroundColor = '#ccc';
		top = '0';
		left = '0';
		zIndex = '1000';
		overflow = 'hidden';
	}
	opacity(popup_modal_div, 0.35);
}

function createPopupDiv() {
	popup_obj.container = document.getElementById('popup');
	var popup_close_div = document.getElementById('popup_close_div');
	$(popup_close_div).click(function() { hidePopup(); });
	applyHover(popup_close_div);
	popup_obj.content_container = document.getElementById('popup_content');
}

var re = /alpha\(opacity=\d+\)/;
var opacity = function(element, op) {
	if (typeof element == "string") {
		element = E(element);
	}
	element.style.opacity = op;
    element.style.MozOpacity = op;
	element.style.KhtmlOpacity = op;
	if (document.all) {
	    op = Math.round(op * 100);
	    var nf = '';
	    if (element.currentStyle && element.currentStyle.filter) {
	        nf = element.currentStyle.filter.replace(re, '');
	    }
	    if (op < 99) {
	        element.style.filter = "alpha(opacity=" + op + ") " + nf;
	    } else {
	        element.style.filter = nf;
	    }
	}
}

$.fn.selectOptions = function(value, type)
{
	type = type ? type : 0;
	var smallest_diff = 99999999;
	var final_select = null;
	var next_select = null;
	trace(value);
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != 'select') return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			var diff;
			for(var i = 0; i < oL; i++)
			{
				diff = o[i].value - value;
				o[i].selected = false;
				if (
					Math.abs(diff) < Math.abs(smallest_diff) &&
					(!type || (diff < 0))
				) {
					smallest_diff = diff;
					final_select = o[i];
					if ((type == 2) && (i + 1 < oL)) {
						next_select = o[i + 1];
					} 
				}
			}
			if (final_select) {
				if (next_select) {
					next_select.selected = true;
				} else {
					final_select.selected = true;
				}
				
			}
		}
	);
	return this;
};

if (window.addEventListener)
{
	window.addEventListener("resize", updatePopupPos, false);
	window.addEventListener("scroll", updatePopupPos, false);
}
else if (document.documentElement && document.documentElement.addEventListener)
{
	document.documentElement.addEventListener("resize", updatePopupPos, false);
	document.documentElement.addEventListener("scroll", updatePopupPos, false);
}
else if (document.addEventListener)
{
	document.addEventListener("resize", updatePopupPos, false);
	document.addEventListener("scroll", updatePopupPos, false);
}
else if (window.attachEvent)
{
	window.attachEvent("onresize", updatePopupPos);
	window.attachEvent("onscroll", updatePopupPos);
} else {
	window.onresize = updatePopupPos;
	window.onscroll = updatePopupPos;
}

function echo(list) {
    var el = null;
	for (i = 0; i < list.length; i++) {
		el = list[i];
		if (el) {
			document.write(el);
		}
	}
}

function echo_m(e_list, id, subject) {
	document.write('<a href="mailto:');
	echo(e_list);
	if (subject) {
		document.write('?subject=' + subject);
	}
	document.write('" id="' + id + '">');
    echo(e_list);
    document.write('</a>');
}
