//<![CDATA[
// *** functions ***
	// changes theme/type
	function changeDrinkType(which_type){
		var background_color = [];
		background_color = ['#000', '#d4d4cb', '#eeeeec'];
		$('body').animate({ 
			backgroundColor: background_color[which_type] 
		}, 'slow').attr("class","type-" + which_type);
		$('header img').fadeOut("slow");
		$('#header-' + which_type).fadeIn("slow");
	};

	// input defaults
	function inputDefaults(which_search_input) {
		var input_default = $(which_search_input).attr("title");
		$(which_search_input).val(input_default);
		$(which_search_input).focus(function(){
			if($(this).val() == input_default){
				$(this).val('');		
			}
		});
		$(which_search_input).blur(function(){
			if($(this).val() == ''){
				$(this).val(input_default);		
			}
		});
	};

	// pagination
	function pagination(selector,pages,current){
		$(selector + " .page-numbers li").each(function(i){
			// reset pages
			$(this).removeClass("p-hide");
			if(current == '1' && i == '0' || pages == '1' && i == '0' || pages == '1' && i=='6' || current == '5' && i == '6' || i > pages && i < 6){
				$(this).addClass("p-hide");
			}	
			if(pages > 1 && pages == current){
				$(selector + " .page-numbers li.p-6").addClass("p-hide");
			}
		});
	};

	// filter function to grab establishments 
	function grabFilters(which_form,pg){
		//grab values from filters to search
		var zfilters = [];

		zfilters['areas'] = $('#area-values-' + which_form).val();	
		zfilters['day'] = $('#current-day').val();	
		zfilters['type'] = $('#current-type').val();	
		zfilters['keyword'] = $('#keyword-' + which_form).val();

		if(pg == 'y'){
			zfilters['page'] = $('#current-page-' + which_form).val();
			zfilters['total'] = $('#number-of-pages-' + which_form).val();
		}
		else{
			zfilters['page'] = "1";
			zfilters['total'] = "";
			$('.page-numbers a').removeClass("current");
			$('.page-numbers li.p-1 a').addClass("current");
		}
		if(zfilters['keyword'] == 'Live Search'){
			zfilters['keyword'] = "";
		};

		// communicate with server to pull data
		$.getJSON(
			"RestServer.php?action=search&q=" + zfilters['keyword'] + "&n=" + zfilters['areas'] + "&d=" + zfilters['day'] + "&t=" + zfilters['type'] + "&p=" + zfilters['page'] + "&tp=" + zfilters['total'] + "",
			function(data){
			// define google map point, clear overlay ready to repopulate
				map.clearOverlays();
            		var point; 
            		var total_no_of_pages = data.pages;
            		var current_page = data.currpage;

					$('#current-page-' + which_form).attr("value",current_page);
					$('#number-of-pages-' + which_form).attr("value",total_no_of_pages);
					pagination('#specials-events',total_no_of_pages,current_page);
					pagination('#map-view',total_no_of_pages,current_page)

					// clear table	
					$('#results-' + which_form + ' tbody tr').removeClass("rec");
					$('#results-' + which_form + ' tbody tr td.c-1').text("");
					$('#results-' + which_form + ' tbody tr td.c-2 span.name').removeAttr("id");
					$('#results-' + which_form + ' tbody tr td.c-2 span').text("");
					$('#results-' + which_form + ' tbody tr td.c-2 em').text("");
					$('#results-' + which_form + ' tbody tr td.c-2 div').text("");
					$('#results-' + which_form + ' tbody tr td.c-3').text("");

					map.setZoom(12);
					map.panTo(new GLatLng(data.maplat,data.maplng));

					var count_introanddesc, count_offset, count_offset_d, count_intro, count_desc, count_intro_span, count_desc_span, full_desc;

					// populate table	
					$.each(data.listings,function(i,listing){
						$('#r-' + which_form + '-' + i + '').addClass("rec");	
						$('#r-' + which_form + '-' + i + ' td:first').text(listing.neighborhoods);

						// add url or not
						if(listing.url){             		
							var listing_url = listing.url.replace("http://", "");
						}

						var listing_establishment = listing.name;

						$('#r-' + which_form + '-' + i + ' td:nth-child(2) .name').attr("id","zid-" + listing.id).html(listing_establishment);
						$('#r-' + which_form + '-' + i + ' td:nth-child(2) .street').text(listing.streetAddress);
						$('#r-' + which_form + '-' + i + ' td:nth-child(2) em').text(listing.etype);
						$('#r-' + which_form + '-' + i + ' td:nth-child(2) .url').text(listing_url);
						$('#r-' + which_form + '-' + i + ' td:nth-child(2) .lat').text(listing.lat);
						$('#r-' + which_form + '-' + i + ' td:nth-child(2) .lng').text(listing.lng);

						var count_introanddesc = listing.special.search(/lass=\"extended\"/);
						var count_intro = listing.special.search(/lass=\"intro\"/);
						var count_desc = listing.special.search(/lass=\"description\"/);

						if(count_introanddesc < count_desc){
							var special_short = listing.special.replace("<\/span>","...<\/span>");
						}
						else {

							var count_intro_span = listing.special.search(/<\/span>/) - (count_intro + 13);
							var count_desc_span_end = listing.special.indexOf("<\/span>",count_desc + 1);
							var count_offset = (count_desc + 19)
							var count_desc_span = count_desc_span_end - count_offset;
							var total_span = count_intro_span + count_desc_span;

							
							
							if(total_span > 53){

								var count_offset_d = 53 - count_intro_span;

								var full_desc = listing.special.substring(count_offset, count_desc_span_end);
								var short_desc = listing.special.substring(count_offset,(count_offset + count_offset_d));
				

								var special_short = listing.special.replace(full_desc,short_desc + '...');
							}
							else { 

								var special_short = listing.special;
							}
						}


						$('#r-' + which_form + '-' + i + ' td:last').html(special_short);


						var map_html = 	'<div class="extended-m">' +
										'<dl>' +
											'<dt class="name-t">Name</dt>' +
											'<dd class="name-d">' + listing_establishment + '</dd>' +
											'<dt class="neighborhood-t">Neighborhood</dt>' +
											'<dd class="neighborhood-d">' + listing.neighborhoods + '</dd>' +
											'<dt class="description-t">Description</dt>' +
											'<dd class="description-d">' +
												listing.special +
											'</dd>' +
											'<dt class="more-t">' + listing.id +'</dt>' +
											'<dd class="more-d">' +
												'<a onclick="javascript:mapToPage(' + listing.id + ')" href="#" title="More">More</a>' +
											'</dd>' +
										'</dl>' +
										'</div>';

						// google map popuplation		
						point = new GLatLng(listing.lat,listing.lng);
						map.addOverlay(createMarker(point, map_html));
					});
				}
			);

	// ga page tracking
	pageTracker._trackPageview("RestServer.php?action=search&q=" + zfilters['keyword'] + "&n=" + zfilters['areas'] + "&d=" + zfilters['day'] + "&t=" + zfilters['type'] + "&p=" + zfilters['page'] + "&tp=" + zfilters['total'] + "");
	};

	// create marker on google map
	function createMarker(point,text_special) {
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://zloud.zdrinks.com/images/shadow.png";
		baseIcon.iconSize = new GSize(18, 16);
		baseIcon.shadowSize = new GSize(28, 19);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		var zIcon = new GIcon(baseIcon);
		zIcon.image = "http://zloud.zdrinks.com/images/marker.png";
		//baseIcon.iconSize = new GSize(18, 16);
	// Set up our GMarkerOptions object
	 markerOptions = { icon:zIcon };
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(text_special);
	});
	return marker;
	}

	// create marker on google map
	function createMarkerProfile(point,text_special) {
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://zloud.zdrinks.com/images/shadow.png";
		baseIcon.iconSize = new GSize(18, 16);
		baseIcon.shadowSize = new GSize(28, 19);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		var zIcon = new GIcon(baseIcon);
		zIcon.image = "http://zloud.zdrinks.com/images/marker.png";
	 	markerOptions = { icon:zIcon, clickable:false };
		var marker = new GMarker(point, markerOptions);
		return marker;
	}

	// map view
	function mapToPage(mapID){
		$('.ui-tabs-nav a').eq(0).trigger('click');
		$('#zid-' + mapID).trigger('click');
		$('#profile-c').addClass('back-to-map');
		return false;
	}

	// google search
	function googleSearchStyle(){
		$('.google .gsc-search-box input.gsc-input').attr("id","google-search").before('<label for="google-search">First Search For Your Bar/Venue</label>');
		google_search_button = $('.gsc-search-box td.gsc-search-button').html();
		$('.google .gsc-search-box td.gsc-search-button').remove();
		// google_clear_button = $('.gsc-search-box td.gsc-clear-button').html();
		$('.google .gsc-search-box td.gsc-clear-button').remove();
		$('.google td.gsc-branding-img').after('<td class="gsc-search-button">' + google_search_button + '</td>');	
		$('#searchcontrol').removeAttr("class");
	};	

	// format search for dropdowns
	function type_to_format(area) {
		return area.name;
	};

	// validate checkboxes in form
    function checkboxesValidate(section,section_input){
    	$(section).click(function(){
    		$(section_input).attr("value",'');
			$(section).each(function (i) {
				if ($(this).is(':checked')) {
					$(section_input).attr("value",'checked');
					one_checked = "Y";
				}
			});	
    		
			if(one_checked == ''){
				$(section_input).attr("value",'');
			}
			else{
				$(section_input).parent().find("label").removeClass("error");
				$(section_input).parent().find("span.error").hide();
			}   		
    	});
    };
    
	function settingTime(selector,theValue,selectorS,selectorL,position){
		$(selector).slider({
			animate:true,
			orientation: "vertical",
			value:position,
			min:1,
			max:2,
			step:1,
			change:function(event,ui){
				if(ui.value == '2'){
					var new_ui_value = 'am'
				}
				else if(ui.value == '1'){
					var new_ui_value = 'pm'
				}
				
				$('#special-0-time-am-pm-' + theValue).val(new_ui_value);
				$(selectorS + ' li').removeClass("current");
				$(selectorS + ' li#' + selectorL + '-' + ui.value).addClass("current");
			}
		});	
		$('#special-0-time-am-pm-' + theValue).val("am");
		$(selectorS + ' a').after('<ul><li id="'+ selectorL +'-2" class="current">AM<\/li><li id="' + selectorL + '-1">PM<\/li><\/ul>');
		$(selector).click(function(){
			$(this).attr("id");
		});
	}

	// clear form
	function clearForm(){
		$("#record-special-event,#hidden-which-is-it,#hidden-select-type,#hidden-takes-place,#special-0 input[type=text],#special-0 textarea").attr("value","");
		$("#special-0 input[type=checkbox]").attr("checked","");
		$("#time-beg").slider('value',[2]);
		$("#time-end").slider('value',[2]);
	};

	// errors animate 
	function flashAnimate(error,colorHex){
			$(error).animate({color: '#c33706'},507).animate({color: colorHex},507).animate({color: '#c33706'},507);
	}
	
	function errorsAnimate(action,error,colorHex){
		$(action).live("click", function(){
			flashAnimate(error,colorHex);
		});
	};

// google callback  
google.setOnLoadCallback(function() {

// *** plugins ***

/*
 * jQuery validation plug-in 1.5.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

$.extend($.fn, {
	validate: function( options ) {
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
			return;
		}
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}
		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator); 
		if ( validator.settings.onsubmit ) {
			this.find("input, button").filter(".cancel").click(function() {
				validator.cancelSubmit = true;
			});
			if (validator.settings.submitHandler) {
				this.find("input, button").filter(":submit").click(function() {
					validator.submitButton = this;
				});
			}
			this.submit( function( event ) {
				if ( validator.settings.debug )
					event.preventDefault();
				function handle() {
					if ( validator.settings.submitHandler ) {
						if (validator.submitButton) {
							var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
						}
						validator.settings.submitHandler.call( validator, validator.currentForm );
						if (validator.submitButton) {
							hidden.remove();
						}
						return false;
					}
					return true;
				}
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}
		return validator;
	},
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = true;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid &= validator.element(this);
            });
            return valid;
        }
    },
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function(index, value) {
			result[value] = $element.attr(value);
			$element.removeAttr(value);
		});
		return result;
	},
	rules: function(command, argument) {
		var element = this[0];
		
		if (command) {
			var settings = $.data(element.form, 'validator').settings;
			var staticRules = settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				if (argument.messages)
					settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}
		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}
		return data;
	}
});
$.extend($.expr[":"], {
	blank: function(a) {return !$.trim(a.value);},
	filled: function(a) {return !!$.trim(a.value);},
	unchecked: function(a) {return !a.checked;}
});
$.validator = function( options, form ) {
	this.settings = $.extend( {}, $.validator.defaults, options );
	this.currentForm = form;
	this.init();
};
$.validator.format = function(source, params) {
	if ( arguments.length == 1 ) 
		return function() {
			var args = $.makeArray(arguments);
			args.unshift(source);
			return $.validator.format.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = $.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	$.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};
$.extend($.validator, {
	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		validClass: "valid",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: [],
		ignoreTitle: false,
		onfocusin: function(element) {
			this.lastActive = element;
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
				this.errorsFor(element).hide();
			}
		},
		onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element) {
			if ( element.name in this.submitted )
				this.element(element);
		},
		highlight: function( element, errorClass, validClass ) {
			$(element).addClass(errorClass).removeClass(validClass);
			$(element).prev().addClass(errorClass).removeClass(validClass);
		},
		unhighlight: function( element, errorClass, validClass ) {
			$(element).removeClass(errorClass).addClass(validClass);
			$(element).prev().removeClass(errorClass).addClass(validClass);
		}
	},
	setDefaults: function(settings) {
		$.extend( $.validator.defaults, settings );
	},
	messages: {
		required: "This field is required.",
		remote: "Please fix this field.",
		email: "Please enter a valid email address.",
		url: "Please enter a valid URL.",
		date: "Please enter a valid date.",
		dateISO: "Please enter a valid date (ISO).",
		dateDE: "Bitte geben Sie ein gültiges Datum ein.",
		number: "Please enter a valid number.",
		numberDE: "Bitte geben Sie eine Nummer ein.",
		digits: "Please enter only digits",
		creditcard: "Please enter a valid credit card number.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.validator.format("Please enter no more than {0} characters."),
		minlength: $.validator.format("Please enter at least {0} characters."),
		rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
		range: $.validator.format("Please enter a value between {0} and {1}."),
		max: $.validator.format("Please enter a value less than or equal to {0}."),
		min: $.validator.format("Please enter a value greater than or equal to {0}.")
	},
	autoCreateRanges: false,
	prototype: {
		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();
			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});
			
			function delegate(event) {
				var validator = $.data(this[0].form, "validator");
				validator.settings["on" + event.type] && validator.settings["on" + event.type].call(validator, this[0] );
			}
			$(this.currentForm)
				.delegate("focusin focusout keyup", ":text, :password, :file, select, textarea", delegate)
				.delegate("click", ":radio, :checkbox", delegate);

			if (this.settings.invalidHandler)
				$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
		},
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			this.showErrors();
			return this.valid();
		},
		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid(); 
		},
		element: function( element ) {
			element = this.clean( element );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				this.toHide = this.toHide.add( this.containers );
			}
			this.showErrors();
			return result;
		},
		showErrors: function(errors) {
			if(errors) {
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},
		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},
		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},
		hideErrors: function() {
			this.addWrapper( this.toHide ).hide();
		},
		valid: function() {
			return this.size() == 0;
		},
		size: function() {
			return this.errorList.length;
		},
		focusInvalid: function() {
			if( this.settings.focusInvalid ) {
				try {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus();
				} catch(e) {
				}
			}
		},
		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},
		elements: function() {
			var validator = this,
				rulesCache = {};
			return $([]).add(this.currentForm.elements)
			.filter(":input")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;
				rulesCache[this.name] = true;
				return true;
			});
		},
		clean: function( selector ) {
			return $( selector )[0];
		},
		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},
		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.formSubmitted = false;
			this.currentElements = $([]);
		},
		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().add( this.containers );
		},
		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},
		check: function( element ) {
			element = this.clean( element );
			if (this.checkable(element)) {
				element = this.findByName( element.name )[0];
			}
			var rules = $(element).rules();
			var dependencyMismatch = false;
			for( method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;
					
					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}
					
					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method");
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;
			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();
			
			return meta && meta.messages && meta.messages[method];
		},
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},
		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				!this.settings.ignoreTitle && element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},
		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method );
			if ( typeof message == "function" ) 
				message = message.call(this, rule.parameters, element);
			this.errorList.push({
				message: message,
				element: element
			});
			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},
		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
			return toToggle;
		},
		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
		},
		validElements: function() {
			return this.currentElements.not(this.invalidElements());
		},
		invalidElements: function() {
			return $(this.errorList).map(function() {
				return this.element;
			});
		},
		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				label.removeClass().addClass( this.settings.errorClass );
				label.attr("generated") && label.html(message);
			} else {
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow = this.toShow.add(label);
		},
		errorsFor: function(element) {
			return this.errors().filter("[for='" + this.idOrName(element) + "']");
		},
		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},
		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},
		findByName: function( name ) {
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},
		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},
		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},
		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},
		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},
		
		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},
		stopRequest: function(element, valid) {
			this.pendingRequest--;
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			}
		},
		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", previous = {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}
		
	},
	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},
	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},
	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},
	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);
		
		for (method in $.validator.methods) {
			var value = $element.attr(method);
			if (value) {
				rules[method] = value;
			}
		}
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}
		return rules;
	},
	metadataRules: function(element) {
		if (!$.metadata) return {};
		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},
	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},	
	normalizeRules: function(rules, element) {
		$.each(rules, function(prop, val) {
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});
		
		if ($.validator.autoCreateRanges) {
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}
		if (rules.messages) {
			delete rules.messages
		}
		return rules;
	},
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message || $.validator.messages[name];
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},
	methods: {
		required: function(value, element, param) {
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				var options = $("option:selected", element);
				return options.length > 0 && ( element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return $.trim(value).length > 0;
			}
		},
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			var previous = this.previousValue(element);
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			param = typeof param == "string" && {url:param} || param; 
			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					data: data,
					success: function(response) {
						var valid = response === true;
						if ( valid ) {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						} else {
							var errors = {};
							errors[element.name] = previous.message = response || validator.defaultMessage( element, "remote" );
							validator.showErrors(errors);
						}
						previous.valid = valid;
						validator.stopRequest(element, valid);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		},
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) >= param;
		},
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) <= param;
		},
		rangelength: function(value, element, param) {
			var length = this.getLength($.trim(value), element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
		},
		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
		},
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},
		dateDE: function(value, element) {
			return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
		},
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},
		numberDE: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
		},
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
		},
		accept: function(value, element, param) {
			param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
			return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); 
		},
		equalTo: function(value, element, param) {
			return value == $(param).val();
		}
	}
});
$.format = $.validator.format;
})(jQuery);
;(function($) {
	var ajax = $.ajax;
	var pendingRequests = {};
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
		var port = settings.port;
		if (settings.mode == "abort") {
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return (pendingRequests[port] = ajax.apply(this, arguments));
		}
		return ajax.apply(this, arguments);
	};
})(jQuery);
;(function($) {
	$.each({
		focus: 'focusin',
		blur: 'focusout'	
	}, function( original, fix ){
		$.event.special[fix] = {
			setup:function() {
				if ( $.browser.msie ) return false;
				this.addEventListener( original, $.event.special[fix].handler, true );
			},
			teardown:function() {
				if ( $.browser.msie ) return false;
				this.removeEventListener( original,
				$.event.special[fix].handler, true );
			},
			handler: function(e) {
				arguments[0] = $.event.fix(e);
				arguments[0].type = fix;
				return $.event.handle.apply(this, arguments);
			}
		};
	});
	$.extend($.fn, {
		delegate: function(type, delegate, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		},
		triggerEvent: function(type, target) {
			return this.triggerHandler(type, [$.event.fix({ type: type, target: target })]);
		}
	})
})(jQuery);

/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */

;(function($) {
	
$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150
		}, options);
		options.highlight = options.highlight || function(value) { return value; };
		options.formatMatch = options.formatMatch || options.formatItem;
		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});
$.Autocompleter = function(input, options) {
	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);
	var blockSubmit;
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {
			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;
			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;
			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;
			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;
			case KEY.ESC:
				select.hide();
				break;
			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("addToCache", function() {
		cache.add(argument[1],argument[2]);
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});
	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;
		var v = selected.result;
		previousValue = v;
		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
			}
			v += options.multipleSeparator;
		}
		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}
	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}
		
		var currentValue = $input.val();
		
		if ( !skipPrevCheck && currentValue == previousValue )
			return;
		
		previousValue = currentValue;
		
		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};
	function trimWords(value) {
		if ( !value ) {
			return [""];
		}
		var words = value.split( options.multipleSeparator );
		var result = [];
		$.each(words, function(i, value) {
			if ( $.trim(value) )
				result[i] = $.trim(value);
		});
		return result;
	}
	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		return words[words.length - 1];
	}
	function autoFill(q, sValue){
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
		}
	};
	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};
	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) { 
			$input.search(
				function (result){
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else
							$input.val( "" );
					}
				}
			);
		}
		if (wasVisible)
			$.Autocompleter.Selection(input, input.value.length, input.value.length);
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};
	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		if (data && data.length) {
			success(term, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			
			var extraParams = {
				timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});
			
			$.ajax({
				mode: "abort",
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				type: "GET",
				data: $.extend({
					q: lastWord(term),
					limit: options.max
				}, extraParams),
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			select.emptyList();
			failure(term);
		}
	};
	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};
	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};
};
$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 39,
	matchCase: false,
	matchSubset: true,
	matchContains: true,
	cacheLength: 10,
	max: 100,
	mustMatch: true,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { 
		return type_to_format(row);
	},
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: true,
	multipleSeparator: ", ",
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {
	var data = {};
	var length = 0;
	function matchSubset(s, sub) {
		if (!options.matchCase) 
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};
	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){ 
			length++;
		}
		data[q] = value;
	}
	function populate(){
		if( !options.data ) return false;
		var stMatchSets = {},
			nullData = 0;
		if( !options.url ) options.cacheLength = 1;
		stMatchSets[""] = [];
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;
			var firstChar = value.charAt(0).toLowerCase();
			if( !stMatchSets[firstChar] ) 
				stMatchSets[firstChar] = [];
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};
			stMatchSets[firstChar].push(row);
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};
		$.each(stMatchSets, function(i, value) {
			options.cacheLength++;
			add(i, value);
		});
	}
	setTimeout(populate, 25);
	function flush(){
		data = {};
		length = 0;
	}
	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			if( !options.url && options.matchContains ){
				var csub = [];
				for( var k in data ){
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}				
				return csub;
			} else 
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};
	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);
	
		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);            
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});
		
		if( options.width > 0 )
			element.css("width", options.width);
		needsInit = false;
	} 
	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}
	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};
	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}
	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}
	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}
	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});
				
                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }
            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};
