


function getDimensions() {
	var myWidth = 0,
		myHeight = 0;
	if (typeof(window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return {
		width: myWidth,
		height: myHeight
	};
}
var order_hash = {};



function all_values_empty(hash) {
	var all_empty = true;
	for (var i in hash) {
		if (hash[i] != "" && hash[i] !== null) {
			all_empty = false;
			break;
		}
	}
	return all_empty;
}



function get_state_hash_from_page() {
	var hash = {};
	hash.franchise_id = $("#franchise-id-value").attr("value");
	hash.login_enter = $("#login-enter").attr('value');
	hash.login_status = $("#logged-in").attr('value');
	hash.enter_address = $("#enter-address").attr('value');
	hash.address_status = $("#address-status-value").attr('value');
	hash.delivery_time_status = $("#delivery_time-status-value").attr('value');
	hash.restaurant_status = $("#restaurant-status-value").attr('value');
	hash.cart_status = $("#cart-status-value").attr('value');
	hash.checkout_status = $("#checkout-status").attr('value');
	hash.cc_status = $("#cc-status").attr('value');
	hash.contact_info_status = $("#contact_info-status").attr('value');
	hash.tip_status = $("#tip-coupon-status").attr('value');
	return hash;
}



function set_state_hash_to_page(state) {
	$("#franchise-id-value").attr("value", state.franchise_id);
	$("#login-enter").attr('value', state.login_enter);
	$("#logged-in").attr('value', state.login_status);
	$("#enter-address").attr('value', state.enter_address);
	$("#address-status-value").attr('value', state.address_status);
	$("#delivery_time-status-value").attr('value', state.delivery_time_status);
	$("#restaurant-status-value").attr('value', state.restaurant_status);
	$("#cart-status-value").attr('value', state.cart_status);
	$("#checkout-status").attr('value', state.checkout_status);
	$("#cc-status").attr('value', state.cc_status);
	$("#contact_info-status").attr('value', state.contact_info_status);
	$("#tip-coupon-status").attr('value', state.tip_status);
}


function get_order_hash_from_page() {
	if (init_order_hash !== null) {
		return init_order_hash;
	}
	var hash = {};
	//TODO  use jquery.each to set all these values
	if ($("#restaurant-id-value").attr("value") == "" ||  $("#restaurant-id-value").attr("value") == undefined) {
		hash.restaurant_id = null;
	} else {
		hash.restaurant_id = $("#restaurant-id-value").attr("value");
	}
	if ($("#cuisine-id-value").attr("value") == ""  || $("#cuisine-id-value").attr("value") == undefined) {
		hash.cuisine_id = null;
	} else {
		hash.cuisine_id = $("#cuisine-id-value").attr("value");
	}
	if ($("#franchise-id-value").attr("value") == "" || $("#franchise-id-value").attr("value") == undefined) {
		hash.franchise_id = null;
	} else {
		hash.franchise_id = $("#franchise-id-value").attr("value");
	}
	hash.logged_in = $("#logged-in").attr('value');

	if ($("#tip").attr("value") === undefined) {
		hash.tip = null;
	} else {
		hash.tip = $("#tip").val();
	}
	if ($("#selectable-restaurant").attr("value") === undefined) {
		hash.selectable_restaurant = null;
	} else {
		hash.selectable_restaurant = $("#selectable-restaurant").attr("value");
	}
	if ($("#order_note").attr("value") === undefined) {
		hash.note = null;
	} else {
		hash.note = $("#order_note").attr("value");
	}
	hash.coupon = $("#coupon-value").attr("value");
	hash.coupon_code = $("#coupon-code").attr("value");
	hash.payment_code = $("#business_account").attr("value");
	
	hash.tip_status = $("#tip-coupon-status").attr('value');
	hash.checkout_status = $("#checkout-status").attr('value');

	hash.delivery_target = $("#DeliveryTime-value").attr("value");
	// if (all_values_empty(hash.delivery_target)) {
	// 	hash.delivery_target = null;
	// }
	hash.partner_surcharge = 0;
	hash.partner_discount = 0;
	hash.source = 'web';
	hash.total_billed_override = null;
	if ($("#payment-type").attr('value') == ""){
		hash.payment_type = "cash";
	} else {
		hash.payment_type = $("#payment-type").attr('value');
	}
	if (!all_values_empty(get_hash_from_prefix('newuser'))) {
		hash.newuser = {};
		hash.newuser = get_hash_from_prefix('newuser');
	}
	if (all_values_empty(hash.newuser)) {
		hash.newuser = null;
	}
	if (!all_values_empty(get_hash_from_prefix('account'))) {
		hash.account = {};
		hash.account = get_hash_from_prefix('account');
	}
	if (all_values_empty(hash.account)) {
		hash.account = null;
	}
	if (!all_values_empty(get_hash_from_prefix('customer'))) {
		hash.customer = get_hash_from_prefix('customer');
	}
	if (!all_values_empty(get_hash_from_prefix('customer')) && !(get_hash_from_prefix('address').city == 'City') && !(get_hash_from_prefix('address').line1 == 'Street Address')) {
		hash.customer.address = get_hash_from_prefix('address');
	}
	if (all_values_empty(get_hash_from_prefix('customer')) && (!(get_hash_from_prefix('address').city == 'City') || !(get_hash_from_prefix('address').line1 == 'Street Address'))) {
		hash.customer = {};
		hash.customer.address = get_hash_from_prefix('address');
		if (all_values_empty(hash.customer.address)) {
			hash.customer.address = null;
		}
	}
	if (!all_values_empty(get_hash_from_prefix('customer')) && (get_hash_from_prefix('address').city == 'City') && (get_hash_from_prefix('address').line1 == 'Street Address')) {
		hash.customer.address = null;
	}
	if (!all_values_empty(get_hash_from_prefix('contact'))) {
		var temp_hash = {};
		temp_hash.contact = get_hash_from_prefix('contact');
		hash.customer.first_name = temp_hash.contact.first_name;
		hash.customer.last_name = temp_hash.contact.last_name;
		hash.customer.email = temp_hash.contact.email;
		if(hash.customer.address == null || hash.customer.address == undefined){
		    hash.customer.address ={};
		}
		hash.customer.address.phone = temp_hash.contact.phone;
	}
	if (all_values_empty(hash.customer)) {
		hash.customer = null;
	}
	if ($('#new_billing_entered').attr('value') == "true") {
		hash.billing_address = get_hash_from_prefix('billingaddress');
	} else if (!hash.customer == null){
		hash.billing_address = hash.customer.address;
	} else {
		hash.billing_address = null;
	}
	if ($('#credit_card_save_info').attr('checked') == true) {
		hash.save_credit_card = true;
	} else {
		hash.save_credit_card = false;
	}
	
	hash.credit_card = get_hash_from_prefix('creditcard');
	
	if (hash.logged_in == "true" && hash.customer === null) {
		hash.customer = {};
		hash.customer['id'] = $("#customer-id-value").attr("value");
	}
	if (hash.logged_in == "true") {
		hash.customer['id'] = $("#customer-id-value").attr("value");
	}
	var items = [];
	$(".cart-item").each(function() {
		var item_hash = {};
		item_hash.menu_item_id = $(this).find("#menu_item").attr("value");
		item_hash.quantity = $(this).find("#item_quantity").attr("value");
		if ($(this).find("#item_note").attr("value").length < 5) {
			item_hash.note = "";
		} else {
			item_hash.note = $(this).find("#item_note").attr("value");
		}
		var menu_options = $(this).find(".menu_option");
		item_hash.options = jQuery.map(menu_options, function(n, i) {
			return $(n).attr("menu_option_id");
		});
		items.push(item_hash);
	});
	hash.items = items;
	return hash;
}

function editOrder(reload) {
	$("#checkout-status").attr('value', null);
	$("#tip-coupon-status").attr('value', null);
	contextLoad();
	if (reload == true) {
		order = JSON.stringify(get_order_hash_from_page());
		post_to_url('/',{'order':order});
	}
}


function emptyCart(callback) {
	$(".cart-item").each(function() {
		$(this).remove();
	});
	$("#cart-container").remove();
	$("#tip-status").remove();	
	$("#restaurant-id-value").attr("value", "");
	loadDivs("#selected-restaurant", function (){
		eval(callback);
	});
}

function loadSearch() {
	url = '/home/search';
	order_hash = get_order_hash_from_page();
	$('#description').load(url, {'order':JSON.stringify(order_hash)}, function(){
		$("#menu-container").hide();
		$("#option-container").hide();
		$("#info-container").hide();
		$("#description").slideDown();
	});
}

function get_hash_from_prefix(prefix) {
	var hash = {};
	var reg_prefix = new RegExp("^" + prefix + "_");
	$("input[id^='" + prefix + "']").each(function() {
		hash[$(this).attr("id").replace(reg_prefix, "")] = $(this).val();
	});
	$("select[id^='" + prefix + "']").each(function() {
		hash[$(this).attr("id").replace(reg_prefix, "")] = $(this).val();
	});
	return hash;
}


function get_context_from_order(state) {
	var context = null;
	var selection = null;
	var content = null;
	var sanitized_hash = {};
	context = 'landing';
	content = '/home/home';
	if (state.enter_address == 'true' && state.franchise_id === null) {
		selection = 'address';
		content = null;
	}
	if (state.enter_address == 'true' && state.franchise_id !== null) {
		selection = 'franchise_address';
		content = null;
	}
	if (state.login_enter == 'true') {
		selection = 'login';
		content = null;
	}
	if (state.login_status == 'true'){
		selection = 'logged_in';
		content = '/home/search';
		_gaq.push(['_trackPageview', "/place_order_funnel/info_entered.html"]);	
	}
	if (state.address_status == 'true') {
		context = 'delivery_time';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/info_entered.html"]);	
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true') {
		context = 'restaurant';
		content = '/home/search';
		_gaq.push(['_trackPageview', "/place_order_funnel/info_entered.html"]);	
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.login_status == 'true') {
		context = 'restaurant';
		selection = 'logged_in';
		content = '/home/search';
		_gaq.push(['_trackPageview', "/place_order_funnel/info_entered.html"]);	
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.restaurant_status == 'true') {
		context = 'menu';
		selection = null;
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/empty_cart.html"]);	
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.restaurant_status == 'true' && state.cart_status == 'true') {
		context = 'menu';
		selection = 'cart';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/full_cart.html"]);	
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.restaurant_status == 'true' && state.cart_status == 'true'  && state.login_status == 'true') {
		context = 'menu';
		selection = 'cart_logged_in';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/full_cart.html"]);	
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.restaurant_status == 'true' && state.cart_status == 'true' && state.checkout_status == 'true') {
		context = 'checkout';
		selection = 'driver_tip';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/checkout.html"]);
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.restaurant_status == 'true' && state.cart_status == 'true' && state.checkout_status == 'true' && state.login_status == 'true') {
		context = 'checkout';
		selection = 'driver_tip_logged_in';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/checkout.html"]);
	}
	if (state.address_status == 'true' && state.delivery_time_status == 'true' && state.restaurant_status == 'true' && state.cart_status == 'true' && state.checkout_status == 'true' && state.tip_status == 'true') {
		context = 'checkout';
		selection = 'contact_info';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/tip_payment.html"]);
	}
	if (state.cc_status == 'true') {
		context = 'checkout';
		selection = 'contact_info_cc';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/tip_payment.html"]);
	}
	if (state.cc_status == 'true' && state.login_status == 'true' ) {
		context = 'checkout';
		selection = 'contact_info_cc_logged_in';
		content = null;
		_gaq.push(['_trackPageview', "/place_order_funnel/tip_payment.html"]);
	}	
	return [context, selection, content];
}

function set_order_cookie() {
	// TODO - make sure this works when the address is entered
	// $.cookie('order', JSON.stringify(get_order_hash_from_page()));

}

var div_name_url_map = {"#Login":"/home/status_bar_login",
						"#Address":"/home/status_bar_location",
						"#DeliveryTime":"/home/status_bar_delivery_time",
						"#selected-restaurant":"/home/status_bar_restaurant",
						"#description":"/home/status_bar_contact_info/",
						"#cc-payment-info":"/home/status_bar_payment_info/",
						"#cart":"/home/add_tip_coupon",
						"#DriverTip":"/home/status_bar_tip_coupon"
						};

function multiLoad( arglist, callback ) {
    var results = [], n = arglist.length;
    $.each( arglist, function( i, arg ) {
        $( arg[0] ).load( arg[1], arg[2], function() {
            results[i] = arguments;
            if( ! --n ) callback( results );
        });
    });
}

function loadDivs(div_specifier, callback){
	var order = get_order_hash_from_page();
	if (!(div_specifier instanceof Array)){
		div_specifier =[div_specifier];
	}
	var arg_list = jQuery.map(div_specifier, function(n,i){
		return [[n,div_name_url_map[n],{'order':JSON.stringify(order)}]];
	});
	return multiLoad(arg_list,callback);
}

function restaurantHeight(offset){
	var dimensions = getDimensions();
	myHeight = dimensions.height;
	if (myHeight > 593) {
		$(".restaurant-select").height(myHeight - offset);
		$("#right-facets-order").height(myHeight - offset);
	}
}

function itemContainer(offset){
	$(".item-container").show();
	var dimensions = getDimensions();
	myHeight = dimensions.height;
	if (myHeight > 593) {
		$(".item-container").height(myHeight - offset);
	}
}

function landingContext(context, selection, content) {
	var dimensions = getDimensions();
	myHeight = dimensions.height;
	contextArray = [context, selection, content];
	_gaq.push(['_trackEvent', context, selection]);
		// setcontextHistory(contextArray);
	$(".top-tabs").hide();

	if (context == 'landing') {
		if (selection === null || selection == 'logged_in') {
			$("#landing-tabs").show();
			$('#top-status-bar,#middle-status-bar').hide();
		}
		if (selection == null) {
			restaurantHeight(374);
		}
		if (selection == 'logged_in') {
			$("#intro-status-bar").slideUp("slow");
			restaurantHeight(245);
		}
		if (selection === null || selection == 'logged_in') {
			$("#right-facets-order").slideDown();
			$('#top-status-bar, #middle-status-bar').fadeIn("slow");
			$('#status-wait').hide();
		}
		if (selection == 'franchise_address') {
			$('#right-facets-order').slideDown();
			$('#intro-status-bar').slideUp();
			$('#status-wait').hide();
			restaurantHeight(358);
		}
		if (selection == 'login') {
			$("#landing-tabs").show();
			$("#Login-signup-input").slideUp();
			$("#Login-input").slideDown('slow');
			$("#Address-input").hide();
			restaurantHeight(310);
			$("#login:first").focus();
		}
		if (selection == 'address') {
			$("#landing-tabs").show();
			$("#Login-signup-input").slideUp();
			$("#Login-input").hide();
			$("#Address-input").slideDown('slow');
			restaurantHeight(325);
			$("#address_line1:first").focus();
		}
		if (selection == 'signup') {
			$("#Login-signup-input").show();
			$("#landing-tabs").show();
			$("#Address-input, #DeliveryTime-input, #Login-input, #Address-close,#cart-items").hide();
			$("#newuser_email:first").focus();
			restaurantHeight(575);
		}
		if (selection == 'manage') {
			$("#manage-tabs").show();
			$("#account-info").show();
			$("#Address-input, #DeliveryTime-input, #Login-input, #Address-close,#cart-items").hide();
			restaurantHeight(455);
		}

	} else if (context == 'delivery_time') {
		$(".status-input-top").hide();
		$("#option-container, #menu-container, #info-container").hide();
		$("#bottom-status-bar").hide();
		$("#cart-border").hide();
		$("#order_time-tabs").show();
		$("#address-check").show();
		$("#description").show();
		if (selection === null) {
			restaurantHeight(205);
			$("#right-facets-order").show();
			$("#DeliveryTime-input").slideDown();
		}
		$("#event_time_5i:first").focus();
		if (selection == 'order_now') {
			$("#delivery_time-check").show();
			restaurantHeight(245);
		}
		if (selection == 'advanced_order') {
			$("#DeliveryTime-input").show();
			restaurantHeight(320);
		}
	} else if (context == 'restaurant') {
		if (selection == 'logged_in' || selection == null) {
			$("#cart").hide();
			$("#right-facets-order").show();
			$("#option-container, #menu-container, #info-container").hide();
			$("#description").show();
			$('#top-status-bar, #middle-status-bar').show();
			$('#intro-status-bar, #bottom-status-bar').hide();
			$("#add-restaurant-action").hide();
			
		}
		if (selection == null) {
			restaurantHeight(234);
		}
		if (selection == 'logged_in') {
			restaurantHeight(252);
			$('#status-wait').hide();
		}
		if (selection == 'logged_in' || selection == null) {
			$(".status-input-top").hide();
			$("#address-check").show();
			$("#delivery_time-check").show();
			$("#restaurant-tabs").show();
		}
	} else if (context == 'menu') {
		$(".status-input-top").hide();
		$("#address-check").show();
		$("#delivery_time-check").show();
		$("#restaurant-check").show();
		$("#menu-container").show();
		$("#description").hide();
		$("#option-container").hide();
		$("#info-container").hide();
		$('#top-status-bar, #middle-status-bar').show();
		$('#intro-status-bar, #bottom-status-bar').hide();
		$("#checkout-button").show();
		$("#option-container, #description, #info-container").hide();
		$("#menu-container").show();
		$(".item-edit").show();
		$(".remove-contain").show();
		$("#restaurant-info").show();
		
		if( selection == null || selection == 'cart' || selection == 'cart_logged_in' ){
			restaurantHeight(322);
			$("#restaurant-check").show();
			if (get_order_hash_from_page().selectable_restaurant == 'false'){
				$(".restaurant_logo_order").filter(function() { return $(this).attr('restaurant_id');}).each(function(){ if ($(this).attr('restaurant_id') == get_order_hash_from_page().restaurant_id) { $(this).click();} });
			}
		}
		if (selection === null ) {
			$("#menu-tabs").show();
			$("#right-facets-order").show();
		}
		if (selection == 'cart' || selection == 'cart_logged_in') {
			$("#cart-tabs").show();
			$("#cart-border").show();
			$("#cart").slideDown('slow');
			$("#right-facets-order").slideUp();
			$("#selected-restaurant-logo").slideDown();
			$("#description").hide();
			$("#option-container").hide();
			$("#info-container").hide();
			$("#menu-container").show();
			$("#add-restaurant-action").show();
			$("#cart-items").show();
		}
		if (selection == 'cart') {
			itemContainer(388);
		}
		if (selection == 'cart_logged_in') {
			restaurantHeight(340);
			itemContainer(406);
		}	
	} else if (context == 'checkout') {
		// var order = get_order_hash_from_page();
		$(".status-input-top").hide();
		$(".item-edit").hide();
		$(".remove-contain").hide();
		$("#restaurant-info").hide();
		$("#right-facets-order").hide();
		
		if (selection == 'driver_tip' || selection == 'driver_tip_logged_in') {
			$("#checkout-tabs").show();
			$("#selected-restaurant-logo").slideUp();
			$("#checkout-button").hide();
			$("#description").hide();
			$("#option-container").hide();
			$("#info-container").hide();
			$("#menu-container").show();
			$("#bottom-status-bar").fadeIn(500, function() {
				$("#bottom-status-bar").effect("highlight", {}, 500, function() {
					$('#DriverTip').show();
					$("#DriverTip-input").slideDown();
				});
			});
			$("#cart-check").show();
		}
		if (selection == 'driver_tip'){
			itemContainer(505);
		}
		if (selection == 'driver_tip_logged_in') {
			itemContainer(523);
		}
		if (selection == 'contact_info' || selection =='contact_info_logged_in') {
			$("#payment-tabs").show();
			$("#DriverTip").show();
			$("#selected-restaurant-logo").slideUp();
			$("#DriverTip-input").slideUp();
			$("#tip-check").show();
			$("#cart-items").show();
			$("#checkout-button").hide();
			$('#intro-status-bar').hide();
			$("#option-container,#menu-container,#info-container").hide();
			$("#ContactInfo, #description").show();
			$("#ContactInfo-input").slideDown();
			$("#cart-check").show();
		}
		if (selection == 'contact_info') {
			itemContainer(492);
		}
		if (selection == 'contact_info_logged_in') {
			itemContainer(510);
		}
		if (selection == 'contact_info_cc' || selection == 'contact_info_cc_logged_in') {
			$("#intro-status-bar").hide();
			$("#top-status-bar,#middle-status-bar,#bottom-status-bar,#restaurant-check").fadeIn();
			$("#DriverTip").show();
			$("#address-check,#delivery_time-check,#restaurant-check,#cart-check,#tip-check").show();
			$("#payment-tabs").show();
			$('#ContactInfo-input').show();
			$('#cc-payment-info').show();
			$('#ContactInfo').fadeIn();
			// var creditcard = $("#credit_card_number").mask("9999 9999 9999 9999");
			// var creditcard2 = $("#credit_card_verification_value").mask("999");	
			$("#selected-restaurant-logo").hide();
			$("#checkout-button").hide();
			$("#cart-items").slideDown();
			$('#status-wait, #description-wait').hide();
			restaurantHeight(620);
			itemContainer(492);
		}
		if (selection == 'contact_info_cc_logged_in') {
			$('#login-check').show();
			itemContainer(510);
		}
	}
	if (get_order_hash_from_page().logged_in == 'true') {
		$('#login-check').show();
	}
	$("#description").load(content, {'order':JSON.stringify(get_order_hash_from_page())}, function() {
		$("#description").show();
	});
	init_order_hash = null;
}



function contextLoad(content) {
	var x = get_context_from_order(get_state_hash_from_page());
	if (content == false)
	{
	    x[2] = null;
	}
	landingContext(x[0], x[1], x[2]);	
}



function delete_state_hash_from_page() {
	delete_order_hash_from_page();
	$("#login-enter").attr('value', null);
	$("#logged-in").attr('value', null);
	$("#enter-address").attr('value', null);
	$("#address-status-value").attr('value', null);
	$("#delivery_time-status-value").attr('value', null);
	$("#restaurant-status-value").attr('value', null);
	$("#cart-status-value").attr('value', null);
	$("#checkout-status").attr('value', null);
	$("#cc-status").attr('value', null);
	$("#contact_info-status").attr('value', null);
	$("#tip-coupon-status").attr('value', null);
	// contextLoad();
}

function delete_order_hash_from_page() {
	$("#restaurant-id-value").attr("value", null);
	$("#cuisine-id-value").attr("value", "");
	$("#franchise-id-value").attr("value", "");
	$("#tip").attr("value", undefined);
	$("#restaurant-id-value").attr("value", null);
	$("#coupon-value").attr("value", null);
	$("#tip-coupon-status").attr('value', null);
	$("#checkout-status").attr('value', null);
	$("#DeliveryTime-value").attr("value", null);
	$("#payment-type").attr('value', null);
	emptyCart();
}

function place_order() {
	var res = $.post("/home/place_order", JSON.stringify(get_order_hash()), function(data, textStatus) {
		$("#order-complete").html(data);
	});
}



function removeItem(a, context_load) {
	$(a).parent().parent().parent().remove();
	var order_hash = {};
	order_hash.order = JSON.stringify(get_order_hash_from_page());
	var url = "/home/remove_from_cart/";
	$('#status-wait').show();
	$("#cart").load(url, order_hash, function() {
		$('#status-wait').hide();
		$("#cart-items").show();
		$(".item-container").show();
		if (order_hash.logged_in == 'true') {
			itemContainer(426);
		} else {
			itemContainer(408);
		}
		if (context_load != false){
			contextLoad();
		}
	});
}

function editItem(a, menu_item_id) {
	$("#description-wait").show();
	order = get_order_hash_from_page();
	var menu_url = '/home/choose_options/'+menu_item_id;
	$("#description").hide();
	$("#menu-container").hide();
	$("#info-container").hide();
	var address = order.customer.address;
	var menu_options = $(a).parent().parent().find(".menu_option");
	var menu_hash ={"address":JSON.stringify(address),
		"id":$(a).attr("id"), "delivery_time":JSON.stringify(order.delivery_target),
		"options":jQuery.map(menu_options, function(n, i) {return $(n).attr('menu_option_id');}), "note":"" };
	$("#option-container").load(menu_url,menu_hash,function(){
		$("#option-container").show();
		$("#description-wait").hide();
	});
	removeItem(a, false);
}

function loadCustomerOrders(customer_id) {
	var order_hash={};
	order_hash['order'] = get_order_hash_from_page();
	order_hash['order']['customer_id'] = customer_id;
	order = JSON.stringify(order_hash['order']);
	$('#description-wait').show();
	$('#description').load('/home/customer_orders/', {'order':order}, function() {
		$('#description-wait').hide();
		if (myHeight > 593) {
			$('#order-history').height(myHeight - 374);
		}
	});
}


//From the _login partial
function loginSuccess(r) {
	$("#Login").html(r);
	$("#logged-in").attr('value', "true");
	loadDivs(["#Address","#DeliveryTime"], function() {
		loadDivs(["#selected-restaurant"], function() {
			$('.ac_results').hide();
			$("#delivery_time-status-value").attr('value', 'true');
			$("#intro-status-bar").slideUp("slow");
			contextLoad();
		});
	});
}

var contextHistory = {
	'start': new Date(),
	'history': []
};



function setcontextHistory(context) {
	var now = new Date();
	var delta = (now - contextHistory.start) / 1000;
	context_index = contextHistory.history.length;
	contextHistory.history[context_index] = [context, delta, get_state_hash_from_page(), get_order_hash_from_page()];
}



function getcontextHistory(delta) {
	context_index = contextHistory.history.length;
	context_index = context_index - 1 - delta;
	return contextHistory.history[context_index];
}

$("[target_context]").live("click", function() {
	if ($(this).attr("callback") != "" && $(this).attr("callback") !=undefined){
		var callback_function = $(this).attr("callback");
		callback_function = callback_function.substring(0,callback_function.length-1);
		if ($(this).attr("target_selection") == "null") {
			selection = '",' + null + ')';
		} else {
			selection = '","' + $(this).attr("target_selection") + '")';
		}
		var landing_context = 'landingContext("'+ $(this).attr("target_context") + selection;
		callback_function = callback_function + "'" + landing_context + "'" + ")";
		eval(callback_function);
	} else {
		landingContext($(this).attr("target_context"), $(this).attr("target_selection"));
	}
});

$("[target_div]").live("click", function() {
	var url = $(this).attr("url");
	var div_selector = $(this).attr("target_div");
	var div_id = $(this).attr("id");
	$(div_selector).load(url, '', function() {
	});
});
$("[target_hide]").live("click", function() {
	var div_hide = $(this).attr("target_hide");
	$(div_hide).hide();
});
$("[target_show]").live("click", function() {
	var div_show = $(this).attr("target_show");
	$(div_show).show();
	$(div_show).effect("highlight", {},
	1500);
});
$("[target_change]").live("click", function() {
	var div_change = $(this).attr("target_change");
	var add_class = $(this).attr("add_class");
	var remove_class = $(this).attr("remove_class");
	$(div_change).addClass(add_class);
	$(div_change).removeClass(remove_class);
});
$("#add-restaurant-action").live("click",function(){
	$("#right-facets-order").slideDown(function(){
		restaurantHeight(422);
		$("#add-restaurant-action").hide();
	});
	$(".item-container").hide();
});
$(".restaurant_logo_order").live("click", function() {
    viewRestaurantMenu($(this).attr("restaurant_id"));
});
function viewRestaurantMenu(restaurant_id)
{
    $('#description-wait').show();
	
	var order = get_order_hash_from_page();
	$('#restaurant-id-value').attr('value', restaurant_id);
	$("#restaurant-status-value").attr('value', "true");
	var menu_url = "/home/restaurant_menu/";
	if (order.customer !== null) {
		$(".top-tabs").hide();
		$("#menu-tabs").show();
		var address = order.customer.address;
		menu_hash = {
			"address": JSON.stringify(address),
			"id": restaurant_id,
			"delivery_time": JSON.stringify(order.delivery_target)
		};
		$("#menu-container").load(menu_url, menu_hash, function() {
			$('#description-wait').hide();
			$('#description').hide();
			$('#menu-container').show();
			$('#option-container').hide();
			loadDivs("#selected-restaurant", function(){
				$("#right-facets-order").show();
				restaurantHeight(322);
				$("#add-restaurant-action").hide();
			});
		});
	} else {
		menu_hash = {
			"id": restaurant_id,
			"delivery_time": JSON.stringify(order.delivery_target)
		};
		$("#menu-container").load(menu_url, menu_hash, function() {
			$('#description-wait').hide();
			$('#description').hide();
			$('#menu-container').show();
			$('#option-container').hide();
			loadDivs("#selected-restaurant", function(){
				$("#right-facets-order").show();
				restaurantHeight(322);
				$("#add-restaurant-action").hide();
			});
		});
	}
}
$(".cuisine").live("click", function() {
	order = get_order_hash_from_page();
	$(".cuisine").removeClass('selected_cuisine');
	$(this).addClass('selected_cuisine');
	$('#cuisine-id-value').attr('value', $(this).attr("id"));
	loadDivs("#selected-restaurant", function(){
		$("#right-facets-order").show();	
	});
});
$("#top-login").click(function() {
	$("#login-enter").attr('value', true);
	$("#enter-address").attr('value', false);
	contextLoad();
});
$("#top-address").click(function() {
	$("#enter-address").attr('value', true);
	$("#login-enter").attr('value', false);
	contextLoad();
});

$("#top-checkout").click(function() {
	$("#checkout-status").attr('value', true);
	contextLoad();
});
$("#top-cuisines").click(function() {
	var url = "/home/cuisines";
	$("#description").load(url);
});
$("#top-featured").click(function() {
	var url = "/home/search";
	$("#description").load(url);
});
$("#Address").click(function() {
	$("#Address-input").show();
});
$(".load-customer_orders").click(function() {
	loadCustomerOrders();
});
function checkout(callback){
	if (parseFloat($('#items-billed').val()) > parseFloat($("#minimum-order").val())) {
		$("#checkout-status").attr('value', true);
		eval(callback);
	} else {
		alert("Minimum order size of $"+$("#minimum-order").attr("value"));
	}
}

function infoBack(back) {
	$("#info-container").hide();
	$("#menu-container").hide();
	$("#option-container").hide();
	$("#description").hide();
	
	back_string = "#" + back;
	$(back_string).show();
}
function orderNow(callback) {
	$("#DeliveryTime-value").attr("value", "");
	var url = "/home/status_bar_delivery_time";
	loadDivs("#DeliveryTime", function() {
		$("#DeliveryTime-input").hide();
		eval(callback);
	});
}

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}

function place_order_action() {
    $('#ContactInfo').slideUp();
    $("#description-wait").show();
    $("#payment-tabs").hide();
    $("#post-payment-tabs").show();
    emptyCart(false);
    $("#cart-border").hide();
    $("#cart-status").hide();
    $('#top-status-bar').fadeOut("slow");
    $('#middle-status-bar').fadeOut("slow");
    $('#bottom-status-bar').fadeOut("slow", function() {
    	$('#thank_you-status-bar').fadeIn("slow");
	});
}
