
function adjustPercentage(node){
	node.children('div').each(function(){
		var width = $(this).text();
		$(this).css({"width":width});
	});
}
$(document).ready(function(){
	$('.percentage').each(function(){
		adjustPercentage($(this));
	});
});
$(document).ready(function(){
	var elems = $('div.dotd');
	elems.each(function(){
		var node = $(this);
		var offset = node.offset();
		var height = node.outerHeight();
		var width = node.outerWidth();
		var cover = $('<div class="coming-soon"><span>Coming Soon</span></div>');
		cover.css({
			left:offset.left,
			top:offset.top,
			lineHeight:height+'px',
			height:height,
			width:width,
			opacity:0.7
		});
		$('body').append(cover);
	});
});
$(document).ready(function(){
	var login, waiting;
	var link = $('#sign_in');
	var hide_timeout;
	var popup;
	link.bind('click', showLogin);
	function showLogin(e){
		if(!login){
			waiting = true;
			$.ajax({
				"url":"/ajax/login",
				"type":"get",
				"dataType":"html",
				"success":function(response){
					login = $(response);
					$('body').append(login);
					login.find('form').bind('submit', submitLogin);
					login.find('a.facebook').bind('click', function(){
						var anchor = $(this);
						//loginWindow(anchor.attr('href'));
						//return false;
					});
					if(waiting)
						showLogin();
				}
			});
			$('body').bind('click', function(e){
				clearTimeout(hide_timeout);
				hide_timeout = setTimeout(function(){
					hideLogin(e);
				}, 100);
			});
			return false;
		}
		else if(e && !login.is(':hidden')){
			hideLogin(e);
			return false
		}
		link.addClass('sign-in-active');
		var offset = link.offset();
		login.css({
			"left":offset.left-login.outerWidth()+link.outerWidth()+"px",
			"top":offset.top+link.outerHeight()+"px"
		});
		login.show();
		return false;
	}
	function loginWindow(src){
		createloginWindow(src);
		popup.focus();
	}
	
	function createloginWindow(src){
		var width = 800;
		var height = 500;
		var left = Math.round($(window).width() / 2 - width / 2);
		var top = Math.round($(window).height() / 2 - height / 2);
		popup = open(src, 'login_window', 'width='+width+',height='+height+',left='+left+',top='+top+',resizable=0,scrollbars=0,menubar=0,status=0,titlebar=0,toolbar=0,location=0');
	}
	
	function submitLogin(){
		var data = $(this).serialize();
		$.ajax({
			"url":"/ajax/login",
			"type":"post",
			"dataType":"json",
			"data":data,
			"success":function(response){
				if(response.success){
					window.location.reload();
				} else {
					login.find("div.error").remove();
					var error = $('<div class="error">'+response.message+'</div>');
					login.find("form").prepend(error);
				}
			}
		});
		return false;
	}
	function hideLogin(e){
		if(e && hasParent(e.target, login[0])) return null;
		link.removeClass('sign-in-active');
		login.hide();
	}
	function hasParent(child, node){
		if(child == node) return true;
		if(child.parentNode) return hasParent(child.parentNode, node);
		return false;
	}
});

