jQuery(document).ready(function() {
	
	jQuery("#location").blur(function() {
		var elm = jQuery(this);
		if (/^\s*$/.test(elm.val())) elm.val(elm[0].title).addClass('blur');
	}).blur();
	
	jQuery("#location").focus(function(s) {
		var elm = jQuery(this);
		if (elm.val() == elm[0].title) elm.val("").removeClass('blur');
	});
	
	jQuery(".ajax_submit #range").change(function() {
		var view = gup('view');
		if (view == 'city') return;
		var url = build_url("");
		if (url) { window.location.hash = build_hash(""); getData(url); }
	});
	
	jQuery(".ajax_submit #facility_filter input:checkbox").click(function() {
		var url = build_url("");
		if (url) { window.location.hash = build_hash(""); getData(url); } 
	});
	
	jQuery(".ajax_submit #features_filter input:checkbox").click(function() {
		var url = build_url("");
		if (url) { window.location.hash = build_hash(""); getData(url); }
	});
	
	jQuery("#results input:checkbox").click(addRequestInfoToForm);
	jQuery("#req_info_detail_page input:checkbox").click(addRequestInfoToForm);
	
	jQuery(".list-footer a").click(handle_list_footer_click);
	
	jQuery("#zs_submit").click(function() {
		var loc = jQuery('#location');
		var val = loc.val();
		if (/^\s*$/.test(val) || val == loc[0].title) {  
			alert('Please enter Zip Code or City, State');
			loc.focus();
			return false;
		}
	});
	
	jQuery("#show_phone_link").click(function() {
		var el = jQuery("#phone_box");
		if (!el.is(':visible')) {
			el.show('slow');
			jQuery.get(this.href); // tracking the click
		}
		return false;
	});
	
	jQuery("#req_all_cur_page").click(function() {
		var chkboxes = jQuery("#results input:checkbox");
		if (this.checked && chkboxes.length > 0) {
			chkboxes.attr('checked', true);
			chkboxes.trigger('click');
		}
	});
	
});

function handle_list_del_click(url) {
	var hash = unescape(url.split('#')[1]);
	var vals = hash.split('_');
	var id = vals[0];
	var name = vals[1];
	var del = confirm("Do you really want to delete this community: " + name + '?');
	if (del) {
		var el = jQuery(".requested_box input[value='" + id + "']");
		if (el.length) { el.prev().remove(); el.remove(); del_req_listings_added_cookie(id); }
		var chkbox = jQuery("input[value^='" + id + "_']");
		if (chkbox.length > 0) {
			chkbox.attr('checked', false);
			chkbox.removeAttr('disabled');
		}
	}
}

function del_req_listings_added_cookie(id) {
	var cv = jQuery.cookie('req_listings_added');	
	var ids = cv.split('|');
	var ids_2 = new Array();
 	for (var i = 0; i < ids.length; i++) {
		if (ids[i] != id) ids_2.push(ids[i]);
	}	
	if (ids_2.length) {
		cv = ids_2.join('|');
        	jQuery.cookie('req_listings_added', cv, { path: '/' });
        } else {
		jQuery.cookie('req_listings_added', '', { path: '/', expires: -1 });
	}
}

// handle request info click from google map
function handle_request_info_click(url) {
	var hash = url.split('#')[1];
	var vals = hash.split('_');
	var id = vals[0];
	var chkbox = jQuery("input[value^='" + id + "_']");
	if (chkbox.length > 0) {
		chkbox.attr('checked', true);
		chkbox.trigger('click');
	}
}

function handle_list_footer_click() {
	var hash = build_hash("");
	var r = this.href.match(/start\=(\d+)/);
	if (r != null) {
		hash += '/p_' + r[1];
	} else {
		// do nothing
	}
	window.location.hash = hash;
	jQuery.cookie('last_query', this.href.replace('ajaxsearch', 'zipsearch'), { path: '/' });
	var url = this.href;
	if (!url.match('ajaxsearch')) { url += '&task=ajaxsearch'; }
	getData(url); 
	return false; 
}

