(function ($, window) {
	/* Defaults for autocomplete */
	window.preFilledZip = false;
	window.preFilledCity = false;
	
	/* Activate tabs */
	$('#demographics > ul, #cityLiving > ul').each(function () {
		var tabContent, tabs = $(this).children('li:not(.lastUnit)');
		tabContent = $(this).siblings('.tabPane');
		tabs.css('cursor', 'pointer');
		tabs.each(function (index) {
			$(this).click(function () {
				tabs.removeClass('currentTab');
				$(this).addClass('currentTab');
				tabContent.addClass('hide').hide();
				tabContent.eq(index).removeClass('hide').css({ opacity: 0 }).animate({ opacity: 1 }, 500);
			});
		});
	});

	/* Handle the show/hide for zip code list */
	$('.showAllZipCodes').each(function () {
		var hidden = true, list = $(this).siblings('ul'), label = $(this).children('strong');
		list.children('li:gt(4)').hide();

		$(this).click(function () {
			if (hidden) {
				label.text(label.text().replace(/^show/i, 'Hide'));
				list.children('li').show();
			} else {
				label.text(label.text().replace(/^hide/i, 'Show'));
				list.children('li:gt(4)').hide();
			}
			hidden = !hidden;
			return false;
		});
	});

	(function yelp() {
		var yelpTabLoaded, city, state;
		city = $('#questiona > input[name=city]').val();
		state = $('#questiona > input[name=state]').val();

		yelpTabLoaded = new Array();
		yelpTabLoaded['lndRestaurants'] = false;
		yelpTabLoaded['lndShopping'] = false;
		yelpTabLoaded['lndFlavor'] = false;

		$('#cityLiving > ul > li').click(function () {
			var id = $(this).attr('id').replace(/Tab$/, '');
			if (typeof yelpTabLoaded[id] !== 'undefined') {
				refreshYelpTab(id);
			}
		});

		function refreshYelpTab(tab) {
			if (yelpTabLoaded[tab] != true) {
				$.getJSON(window.forrentBaseUrl + "ajax/yelpRequest.ajax.php?tab=" + tab + "&city=" + city + "&state=" + state + '&callback=?', function(data) {
					$('#' + tab).html(yelpHTML(data.reviews, tab));
					yelpTabLoaded[tab] = true;
				});
			}
		}

		function yelpHTML(reviews, tab) {
			var x;
			var htmlResults = new Array();
			if (reviews != '') {
				for (x in reviews) {
					if (reviews[x] != undefined) {
						even = '';
						if (!(x % 2)) {
							even = ' even';
						}
						htmlResult = '<div class="businessresult line' + even + '">';
						htmlResult += '<div class="leftcol">';
						htmlResult += '<div class="itemheading" id="bizTitle0">';
						htmlResult += '<a id="bizTitleLink0" href="' + reviews[x].url + '">' + (parseInt(x) + 1) + '. 	' + reviews[x].name + '</a>';
						htmlResult += '</div>';
						if (reviews[x].categories.length > 0) {
							htmlResult += '<div class="itemheading">';
							htmlResult += 'Categories: ';
							categoryLine = new Array();
							for (cat in reviews[x].categories) {
								categoryLine[cat] = '<a href="' + reviews[x].categories[cat].url + '" class="category">' + reviews[x].categories[cat].name + '</a>';
							}
							categories = categoryLine.join(',');
							htmlResult += categories;
							htmlResult += '</div>';
						}
						htmlResult += '<div class="vcard">';
						htmlResult += reviews[x].address1 + '<br />' + reviews[x].city + ', ' + reviews[x].state_code + ' ' + reviews[x].zip + '<br />';
						htmlResult += '<div class="phone">';
						htmlResult += reviews[x].phone;
						htmlResult += '</div>';
						htmlResult += '</div>';
						htmlResult += '</div>';
						htmlResult += '<div class="rightcol">';
						htmlResult += '<div class="rating">';
						htmlResult += '<img title="' + reviews[x].rating_text + ' star rating" alt="' + reviews[x].rating_text + ' star rating" src="' + reviews[x].rating_img + '" />';
						htmlResult += '</div>';
						htmlResult += '<a href="' + reviews[x].url + '" class="reviews">' + reviews[x].review_count + ' reviews</a><br />';
						htmlResult += '<a href="' + reviews[x].url + '" class="read_more" target="_blank">Read Reviews</a>';
						htmlResult += '</div>';
						htmlResult += '</div>';
						htmlResults[x] = htmlResult;
					}
				}
				var htmlR = htmlResults.join('');
			} else {
				var htmlR = '<div class="businessresult line">';
				htmlR += '<div class="leftcol">';
				htmlR += '				<div class="itemheading">';
				htmlR += '					Sorry, no reviews found.';
				htmlR += '				</div>		';
				htmlR += '			</div>';
				htmlR += '			<div class="rightcol">';
				htmlR += '				&nbsp;		';
				htmlR += '			</div>	';
				htmlR += '		</div> ';
			}
			var linkText = '';
			var link = '';
			var fdLocalFlavorLink = 'http://www.yelp.com/search?find_desc=local%20flavor&find_loc=' + city + '%2C+' + state + '&ns=1';
			var fdRestaurantsLink = 'http://www.yelp.com/search?find_desc=restaurants&find_loc=' + city + '%2C+' + state + '&ns=1';
			var fdShoppingLink = 'http://www.yelp.com/search?find_desc=shopping&find_loc=' + city + '%2C+' + state + '&ns=1';
			var fdLBusinessesLink = 'http://www.yelp.com/search?find_desc=&find_loc=' + city + '%2C+' + state + '&ns=1';
			switch (tab) {
			case 'lndRestaurants':
				linkText = 'Restaurants';
				link = fdRestaurantsLink;
				break;
			case 'lndShopping':
				linkText = 'Shopping';
				link = fdShoppingLink;
				break;
			case 'lndFlavor':
				linkText = 'Local Flavor';
				link = fdLocalFlavorLink;
				break;
			}
			htmlR += '<div class="businessresult line">';
			htmlR += '		<div class="leftcol">';
			htmlR += '			<div class="itemheading">';
			htmlR += '				<a href="' + link + '">See more ' + linkText + '</a>';
			htmlR += '			</div>';
			htmlR += '			<div class="itemheading">';
			htmlR += '				<a href="' + fdLBusinessesLink + '">Find more businesses in ' + city + ', ' + state + '</a>';
			htmlR += '			</div>';
			htmlR += '		</div>';
			htmlR += '		<div class="rightcol">';
			htmlR += '			<div id="yelpButton">';
			htmlR += '			<a href="http://yelp.com"><img src="http://static4.px.yelpcdn.com/static/20091130276394575/i/developers/reviewsFromYelpRED.gif" alt="Yelp.com" /></a>';
			htmlR += '			</div>';
			htmlR += '		</div>';
			htmlR += '	</div>';
			return htmlR;
		}
	}());

	/* Q&A AJAX form submission */
	$('#questiona').submit(function () {
		var data = {};
		var form = $('#questiona');
		form.find(':input').each(function () {
			var $elm = $(this);
			if ($elm.val() == 'Question' || $elm.val() == 'Email Address (optional)') {
				$elm.val(''); // Setting to null since this is default text.
			}
			data[$elm.attr('name')] = $elm.val();
		});

		$.getJSON('/search-tip/submit', data, function (data) {
			if(data.success == true){
				form.hide();
				form.prev('h2').after('<p class="success">Success!<br/> Your question has been submitted.<br><br><span class="submitNewQuestion" style="cursor:pointer;color:#07479b">Submit another question.</span></p>');
				form.prev('.success').children('.submitNewQuestion').click(function(){ 
					form.prev('.success').remove(); 
					form.show(); 
					form.find('textarea').val('');
				});
			}else{
				form.hide();
				form.prev('h2').after("<p class='error'>Error<br/> We're sorry. There was an error submitting your question. "+ data.message +"<br><br><span class='submitNewQuestion' style='cursor:pointer;color:#07479b'>Try Again.</span></p>");
				form.prev('.error').children('.submitNewQuestion').click(function(){ 
					form.prev('.error').remove();
					form.show();
				});     
			}
		});
		return false;
	});

	jQuery.fn.pieGraph = function () {
		if (!this.length) {
			return;
		}
		var canvas, getColor, resetColors, data = [], width = 350, height = 190;
		canvas = new Raphael(this[0]);

		function toRadians(deg) {
			return deg * (Math.PI / 180);
		}

		(function () {
			var color = -1, colors;
			colors = ['#fcb040', '#8ec63f', '#24a9e1', '#f37895', '#652d90', '#f1592a', '#fef200'];

			getColor = function () {
				return colors[color = (color + 1) % colors.length];
			};

			resetColors = function () {
				color = -1;
			};
		}());


		(function () {
			var table = $('#pieGraph').parent().parent().children('table');

			/* Extract data from table */
			table.find('td').each(function (index) {
				if (index) {
					data.push($(this).text().replace(/%$/, ''));
				}
			});

			/* Add legend to table */
			table.find('th').each(function (index) {
				if (index) {
					$(this).html('<div style="float: left; width: 10px; height: 10px; border: 1px #000 solid; margin: 2px 4px 2px 2px; background: ' + getColor() + '"></div>' + $(this).text());
				}
			});

			resetColors();
		}());

		function pie(x, y, radius, data) {
			var set, angle, delta, cx, cy, j, path;
			set = canvas.set();
			angle = 0;
			cx = Math.cos(toRadians(angle)) * radius;
			cy = Math.sin(toRadians(angle)) * radius;

			for (j = 0;j < data.length; j+= 1) {
				path = 'M0,0 L' + cx + ',' + cy;
				delta = (data[j] / 100) * 360;
				angle -= delta;
				cx = Math.cos(toRadians(angle)) * radius;
				cy = Math.sin(toRadians(angle)) * radius;

				path += ' A' + radius + ',' + radius + ' 1 ' + (delta > 180 && 1 || 0) + ',0 ' + cx + ',' + cy + 'z';
				set.push(canvas.path(path).attr({
					fill: getColor(),
					stroke: 'none'
				}));
			}

			set.push(canvas.circle(0, 0, radius).attr({
				stroke: '#6b6b6b',
				'stroke-width': '3',
				fill: 'none'
			}));

			set.translate(x, y);
		}

		pie(width / 2, height / 2, (Math.min(width, height) - 40) / 2, data);
	};

	jQuery.fn.barGraph = function (data) {
		if (!this.length) {
			return;
		}
		var canvas, width = 215, height = 125;
		canvas = new Raphael(this[0]);
		
		/* Price Labels */
		(function () {
			var y, maxLabels, step, labels;
			y = 0;
			maxLabels = 6;
			step = (data.range.max - data.range.min) / (maxLabels - 1);
			labels = canvas.set();
			for (j = 0; j < maxLabels;j += 1) {
				labels.push(canvas.text(0, j * 20, '$' + (data.range.max - j * step)));
			}

			labels.translate(40, 10);
			labels.attr({
				font: '12px Arial',
				'text-anchor': 'end'
			});
		}());

		/* Bar Graphs */
		(function () {
			var j, maxHeight, labels;
			maxHeight = height - 10;
			labels = canvas.set();

			for (j = 0;j < data.values.length;j += 1) {
				var h = Math.floor(Math.random() * 100);
				h = 0;
				canvas.rect(j * 35, maxHeight, 22, maxHeight - h).attr({
					stroke: 'none',
					fill: '#6BC3FA',
					y: 5 + maxHeight - Math.min(maxHeight, ((data.values[j].price - data.range.min) / (data.range.max - data.range.min)) * maxHeight)

				})
				.translate((data.values.length * 35) / 2, 0);

				labels.push(canvas.text(j * 35, 0, data.values[j].label));
			}

			labels.attr({
				stroke: 'none',
				fill: '#000',
				font: 'bold 14px arial, helvetica'
			})
			.rotate(270)
			.translate((data.values.length * 35 / 2) + 10, maxHeight / 2);
		}());

		/* Graph Border */
		canvas.set()
		.push(canvas.rect(45, 5, 6, 118))
		.push(canvas.rect(45, 117, 165, 6))
		.attr({
			stroke: 'none',
			fill: '#000'
		});
	};

	jQuery.fn.speedometerGraph = function (percent) {
		if (!this.length) {
			return;
		}
		var canvas, getColor, data, width = 215, height = 90;
		canvas = new Raphael(this[0]);
		data = [16.6, 16.8, 16.6];
		percent = percent || 0;

		function toRadians(deg) {
			return deg * (Math.PI / 180);
		}

		getColor = (function () {
			var color = -1, colors;
			colors = ['#31b44a', '#fcb040', '#ee4037'];
			return function () {
				return colors[color = (color + 1) % colors.length];
			};
		}());

		function pie(x, y, radius, data, style) {
			var set, angle, delta, cx, cy, j, path, piece;
			set = canvas.set();
			angle = 0;
			cx = Math.cos(toRadians(angle)) * radius;
			cy = Math.sin(toRadians(angle)) * radius;

			for (j = 0;j < data.length; j+= 1) {
				path = 'M0,0 L' + cx + ',' + cy;
				delta = (data[j] / 100) * 360;
				angle -= delta;
				cx = Math.cos(toRadians(angle)) * radius;
				cy = Math.sin(toRadians(angle)) * radius;

				path += ' A' + radius + ',' + radius + ' 1 ' + (delta > 180 && 1 || 0) + ',0 ' + cx + ',' + cy + 'z';
				piece = canvas.path(path);
				if (!style) {
					piece.attr({
						fill: getColor(),
						stroke: 'none'
					})
				} else {
					piece.attr(style);
				}

				set.push(piece);
			}

			set.translate(x, y);
		}

		/* Multi-colored pieces */
		pie(width / 2, height - 2, 70, data);


		/* Dial */
		(function () {
			var base = {
				x: (width / 2) - 3,
				y: height - 62
			};
			canvas.rect(base.x, base.y, 6, 55).attr({
				fill: '#fff',
				stroke: 'none'
			}).rotate((percent / 100) * 180 - 90, base.x + 5, base.y + 55);
		}());

		/* Rotator */
		canvas.circle((width / 2), height - 7, 7).attr({
			stroke: 'none',
			fill: '#000'
		});

		/* Outline */
		pie(width / 2, height - 2, 70, [50], {
			fill: 'none',
			stroke: '#000',
			'stroke-width': 4
		});

		/* Percentage Marks */
		(function () {
			var text = canvas.set();
			text.push(canvas.text(20, 80, '0%'));
			text.push(canvas.text(35, 30, '25%'));
			text.push(canvas.text(110, 6, '50%'));
			text.push(canvas.text(180, 30, '75%'));
			text.push(canvas.text(198, 80, '100%'));
			text.attr('font', '12px arial');
		}());
	};
}(this.jQuery, this));