$(document).ready(function(){
	var node, waiting, child;
	var locale = {};
	var link = $('#locations');
	var anchor = link.children('a');
	var hide_timeout;
	anchor.bind('click', showLocations);
	function showLocations(e){
		if(e && link.hasClass('location-drop')){
			link.removeClass('location-drop');
			return false;
		}
		link.addClass('location-drop');
		clearTimeout(hide_timeout);
		if(!node){
			waiting = true;
			$.ajax({
				"url":"/ajax/areas",
				"type":"get",
				"dataType":"html",
				"success":function(response){
					node = $(response);
					if(node.length > 1){
						var temp = node[1];
						node = $(node[0]);
					}
					var wrapper = $('<div class="locations"></div>');
					wrapper.append(node);
					/*var footer = $('<div class="bottom"></div>');
					var button = $('<a class="button ok" href="#"><span>Ok</span>');
					var cancel = $('<a class="button cancel" href="#"><span>Cancel</span>');
					footer.append(button);
					footer.append(cancel);
					wrapper.append(footer);
					button.bind('click', confirm);
					cancel.bind('click', close);*/
					node = wrapper;
					link.append(node);
					node.find('li a').bind('click', showCities);
					if(temp){
						initCities(temp, node.find('li.selected a'), true);
					}
					
					if(waiting)
						showLocations();
				}
			});
			$('body').bind('mousedown', function(e){
				clearTimeout(hide_timeout);
				hide_timeout = setTimeout(function(){
					hideLocations(e);
				}, 100);
			});
			return false;
		}
		return false;
	}
	function confirm(e){
		if(!locale.city) return;
		$.ajax({
			"url":"/ajax/set-location",
			"data":locale,
			"type":"post",
			"dataType":"json",
			"success":function(response){
				hideLocations();
				if(!response.city && !response.province) return false;
				var name = response.city ? response.city.name : response.province.name;
				anchor.children('strong').html(name);
			}
		});
		return false;
	}
	function close(){
		node.remove();
		node = null;
		hideLocations();
		return false;
	}
	function showCities(){
		var province_id = get_id(this);
		var tag = $(this);
		tag.parent().parent().children('li').removeClass('selected');
		changeProvince(tag.parent());
		$.ajax({
			"url":"/ajax/sub_areas",
			"data":{"parent_id":province_id},
			"type":"post",
			"dataType":"html",
			"success":function(response){initCities(response, tag);}
		});
		return false;
	}
	
	function changeProvince(elem){
		node.children('ul:first').children('li').removeClass('selected');
		elem.addClass('selected');
		locale.province = get_id(elem.children('a'));
		locale.city = null;
	}
	
	function changeCity(elem){
		child.children('li').removeClass('selected');
		elem.addClass('selected');
		locale.city = get_id(elem.children('a'));
	}
	
	function initCities(response, tag, preset){
		var offset = $(tag).position();
		var link_height = $(tag).outerHeight();
		if(child) child.remove();
		child = $(response);
		node.children('ul:first').after(child);
		height = child.outerHeight();
		if(offset.top+link_height > height){
			child.css({"marginTop":offset.top-height+link_height});
		}
		//child.find('a').bind('click', selectCity);
		/*if(!preset || !child.children('li.selected').length)
			child.children('li').addClass('selected');*/
	}
	
	function hideLocations(e){
		if(node && e && hasParent(e.target, node[0])) return null;
		link.removeClass('location-drop');
	}
	function hasParent(child, node){
		if(child == node) return true;
		if(child.parentNode) return hasParent(child.parentNode, node);
		return false;
	}
	function get_id(node){
		return $(node).parent().attr('id').replace(/^[^0-9]+/gi, '');
	}
	function selectCity(){
		changeCity($(this).parent());
		return false;
	}
});