// build the ajax url for search
function build_url(loc) {
	var _loc;
	if (loc.length == 0) {
		var loc_elm;
		loc_elm = jQuery('#location');
		_loc = loc_elm.val();
		var re = /^\s*$/;
		if (re.test(_loc) || _loc == loc_elm[0].title) {
			alert('Please enter Zip Code or City, State.');
			jQuery('#location').focus();
			return false;
		}
	} else {
		_loc = loc;
	}
	
	var url;
	
	var range = jQuery('#range').val();
	var types = new Array();
	var features = new Array();
	jQuery('#facility_filter input:checkbox').each(function() { if (this.checked) types.push( jQuery(this).val()); });
	jQuery('#features_filter input:checkbox').each(function() { if (this.checked) features.push( jQuery(this).val()); });
	url = '/index.php?option=com_zipsearch&task=ajaxsearch&location=' + _loc + '&range=' + range;
	for (var i = 0; i < types.length; i++) {
		url += '&type[]=' + types[i];
	}
	for (var i = 0; i < features.length; i++) {
		url += '&f[]=' + features[i];
	}
	//url += '&operator=' + jQuery('#operator').val();
	
	return url;
}

function build_hash(loc) {
	var hash = '';
	
	if (loc.length == 0) {
		_loc = jQuery('#location').val();
		if (_loc.replace(/\s/g, "") == "") {
			return "";
		}
	} else {
		_loc = loc;
	}
	
	var range = jQuery('#range').val();
	var types = new Array();
	var features = new Array();
	jQuery('#facility_filter input:checkbox').each(function() { if (this.checked) types.push( jQuery(this).val()); });
	jQuery('#features_filter input:checkbox').each(function() { if (this.checked) features.push( jQuery(this).val()); });
	
	hash += 'l_' + _loc.replace(/ /, '+') + '/r_' + range;
	
	if (types.length) {
		hash += '/t_';
		for (var i = 0; i < types.length; i++) {
			hash += types[i] + ',';
		}
		hash = hash.slice(0, -1);
	}
	
	if (features.length) {
		hash += '/f_';
		for (var i = 0; i < features.length; i++) {
			hash += features[i] + ',';
		}
		hash = hash.slice(0, -1);
	}
	
	return hash;
}

function getData(url) {	
	//alert(url);
	add_ajax_loading_overlay();
	
	jQuery.cookie('last_query', url.replace('ajaxsearch', 'zipsearch'), { path: '/' });
	
	jQuery.get(url,
			   { }, 
			   function(xml) { 
				   process(xml);
			   }
	);
}