$.Autocompleter.Selection = function(field, start, end) {
	if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	} else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

})(jQuery);

/* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 */

jQuery.url = function()
{
	var segments = {};
	var parsed = {};
 	var options = {
	
		url : window.location,
		
		strictMode: false,
	
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}
		
	};
	var parseUri = function()
	{
		str = decodeURI( options.url );
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}
		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});
		return uri;
	};
	var key = function( key )
	{
		if ( ! parsed.length )
		{
			setUp();
		} 
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}
	
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	var param = function( item )
	{
		if ( ! parsed.length )
		{
			setUp();
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};
	var setUp = function()
	{
		parsed = parseUri();
		getSegments();	
	};
	var getSegments = function()
	{
		var p = parsed.path;
		segments = [];
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};
	
	return {
		setMode : function( mode )
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		segment : function( pos )
		{
			if ( ! parsed.length )
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},

		attr : key,
		param : param
	};
}();

// *** document ready ***	
	jQuery(function($) {

	// globals
	var zuid = '';
	var suid = '';
	var zlocation = '';
	var test_prefix = ''
	zuid = $.url.param("zuid");
	suid = $.url.param("suid");
	zlocation = $.url.attr("host");
	
	if(zlocation == 'test.zdrinks.com'){
		test_prefix = 't_'
	}
	else {
		test_prefix = ''
	}

	// general
	$.postJSON = function(url, data, callback) { $.post(url, data, callback, "json")};	
	
	$('#jump-ml').click(function(){
		$('#mce-EMAIL').focus();
		return false;
	})
	
	var latest_tweet_time = $('.aktt_tweet_time').text();
	$('#hp-col-b time').text(latest_tweet_time);
	$('.aktt_tweet_time').remove();
	
	// remove rules
	$('#bar-t li:last,#content li:last').addClass('last');
	
	$('.name a,.name-d a,#follow a').live("click", function(){
		$(this).attr("target","_blank");
	});
	
	// load initial data
	if(zlocation != 'zdrinks.com' && zlocation != 'test-wp.zdrinks.com'){
		grabFilters("cities");
	}
	
	// ** header **
	
	// city
	$('#city-tab a#change').toggle(
		function(){
			$('#city-list').slideDown();
			$('#change').removeClass("change").addClass("close").attr("title","Close").text("Close");	
		    },
		function(){
			$('#city-list').slideUp();
			$('#change').removeClass("close").addClass("change").attr("title","Change City").text("Change City");
			}
		);
		
	// blog
	$('#searchsubmit').addClass("button");

	// inputs
	inputDefaults('.areas');
	inputDefaults('.keyword');

	// errors animate 
	errorsAnimate("#mc-embedded-subscribe","#list-status","#fff");
	errorsAnimate(".sendbutton",".cf_li_err label","#000");

	// search
	$('.search-values input').keydown(function(e){
		if(e.keyCode == 13){
			return false;
		}
	});

		// neighborhoods format
		$(".areas").result(function(event, data, formatted) {
			var form_parent = "";
			var form_parent_id = "";
		
			form_parent = $(this).parents('.search-values').attr("id");
			form_parent_id = form_parent.replace("form-","");
	
/*			var boundary_lines = data.boundary;
			var points = [];
			var outline_area = "";
			
			for (var i = 0; i < boundary_lines.length; ++i){
			
				var draw_points = new GLatLng(boundary_lines[i][1],boundary_lines[i][0]);
				points.push(draw_points);

			}
			
			if(outline_area){
				map.removeOverlay(outline_area);
			}
			
			outline_area=new GPolyline(points,'#3333CC',5,.6);
			
			map.addOverlay(outline_area);*/
		
			$(this).attr("value",'');

			$('#' + form_parent + ' .search-inputs-field').before('<li class="area-value" id="area-val-' + data.id + '">' + data.name + '<span>,</span></li>');
			
			var length_of_area = $('#' + form_parent + ' #area-val-' + data.id).width();
			
			var length_of_input = $(this).width();
			var new_length_of_input = length_of_input-(length_of_area + 13);

			var type_to_hidden = $('#area-values-' + form_parent_id);
			
			type_to_hidden.val( (type_to_hidden.val() ? type_to_hidden.val() + "," : type_to_hidden.val()) + data.id);
				grabFilters(form_parent_id);	
				
			$(this).css("width",new_length_of_input + "px");
			
			var total_neigbhorhoods = $('#' + form_parent + ' .area-value').length;

			if(total_neigbhorhoods == '2'){
				$('#' + form_parent + ' .max').show();
				$('#' + form_parent + ' .areas').hide();
			}
			
		});
		
		// neighborhoods
		$(".areas").autocomplete('RestServer.php?action=neighborhood', {
			width: 453,
			parse: function(data) {
				return $.map(eval(data), function(row) { 
					return {
						data: row,
						value: row.name,
						result: row.name
					}
				});
			},
			extraParams: {
       			d: function() { return $("#current-day").val(); }
			}
		});
		
		$('.area-value').live("click",function(){
			var form_parent = "";
			var form_parent_id = "";

			form_parent = $(this).parents('.search-values').attr("id");
			form_parent_id = form_parent.replace("form-","");

			$('#' + form_parent + ' .max').hide();
			$('#' + form_parent + ' .areas').show();

			$('#area-values-' + form_parent_id).attr("value","");
			
			dont_count = $(this).attr("id");

			var current_length_of_area = $(this).width();
			var current_length_of_input = $('#' + form_parent + ' .areas').width();
			var new_current_length_of_input = current_length_of_input+(current_length_of_area + 13);

			$(this).hide('drop',function(){
				$(this).removeClass().attr("id","");
			})
			
			each_area_val = '';
			each_area_comma = '';

			$('#' + form_parent + ' .area-value').each(function(i) {
				if(dont_count != $(this).attr("id")){
					each_area_val = $(this).attr("id").replace("area-val-","") + each_area_comma +  each_area_val;
				}
			});

			$('#area-values-' + form_parent_id).attr("value",each_area_val);

			each_area_val = "";
			
			grabFilters(form_parent_id);

			$('#areas-' + form_parent_id).css("width",new_current_length_of_input + "px");

		});

		// keywords
		var search_timeout = undefined;
		$('.keyword').bind('keyup', function() {
			var form_parent = "";
			var form_parent_id = "";

			form_parent = $(this).parents('.search-values').attr("id");
			form_parent_id = form_parent.replace("form-","");

			if(search_timeout != undefined) {
				clearTimeout(search_timeout);
			}

			// wait till after keys are pressed before sending
			search_timeout = setTimeout(function() {
			keyword_value = $('#' + form_parent + ' .keyword').val();
			search_timeout = undefined;

			grabFilters(form_parent_id);
			}, 313);
		});

		// type of drink
		$('#type-of-drink a').toggle(
			function(){
					changeDrinkType("1");

					$('#current-type').attr("value","3");
					
					grabFilters("cities"); // *** REPLACE WITH VAR;
					
					$(this).prev().text("Looking for all types of drinks and events?");
			    	$(this).removeClass("type-non").addClass("type-both").attr("title","Get This Party Started").text("Get This Party Started");
			    	
		    	},
		    	function(){
					changeDrinkType("0");
					
					$('#current-type').attr("value","0");
					
					grabFilters("cities"); // *** REPLACE WITH VAR;
					
					$(this).prev().text("Looking for drinks and events that won't kill your liver?");
			    	$(this).removeClass("type-both").addClass("type-non").attr("title","Sober Up").text("Sober Up");
			    	
		});   	
    	
		
	// Loader for AJAX
	$('#loading').ajaxStart(function(){
		$('#z-overlay').show(); 
		$(this).show();
	}).ajaxStop(function(){
		$(this).hide();
		$('#z-overlay').hide();
	});		

	// ** tabs **	

	// tabs
		$('#tabs').tabs();   

	// list view

		//more
		$("tr.rec").live("click", function(e){
			extended_name_ID = $(this).find("td:eq(1) .name").attr("id");

			extended_name = $(this).find("td:eq(1) .name").html();
			$('#profile-page h1').html(extended_name);
			
			extended_neighborhood = $(this).find("td:eq(0)").html();
			$('#profile-neighborhood').html(extended_neighborhood);
			
			extended_type_of_place = $(this).find("td:eq(1) .type").html();
			$('#profile-type-of-place').html(extended_type_of_place);
			
			extended_address = $(this).find("td:eq(1) .street").html();
			$('#profile-address').html(extended_address);
			
			extended_url = $(this).find("td:eq(1) .url").html();
			$('#profile-url').html('<a target="_blank" href="http://' + extended_url + '">' + extended_url + '</a>');

			extended_lat = $(this).find("td:eq(1) .lat").html();
			extended_lng = $(this).find("td:eq(1) .lng").html();

			map_profile.clearOverlays();
			var point_profile; 
			map_profile.setZoom(15);
			map_profile.panTo(new GLatLng(extended_lat,extended_lng));

			// google map profile popuplation		
			point_profile = new GLatLng(extended_lat,extended_lng);
			map_profile.addOverlay(createMarkerProfile(point_profile));


			extended_description = $(this).find("td:eq(2) .extended").html();
			$('#profile-specials').after().html(extended_description);

			$('#results-cities').fadeOut(364);
			$('#profile-page').removeClass("profile-hide");
			$('#ads-list-view').addClass("ads-profile");
			$('.ui-tabs-nav li,#search').addClass("hide-sections");
			
/*			var extended_contents_height = $('.extended-b').height();
			var pos_x = e.pageX - 247;
			var pos_y = e.pageY - (extended_contents_height -26);*/

			//$('#z-overlay').show(); 

			//$('.extended-b').css({top: pos_y, left: pos_x}).show();

			$('html, body').animate({scrollTop:273}, 728);
			return false;

			// ga event tracking
			pageTracker._trackEvent("list","more",test_prefix + extended_name_ID);
		});
		

		$('#profile-c').click(function(){
				$('#profile-page').addClass("profile-hide");
				$('#results-cities').fadeIn(364);
				$('#ads-list-view').removeClass("ads-profile");
				$('.ui-tabs-nav li,#search').removeClass("hide-sections");

				if ($('#profile-c').is('.back-to-map')){
					$(this).removeClass();
					$('.ui-tabs-nav a').eq(1).trigger('click');
				} 

				$('html, body').animate({scrollTop:273}, 728);
				return false;
		});

/*		$('.extended-close').click(function(){
			if($('.extended-b').is(":visible")){
				$('#z-overlay,.extended-b').hide();
			}
			else{
				return false;
			}
		});*/

		// pagination
		$('.page-numbers a').click(function(){
			var form_parent = "";
			var form_parent_id = "";

			form_parent = $(this).parents(".page-numbers > div").attr("class");
			form_parent_id = form_parent.replace("page-numbers-","");

			$('.page-numbers-' + form_parent_id + ' a').attr("class","");
			var the_current_page = $(this).attr("title");
			$('.page-numbers-' + form_parent_id + ' li.p-' + the_current_page +' a').attr("class","current");
			if(the_current_page == 'Previous'){
				$('.page-numbers-' + form_parent_id + ' li.p-0 a').attr("class","");
				the_current_page = parseInt($('#current-page-' + form_parent_id).val()) - 1;
				$('.page-numbers-' + form_parent_id + ' li.p-' + the_current_page +' a').attr("class","current");
			}
			if(the_current_page == 'Next'){
				$('.page-numbers-' + form_parent_id + ' li.p-6 a').attr("class","");
				the_current_page = parseInt($('#current-page-' + form_parent_id).val()) + 1;
				$('.page-numbers-' + form_parent_id + ' li.p-' + the_current_page +' a').attr("class","current");
			}
			$('#current-page-' + form_parent_id).attr("value",the_current_page);

			grabFilters(form_parent_id,"y");
			
			$('html, body').animate({scrollTop:273}, 728);
			return false;
	 	});

	// * form *	  
	
	// general
	$('#email').click(function(){
		var was_there_a_search = $('#titleNoFormatting').val();
		if(!was_there_a_search){
			$('#dialog').text('Please Search For Your Establishment First!').dialog('open');
		}
	});	
	  
	    $('#add-tab').toggle(function(){
	    	if($('.google').length > 0 && !zuid){
	    		googleSearchStyle();
	    	}
	    $('#add-form').animate({
   			    marginLeft: "0"
   	    },function(){
   	    
   	    
   	    }).attr("class","open");
   	    		$('#ad-add-form').attr("class","ad-add-form-t");  
	    },function(){
		    $('#add-form').animate({
   			    marginLeft: "201px"
   	    },function(){
   	    }).attr("class","closed");
			$('#ad-add-form').attr("class","ad-add-form-b");    
	    })	
	    
     	// dialog box
    		$('#dialog').dialog({
    		autoOpen: false,
			resizable: false,
			modal: true,
			title: 'Success',
			buttons: {
				'Ok': function() {
					$(this).dialog('close');
				}
			}
			}); 	    
	    
	// neighborhood
	$("#neighborhoods input#neighborhood").result(function(event, data, formatted) {
		var hidden = $("#neighborhoods input#neighborhood-values");
		hidden.val( (hidden.val() ? hidden.val() + "," : hidden.val()) + data.id);
	});
	
	$("#neighborhoods input#neighborhood").autocomplete('RestServer.php?action=neighborhood', {
		width: 297,
		parse: function(data) {
			return $.map(eval(data), function(row) {
				return {
					data: row,
					value: row.name,
					result: row.name
				}
			});
		}
	});
	
    // specials
    
	// days of the week
	$('.takes-place .toggle').toggle(
		function(){
			$('.takes-place').find(':checkbox').attr("checked","checked");
			$('#hidden-takes-place').attr("value",'checked');
			$(this).attr("title","Uncheck All").text("Uncheck All");	
		    },
		function(){
			$('.takes-place').find(':checkbox').attr("checked","");
			$('#hidden-takes-place').attr("value",'');
			$(this).attr("title","Check All").text("Check All");
			}
		);
    
		// date        
	    $('.dates input').live('click',function(){
		    $(this).datepicker({ showOn: 'focus' }).focus();
	    });
	    
	    $('.ui-datepicker-calendar td a').live('click',function(){
	    	$('#hidden-takes-place').attr("value",'checked');
	    });
	    
    	$('.specials textarea').live("keyup", function(){
	    	var limit = parseInt(247);
	    	var textarea = $(this).val();
        	var textlength = $(this).val().length;
        	var charsleft = $(this).parent().parent().attr("id");

        	if(textlength > limit){
            	$('#' + charsleft + ' .specials span.note').html('(Too many characters!)');
            	$(this).val(textarea.substr(0,limit));
            	return false;
        	}
        	else{
        	$('#' + charsleft + ' .specials span.note').html('('+ (limit - textlength) +' characters left)');
	        	return true;
	    	}
    	});
    	
    	// validation for checkboxes
		checkboxesValidate("#select-place input[type=checkbox]","#hidden-type-of-place");
		checkboxesValidate(".which-is-it input[type=checkbox]","#hidden-which-is-it");
		checkboxesValidate(".select-type input[type=checkbox]","#hidden-select-type");
		checkboxesValidate(".takes-place input[type=checkbox]","#hidden-takes-place");
		
		// time
		settingTime('#time-beg','0','#time-slider-beg','tb','2');
		settingTime('#time-end','1','#time-slider-end','te','2');


	// ** form	

	// add special
	$('#fields').validate({
			debug: true,
			errorElement: "span",
			errorPlacement: function(error, element) {
				error.appendTo( element.prev() );
			},
			submitHandler: function(form){
			
			// Loader for AJAX/Processing
			$('#submit-listing img').ajaxStart(function(){
				$(this).show();
				$('#submit-listing input').attr("value","Processing....");
			}).ajaxStop(function(){
				$(this).hide();
				$('#submit-listing input').attr("value","Submit");
			});		
			
			// on submit, send data to server 
			var zerialize = $('#fields').serializeArray();
   
   			// seralize the form
   			jQuery.each(zerialize, function(i, field){
   			});

   			// send data, get response
  			$.post("RestServer.php",zerialize,
  				function(response){
  				
  						// add
  						if(response.code == '13'){
  							$('#record-establishment').attr("value",response.establishment);  			
  						}
  						
  						// updates
  						if(response.code == '91'){
	
  						}

  						clearForm();
  						
  						$('#specials-list').removeClass("inactive");
  						$('#specials-edit').removeAttr("disabled");
  						
  						var edit_options = '<option value=\"0\">Select Special to Edit...</option>';
  							
						$.each(response.special,function(i,specials){
			
							edit_options = edit_options + '<option value="'+specials.id+'">'+specials.special.substring(0,39)+'...</option>';
							
						});
  						
						$('#specials-edit').html(edit_options);
  						
  						// message 
  						$('#dialog').text(response.msg).dialog('open');
						
					},
					"json");		
			}
	});

	// edit a special

	$("#specials-edit").change(function() {
	var new_or_exisiting = $('#action').val();

	//grab values from filters to search
	var zspecials = [];
		
	if(new_or_exisiting == 'tempSpecial' && !zuid){
		zspecials['email'] = $('#email').val();
			
	}else{
		zspecials['email'] = '';
	}
		

	zspecials['record-establishment'] = $('#record-establishment').val();	
	zspecials['specials-edit'] = $('#specials-edit').val();	
	
	
	if(zspecials['specials-edit'] != '0'){
		
		// communicate with server to get listing
	var no_cache = new Date().getTime();

	$.postJSON("RestServer.php", { 
		"action": "special", 
		"record-establishment": '"' + zspecials['record-establishment'] + '"', 
		"special-event": '"' + zspecials['specials-edit'] + '"', 
		"email": '"'+zspecials['email'] + '"'},
	function(data){
          	
            	// reset form
				clearForm();

				// populate form
            	$.each(data,function(i,special){
            	
            	    $('#record-special-event').attr("value",special.recno);
            		$("#special-0-title-0").attr("value",special.title);
            		$("#special-0-special-0").attr("value",special.special);	

     			
     				$.each(special.special_or_event, function() {
						$('#special-0-which-' + this).attr("checked","checked");
    				});
            		
     				$.each(special.alcoholic, function() {
						$('#special-0-type-' + this).attr("checked","checked");
    				});
           		
    				$.each(special.weekday, function() {
						$('#special-0-day-' + this).attr("checked","checked");
    				});
    					
    				$('#hidden-which-is-it,#hidden-select-type,#hidden-takes-place').attr("value","checked");
    					
    				// time
					$("#special-0-time-0").attr("value",special.start_time);
            		if(special.start_time_am_pm == 'am'){
            			var time_beg_val = "2";
            		}
            		else{
            			var time_beg_val = "1";
            		}
            		$("#time-beg").slider('value',[time_beg_val]);

            		$("#special-0-time-1").attr("value",special.end_time);
            		if(special.end_time_am_pm == 'am'){
            			var time_end_val = "2";
            		}
            		else{
            			var time_end_val = "1";
            		}
            		$("#time-end").slider('value',[time_end_val]);
            			
            		// date
            		$("#special-0-date-0").attr("value",special.start_date);
            		$("#special-0-date-1").attr("value",special.end_date);
            	});
            }
        );

	} 
	else if($("#specials-edit").val() == '0'){
		clearForm();
		}	
	});	

	if(zuid){
		if(!suid){
				suid = "";
		}
			$.getJSON(
            		"RestServer.php?action=listing&zuid=" + zuid + "&suid=" + suid + "",
            		function(response){
            		$('#add-tab').trigger('click');	
            			// message
	           			if(suid){
	           				if(response.copied == '1'){
	           					$('#dialog').text('Special Has Been Added').dialog('open');
	           				}
	           				if(response.copied == '2'){
	           					$('#dialog').text('Special Has Already Been Added').dialog('open');
	           				}
  						}

 						//$('#google-search').attr("value",response.name);
  						//$('.gsc-search-button').trigger("click");
  						$('#record-establishment').attr("value",response.id);
  						$('#establishment-name').text(response.establishment);
  						$('#titleNoFormatting').attr("value",response.establishment);
  						$('#establishment-info address').text(response.streetAddress);
  						$('#email').attr("value",response.email);
  						$('#website').attr("value",response.url);

						$.each(response.etype, function() {
							$('#type-of-place-' + this.replace(" ","-").toLowerCase()).attr("checked","checked");
    					});
    					
    					$('#hidden-type-of-place').attr("value","checked");

    					var neighborhood_name = '';
    					var neighborhood_id = '';	

						$.each(response.neighborhoods,function(i,neighborhood){
							neighborhood_name = neighborhood_name + neighborhood.name + ', ';
							neighborhood_id = neighborhood_id + neighborhood.id + ',';
						});

						$('#neighborhood').attr("value",neighborhood_name);
						
						$('#neighborhood-values').attr("value",neighborhood_id);

						//$('#google-search').focus();

  						$('#specials-list').removeClass("inactive");
  						$('#specials-edit').removeAttr("disabled");
  						
  						var edit_options = '<option value=\"0\">Select Special to Edit...</option>';
  							
						$.each(response.special,function(i,specials){
							edit_options = edit_options + '<option value="'+specials.id+'">'+specials.special.substring(0,39)+'...</option>';
							
						});
  						
						$('#specials-edit').html(edit_options);   
					         		
            		}
        	);
		$('#zuid').attr("value",zuid);
		$('#suid').attr("value",suid);
	};

		// mailling list
		$('#mailing-list').validate({
				debug: true,
				errorElement: "span",
				errorPlacement: function(error, element) {
					error.appendTo( element.parent("li").prev("li") );
				},
				submitHandler: function(form){

				// Loader for AJAX/Processing

				// on submit, send data to server 
				var zerialize_email = $('#mailing-list').serializeArray();

				// seralize the form
				jQuery.each(zerialize_email, function(i, field){
				});

   				// send data, get response
  			$.getJSON("http://zdrinks.us1.list-manage.com/subscribe/post-json?u=89fe57e051947886eebe59b48&id=aae236020c&c=?",zerialize_email,
				function(response){
					if(response.result == 'success'){
						$('#list-confirm').show();
						$('#mce-EMAIL').hide();
						$('#list-status').html('&nbsp;');
					}
					if(response.result == 'error'){
						$('#list-status').text(response.msg.replace(" to list Z Drinks Mailing List",""));
					}
					},
					"json");
				}
		});

	}); // end document.ready
}); // end google setOnLoadCallback
//]]>