$(document).ready(function(){
	$('input.empty').attr('value', '');
	var last_query;
	var search = $('input[name=search]');
	var form = search.parents('form');
	var def = search.attr('title');
	if(!search.val()) search.val(def);
	var results;
	var timeout;
	var blur_to;
	var isFocus = false;
	search.bind('focus', function(){
		isFocus = true;
		$(document).bind('click', blur);
		if(blur_to) clearTimeout(blur_to);
		if(search.val() == def){
			search.val('');
		}
		if(results) results.show();
		search.addClass('focus');
		return false;
	});
	search.bind('blur', function(){
		isFocus = false;
	});
	function blur(){
		clearTimeout(timeout);
		if(isFocus) return;
		$(document).unbind('click', blur);
		if(def && search.val() == ""){
			search.val(def);
		}
		if(results) results.hide();
		search.removeClass('focus');
		return false;
		
	}
	search.bind('keyup', function(e){
		switch(e.keyCode){
			case 40:
				return down();
			case 38:
				return up();
			case 13:
				if(current) return enter();
		}
		if(timeout) clearTimeout(timeout);
		var query = search.val();
		if(query.length < 3) return;
		timeout = setTimeout(function(){
			queue(query);
		}, 100);
	});
	form.bind('submit', function(){
		isFocus = false;
		blur();
		if(window.Search && window.Search.type == "regular"){
			var data = serializeJSON(form);
			if(data.search == def) data.search = null;
			data.page = 1;
			$.bbq.pushState( window.Search.serialize(data) );
		}
		else location.href = '/search#'+form.serialize();
		return false;
	});
	function queue(query){
		if(query == last_query) return;
		last_query = query;
		$.ajax({
			"url":"/ajax/search/"+query,
			"type":"post",
			"dataType":"json",
			"success":function(response){
				if(!isFocus) return;
				if(results) results.remove();
				current = null;
				results = $('<div class="search-results"></div');
				if(form.attr('name') == "mini_search"){
					results.addClass('mini-results');
				}
				var list = $('<ul></ul>');
				results.append(list);
				var offset = search.offset();
				var height = search.outerHeight();
				for(var i = 0; i < response.length; i++){
					var item = response[i];
					var li = $('<li><a href="/restaurant/'+item.url+'">'+item.name+' <small>'+item.street+' - '+item.city+'</small></a></li>');
					list.append(li);
					li.children('a').bind('mousedown', function(){
						window.location.href = $(this).attr('href');
					});
					$('body').append(results);
					if(form.attr('name') == "mini_search"){
						results.css({"left":offset.left-9,"top":offset.top+height});
					} else {
						results.css({"left":offset.left-1,"top":offset.top+height});
					}
				}
			},
			"error":function(){
				results.remove();
			}
		});
	}
	var current;
	function up(){
		if(!results) return false;
		if(!current){
			current = results.children('ul').children('li:last');
			current.addClass('selected');
			return false;
		}
		results.children('ul').children('li').removeClass('selected');
		current = current.prev();
		if(current.length){
			current.addClass('selected');
		}
		else{
			current = null;
			up();
		}
	}
	function down(){
		if(!results) return false;
		if(!current){
			current = results.children('ul').children('li:first');
			current.addClass('selected');
			return false;
		}
		results.children('ul').children('li').removeClass('selected');
		current = current.next();
		if(current.length){
			current.addClass('selected');
		}
		else{
			current = null;
			down();
		}
	}
	function enter(){
		search.trigger('blur');
		if(current){
			location.href = current.children('a').attr('href');
		}
	}
});
$(document).ready(function(){
	$('a[href=#top]').bind('click', function(){
		$( 'html, body' ).animate( { scrollTop: 0 }, 'slow' );
		return false;
	});
});

$(document).ready(function(){
	$('form').each(function(){
		var form = $(this);
		form.find('input[type=submit].replace').each(function(){
			var node = $(this);
			node.removeClass('replace');
			node.css({"display":"none"});
			var nu = $('<a href="#" class="'+node.attr('class')+'"><span>'+node.attr('value')+'</span></a>');
			node.after(nu);
			nu.bind('click', function(){
				form.trigger('submit');
				return false;
			});
		});
	});
});

$(document).ready(function(){
	pollFooterLocation();
	setInterval(function(){pollFooterLocation();}, 30);
});

function pollFooterLocation(){
	$('div.footer-wrapper').each(function(){
		var doc_height = $('body').height();
		var footer = $(this);
		var body_height = $('#retainer').height();
		var footer_height = footer.height();
		if(footer.hasClass('footer-pos')){
			body_height+= footer_height;
		}
		if(doc_height > body_height){
			footer.addClass('footer-pos');
		} else if(doc_height < body_height) {
			footer.removeClass('footer-pos');
		}
	});
}

function serializeJSON(form){
	var data = {};
	var results = form.serializeArray();
	$.each(results, function() {
		if (data[this.name] !== undefined) {
			if (!data[this.name].push) {
				data[this.name] = [data[this.name]];
			}
			data[this.name].push(this.value || '');
		} else {
			data[this.name] = this.value || '';
		}
	});
	return data;
}