function process(data) {
	//alert(data);
	if (data == 'error') {
		return;
	}
	
	var xmldoc;
	
	if (window.ActiveXObject) {
		xmldoc = new ActiveXObject("Microsoft.XMLDOM");
		xmldoc.async = "false";
		xmldoc.loadXML(data);
	} else {
		var parser = new DOMParser();
		xmldoc = parser.parseFromString(data,'text/xml');
	}

	var link_id, link_name, link_desc;
	var address, city, state, zip;
	var lon, lat;
	var distance;
	var facility_types;
	var thumbnail;
	var featured;
	
	var total = xmldoc.getElementsByTagName("total")[0].childNodes[0].nodeValue;
	
	var link_ids = xmldoc.getElementsByTagName("link_id");
	var link_descs = xmldoc.getElementsByTagName("desc");
	var link_names = xmldoc.getElementsByTagName("link_name");
	var addresses = xmldoc.getElementsByTagName("address");
	var cities = xmldoc.getElementsByTagName("city");
	var states = xmldoc.getElementsByTagName("state");
	var zips = xmldoc.getElementsByTagName("zip");
	var lons = xmldoc.getElementsByTagName("lon");
	var lats = xmldoc.getElementsByTagName("lat");
	var distances = xmldoc.getElementsByTagName("distance");
	var types = xmldoc.getElementsByTagName("types");
	var thumbnails = xmldoc.getElementsByTagName("thumbnail");
	var featureds = xmldoc.getElementsByTagName("featured");
	
	var count = link_ids.length;
	
	// expire cookie last_query
	if (count == 0) {
		jQuery.cookie('last_query', '', { path: '/', expires: -1 });
	}
	
	// generate html content
	var imgTagArr = new Array();
	var imgTag;
	var html = '<div id="results">' + "\n";
	html += '<div id="requestInfoError" />' + "\n";
	html += '<div id="requestInfoThankyou" />' + "\n";
	for (var i = 0; i < count; i++) {
		link_id = link_ids[i].childNodes[0].nodeValue;
		link_name = link_names[i].childNodes[0].nodeValue.replace(/^\s+|\s+$/g,"");
		link_name = ucwords(strtolower(link_name));
		address = addresses[i].childNodes[0].nodeValue;
		city = cities[i].childNodes[0].nodeValue;
		state = states[i].childNodes[0].nodeValue;
		zip = zips[i].childNodes[0].nodeValue;
		lon = lons[i].childNodes[0].nodeValue;
		lat = lats[i].childNodes[0].nodeValue;
		distance = distances[i] == undefined ? '' : distances[i].childNodes[0].nodeValue;
		facility_types = types[i].childNodes[0] == undefined ? '' : types[i].childNodes[0].nodeValue;
		link_desc = link_descs[i].childNodes[0] == undefined ? '' : link_descs[i].childNodes[0].nodeValue;
		thumbnail = thumbnails[i] == undefined ? '' : thumbnails[i].childNodes[0].nodeValue;
		featured = featureds[i].childNodes[0].nodeValue;
		
		url = '/index.php?option=com_mtree&Itemid=36&lang=en&task=viewlink&link_id=' + link_id;
		html += '<div class="listing_summary">' + "\n";
		html += '<div class="results_box_top">' + "\n";
		html += '<div class="results_box_top_holder">' + "\n";
		html += '<span class="request_info_title_check"><input type="checkbox" name="rid[]" value="' + link_id + '_' + escape(link_name) + '"';
		if (isLinkAdded(link_id)) {
			html += ' checked="checked" disabled="disabled"';
		}
		html +=' /><label for="rid[]">Request Info</label>' + "\n";
		html +='<span class="editlinktip hasTip" title="&lt;div class=&quot;tooltip_pink&quot;&gt;&lt;div class=&quot;results_box_top&quot;&gt;&lt;div class=&quot;results_box_top_holder&quot;&gt;Request Info from ' + link_name + ' &lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;results_box_middle&quot;&gt;&lt;div class=&quot;results_box_middle_holder&quot;&gt;Check this box to request information from ' + link_name + '. Complete the form above to send your information to your selected communities.&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;results_box_bottom&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;" style="text-decoration: none; color: rgb(51, 51, 51);"><img src="/includes/js/ThemeOffice/info_pink.png" style="text-decoration: none; color: rgb(51, 51, 51);"></span></span>'+ "\n";
		html += '<span class="result_title"><a href="' + url + '">' + link_name + '</a></span>';
		html +='</div></div>' + "\n";
		html += '<div class="results_box_middle';
		if (featured == '1') html += ' featured_middle';
		html += '">' + "\n";
		html += '<div class="results_box_middle_holder">' + "\n";
		html += ucwords(strtolower(address)) + '<br />';
		html += ucwords(strtolower(city)) + ', ' + state + ' ' + zip + '<br /><br />';
		if (distance.length) {
			html += 'Distance: ' + distance + ' miles<br /><br />';
		} 
		if (facility_types.length) {
			facility_types = facility_types.replace(/\|/g, ', ');
			html += 'Community types: ' + facility_types + '<br /><br />';
		}
		if (thumbnail.length) {
			html += '<img src="' + thumbnail + '"></img>';
			imgTag = '<img style="float: left;" src="' + thumbnail + '"></img>';
			imgTagArr[link_id] = imgTag; 
		}
		if (link_desc.length) {
			html += '<p>' + link_desc;
			if (link_desc.length > 110) {
				html += '...';
			}
			html += '</p><br />';
		}
		html += '</div></div>' + "\n";
		html += '<div class="results_box_bottom"></div>' + "\n";
		html += '</div>';
	}
	html += '</div>';
	
	
	// pagination
	if (count > 0) {
		//var footer = xmldoc.getElementsByTagName("footer")[0].childNodes[0].nodeValue.replace(/ajaxsearch/g, '');
		var footer = xmldoc.getElementsByTagName("footer")[0].childNodes[0].nodeValue;
		html += "\n" + footer;
	} else { // help message
		html += '\n<p>We\'re sorry. There are no communities that meet your search criteria. We recommend trying a broad zip-code area search with no specific features requested. Once the search results appear, you can begin narrowing your choices by selecting individual community features.</p>\n';
	}
	
	// end html generation
	
	// update html content
	//jQuery('#results_count').empty().append('<h3>Found ' + total + (total == 1 ? ' community' : ' communities</h3>'));
	
	jQuery("#search_results").empty().append(html);
	jQuery("#results input:checkbox").click(addRequestInfoToForm);
	jQuery(".list-footer a").click(handle_list_footer_click);

	JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false});

	window.scrollTo(0, 0);

	remove_ajax_loading_overlay();
	
	// update map
	// addOverlay() doesn't work well after removeOverlay()
	// get everything again

	map.clearOverlays();
	
	// set default center
	map.setCenter(new GLatLng(38, -97), 3, G_NORMAL_MAP);
	//map.savePosition();
	
	if (count > 0) {
		bounds = new GLatLngBounds();

		var description;
		var l_id;
		var l_name;
		for (var i = 0; i < count; i++) {	
			lon = lons[i].childNodes[0].nodeValue;
			lat = lats[i].childNodes[0].nodeValue;
			if (lon == 0 && lat == 0) continue; // handle facilites which don't have geocode
			point = new GLatLng(lat, lon);
			l_id = link_ids[i].childNodes[0].nodeValue;
			l_name = ucwords(strtolower(link_names[i].childNodes[0].nodeValue));
			//l_name = escapeQuotes(l_name);
			l_name = escape(l_name);
			
			description = '';
			if (imgTagArr[l_id]) {
				description += escapeQuotes(imgTagArr[l_id]);
			}
			description += /* escapeQuotes(link_names[i].childNodes[0].nodeValue) + '<br />' */
						 /*+*/ escapeQuotes(ucwords(strtolower(addresses[i].childNodes[0].nodeValue))) + '<br />'
						 + escapeQuotes(ucwords(strtolower(cities[i].childNodes[0].nodeValue))) + ', ' 
						 + states[i].childNodes[0].nodeValue + ' ' 
						 + zips[i].childNodes[0].nodeValue + '<br />';
			description += '<br /><a href="#' + l_id + '_' + l_name +
			'" onclick="handle_request_info_click(this.href); return false;">request info</a>';
			marker = createMarker(point, description, ucwords(strtolower(link_names[i].childNodes[0].nodeValue)));
			map.addOverlay(marker);
			bounds.extend(point);
		}
	
		centerAndSave(map, bounds);

	}
}

function escapeQuotes(str) {
	str = str.replace("'", "\'");
	str = str.replace('"', '\"');
	return str;
}

// assume "this" is the checkbox checked
function addRequestInfoToForm() {
	var cookie_name = 'req_listings_added';
	var cookie_value;
	if (this.checked) {
		//this.disabled = true;
		jQuery(this).attr("disabled", true);
		var val = unescape(jQuery(this).val());
		var vals = val.split('_');
		if (!isLinkAdded(vals[0])) {
			html = '<span class="req_listing_added"><a title="Remove ' + vals[1] + ' from your contact queue." href="#' + escape(val) + '" onclick="handle_list_del_click(this.href); return false;">delete</a>' + vals[1] + ' has been added. ';
			html += '<br /></span>';
			html += '<input type="hidden" name="link_id[]" value="' + vals[0] + '" />';
			cookie_value = jQuery.cookie(cookie_name);
			cookie_value = cookie_value == null ? vals[0] : cookie_value + '|' + vals[0];
			jQuery.cookie(cookie_name, cookie_value, { path: '/' });
			jQuery('.requested_box').append(html);
		};
		jQuery('#requestInfoError').empty();
		jQuery('#requestInfoThankyou').empty();
	}
}

function isLinkAdded(link_id) {
	var match = false;
	jQuery("input[name='link_id[]']").each(function() { 
		if (jQuery(this).val() == link_id) {
			match = true;
			return; // exit each loop
		}
	});
	return match;
}

function add_ajax_loading_overlay() {
	jQuery('#search_results_container').block({ 
        message: '<div align="center" style="font-family:verdana"><br /><img src="/images/ajax-loader.gif" /><h3 style="font-weight:normal">Loading Results</h3></div>', 
        css: { },
        overlayCSS: { 
        	backgroundColor: '#FFF',
        	opacity: '0.7'
        }
    });
}

function remove_ajax_loading_overlay() {
	jQuery('#search_results_container').unblock(); 
}

function sleep(milliseconds) { 	 	 
	var start = new Date().getTime(); 	 	 
	for (var i = 0; i < 1e7; i++) { 	 	 
		if ((new Date().getTime() - start) > milliseconds){ 	 	 
			break; 	 	 
		} 	 	 
	} 	 	 
} 	 	 
	 	 	 
function ucwords(str) { 	 	 
	return (str+'').replace(/^(.)|\s+(.)/g, function ( $1 ) { return $1.toUpperCase( ); } ); 	 	 
} 	 	 
		 	 	 
function strtolower(str) { 	 	 
	return (str+'').toLowerCase(); 	 	 
} 

