function addEvent(obj, evType, fn, useCapture) {
	//Thanks scottandrew.com
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	}
}

function browseNav(index,opt) {
	if (opt=='states') {
		var sections = new Array('browse-states-america','browse-states-canada','browse-states-australia');
	} else {
		var sections = new Array('browse-cities','browse-cuisines','how-it-works');
	}

	if (opt=='states') opt = 'states-';

	for (var i=1;i<=3;i++) {
		document.getElementById(sections[i-1]).className = 'displayOff';
		document.getElementById("browse-nav-" + opt + i).className = '';
	}

	if (index==3) {
		document.getElementById("browse-nav-2").className = 'middlefix';
	}
	document.getElementById(sections[index-1]).className = (opt=='') ? 'displayOn' : 'browse-states displayOn';
	document.getElementById("browse-nav-" + opt + index).className = 'selected';
}


function switchOnOff() {
	var displayOnClass = "displayOn";
	for(var i=0; i<arguments.length; i++) {
		if (typeof(arguments[i])=="boolean") {
			var displayClass = (arguments[i]) ? displayOnClass : "displayOff";
		} else {
			if (i==0) {
				displayOnClass = arguments[0];
			} else {
				document.getElementById(arguments[i]).className = displayClass;
			}
		}
	}
}

function submitOnEnter(obj,evt) {
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (charCode==13) {
		evt.cancel = true;
		getNextParentTag(obj,'form').submit();
		return false;
	}
	return true;
}

function submitOnEnterHeader(obj,evt) {
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (charCode==13) {
		evt.cancel = true;
		if ($('q').val()=="I'm hungry for...") $('q').val('');
		document.getElementById('search-button').click();
		return false;
	}
	return true;
}

function bindRatingWidgets() {
	$("div.rate-u a,div.rate-a a,div.rate-p a").bind("click", function(){rate($(this));});
	$("div.rate-u a,div.rate-a a,div.rate-p a").bind("mouseover", function(){rateOver($(this));});
	$("div.rate-u a,div.rate-a a,div.rate-p a").bind("mouseout", function(){rateOut($(this));});
}

$(document).ready(function() {
	bindRatingWidgets();

	$("span.internal-action").hover(
		function () {
			$(this).attr("className","internal-action-hover");
		},
		function () {
			$(this).attr("className","internal-action");
		}
	);
});

function rate(obj) {
	var randNum = Math.round(Math.random()*1000000);

	var pid = $(obj).parent().attr("id").split("-")[1];
	var r = $(obj).attr("rel");
	$(obj).parent().attr("rel",r + "-user");
	$(obj).parent().attr("className","rate-u");

	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ratePlace.php",
		data: "pid=" + pid + "&r=" + r + "&rand=" + randNum,
		success: function(msg) {
			msgArr = msg.split(";");
			if (msgArr[0]!="1") {
				document.location = 'http://foodio54.com/signin.php';
			}
		}
	});

}

function rateOver(obj) {
	var r = obj.attr("rel");

	$(obj).parent().children("a").each(function (i) {
		$(this).attr("className",($(this).attr("rel")<=r) ? "rateOn" : "rateOff");
	});
}

function rateOut(obj) {
	var r = $(obj).parent().attr("rel");

	obj.className = (obj.rel<=r) ? "rateOn" : "rateOff";
	$(obj).parent().children("a").each(function (i) {
		$(this).attr("className",($(this).attr("rel")<=r) ? "rateOn" : "rateOff");
	});
}

function refreshKNN() {
	var randNum = Math.round(Math.random()*1000000);
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajaxKNN.php",
		data: "&rand=" + randNum
	});
}

function setSearchSort(so) {
	document.cookie = "so=" + so + "; expires=Thu, 01-Jan-2017 00:00:01 GMT";
}

function toggleFastFood(obj) {
	if (obj.checked) {
		document.cookie = "nofastfood=Y; expires=Thu, 01-Jan-2017 00:00:01 GMT";
	} else {
		document.cookie = "nofastfood=N; expires=Thu, 01-Jan-2017 00:00:01 GMT";
	}
}

function getChefmoz(pid) {
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajax_chefmoz.php",
		data: "pid=" + pid,
		success: function(msg) {
			var reviews = msg.split("<hr>");
			var ul = document.getElementById("comments");
			for (var i=0;i<reviews.length-1;i++) {
				reviewli = document.createElement("li");
				reviewli.innerHTML = reviews[i];
				ul.appendChild(reviewli);
			}
		}
	});
}

function getAvailable() {
	objUserName = $("#username");

	if (objUserName.val().length>0) {
		$.ajax({
			type: "GET",
			url: "http://foodio54.com/checkUsernameAvailability.php",
			data: "username=" + objUserName.val(),
			beforeSend: function() { $("#username").className = "displayOff"; },
			success: function(msg) {
				objAvailMsg = $("#availMsg");
				objUserName = $("#username");

				if (msg=="0") {
					objAvailMsg.attr("innerHTML","Good news, the username &quot;" + objUserName.val() + "&quot; is available.");
					objAvailMsg.attr("className","row username-ok");
				} else {
					objAvailMsg.attr("innerHTML","Sorry, the username &quot;" + objUserName.val() + "&quot; is already taken, please select another.");
					objAvailMsg.attr("className","row username-taken");
				}
			}
		});
	}
}

function writeEmbeddedObject(embedded_object) {
	document.write(embedded_object);
	document.write('\n');
}

function findAdAddr(loctype) {
	if (loctype=="addr") {
		data = "addr=" + $('#addr').val() + "&city=&state=";
	} else {
		data = "addr=&city=" + $('#city').val() + "&state=" + $('#state').val();
	}

	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajaxGetLoc.php",
		data: data,
		success: function(msg) {
			if (msg=="invalid") {
				alert("invalid");
			} else {
				loc = msg.split(",");
				map.setCenter(new GLatLng(loc[0],loc[1]),7);
			}
		}
	});
}

function searchBoxTextFocus(obj) {
	if ((obj.value=="Located near...")||(obj.value=="I'm hungry for...")) {
		obj.value = "";
	}
}

function searchBoxTextBlur(obj) {
	if (obj.value=="") {
		if (obj.id=="loc") {
			obj.value = "Located near...";
		} else {
			obj.value = "I'm hungry for...";
		}
	}
}

function getRecs(miles) {
	var randNum = Math.round(Math.random()*1000000);
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajaxRecs.php",
		data: "miles=" + miles + "&rand=" + randNum,
		success: function(msg) {
			var div = msg.indexOf("|");
			var tot = msg.substring(0,div);
			var avg = msg.substring(div+1,msg.indexOf("|",div+1));
			if ((miles==10)&&((tot<5)||(avg<3))) {
				getRecs(20);
			} else {
				$('#loader').attr('className','displayOff');
				$('#col-listings').attr('className','rec-listings');
				$('#recs').html(msg.substring(msg.indexOf("|",div+1)+1));
			}
		}
	});
}

function sendToMobile(pid) {
	var selector = "#row" + pid + " ul.listing-actions";
	var SMStoEmailForm = "<div id='sms"+pid+"' class='sms-form'><label for='carrier"+pid+"'>Carrier:</label><select id='carrier"+pid+"'><option value='1'>Alltel Wireless</option><option value='2'>AT&T Wireless</option><option value='3'>Boost Mobile</option><option value='4'>Helio</option><option value='5'>Nextel</option><option value='6'>Sprint PCS</option><option value='7'>T-Mobile</option><option value='8'>Verizon</option><option value='9'>Virgin Mobile (US)</option><option value='10'>Virgin Mobile (Canada)</option></select><label for='mobile"+pid+"'>Mobile Number:</label><input type='text' id='mobile"+pid+"' /><input type='button' value='Send' onclick=\"sendSMS("+pid+",$('#carrier"+pid+"').val(),$('#mobile"+pid+"').val());\" /></div>";
	if (document.getElementById("sms" + pid) == null) {
		$(selector).after(SMStoEmailForm);
	}
}

function sendToMobileListing(pid) {
	var selector = "ul#listing-actions-" + pid;
	var SMStoEmailForm = "<div id='sms"+pid+"'><label for='carrier"+pid+"'>Carrier:</label><select id='carrier"+pid+"'><option value='1'>Alltel Wireless</option><option value='2'>AT&T Wireless</option><option value='3'>Boost Mobile</option><option value='4'>Helio</option><option value='5'>Nextel</option><option value='6'>Sprint PCS</option><option value='7'>T-Mobile</option><option value='8'>Verizon</option><option value='9'>Virgin Mobile (US)</option><option value='10'>Virgin Mobile (Canada)</option></select><label for='mobile"+pid+"' style='padding-left:5px;'>Mobile Number:</label><input type='text' id='mobile"+pid+"' style='width:85px;' /><input type='button' value='Send' onclick=\"sendSMS("+pid+",$('#carrier"+pid+"').val(),$('#mobile"+pid+"').val());\" /></div>";
	if (document.getElementById("sms" + pid) == null) {
		$(selector).after(SMStoEmailForm);
	}
}

function sendSMS(pid,carrier,mobile) {
	var randNum = Math.round(Math.random()*1000000);
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/sendSMS.php",
		data: "pid=" + pid + "&carrier=" + carrier + "&mobile=" + mobile + "&rand=" + randNum,
		success: function(msg) {
			$("#sms"+pid).html("<p>Sent to your mobile device.</p>");
		}
	});
}

function lookupAddr(loc,m,p,q) {
	if (q=="I'm hungry for...") q = "";
	var rand = Math.round(Math.random() * 1000000);
	var locArr = loc.split(" ");
	if (((locArr.length>1)&&(locArr[0].substring(0,1).match(/^[0-9]+$/)))||(loc.indexOf(" & ")>-1)||(loc.indexOf(" and ")>-1)||(loc.indexOf(" at ")>-1)) {
		$.ajax({
			type: "GET",
			url: "http://foodio54.com/ajaxLookupAddr.php",
			data: "loc=" + loc + "&rand=" + rand,
			success: function(msg) {
				var msgArr = msg.split(";");
				loc = msgArr[1];
				document.location="http://foodio54.com/restaurants/" + loc + "/" + m + "/" + p + "/" + q;
			}
		});
	} else {
		loc = loc.replace(/\s/g,"_");
		document.location="http://foodio54.com/restaurants/" + loc + "/" + m + "/" + p + "/" + q;
	}
}

function getNextParentTag(obj,tag) {
	if (obj.parentNode) {
		while (obj.parentNode) {
			obj = obj.parentNode;
			if (obj.nodeName.toLowerCase() == tag.toLowerCase()) return obj;
		}
	}
	return false;
}

function cookieVal(cookieName) {
	cookies = document.cookie;
	var startLoc=cookies.indexOf(cookieName);
	if (startLoc==-1) {
		return("");
	}
	var sepLoc=cookies.indexOf("=",startLoc);
	var endLoc=cookies.indexOf(";",startLoc);
	if (endLoc==-1) {
		endLoc=cookies.length;
	}
	return(cookies.substring(sepLoc+1,endLoc));
}

function deleteCookie(cookieName) {
	document.cookie = cookieName + "=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function isRememberMe() {
	var user = cookieVal('username');
	if (user.indexOf("__utm")>-1) user = "";
	if ($('login_username')!=null && (user!="")) {
		$('#login_username').val(user);
		$('#rememberMe').attr("checked",true);
	}
}

function checkRememberMe() {
	if ($('#rememberMe').attr("checked")==true) {
		document.cookie = "username=" + $('#login_username').val() + "; expires=Thu, 01-Jan-2017 00:00:01 GMT";
	} else {
		deleteCookie('username');
	}
}

function submitForm(formId) {
	document.getElementById(formId).submit();
}


function reportBadListing(pid,reason) {
	if (reason=='c') reason='Closed';
	if (reason=='d') reason='Duplicate';
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/deletePlace.php",
		data: "pid=" + pid + "&reason=" + $('#reason').val(),
		success: function(msg) {
			alert("Thank you, we will remove this place from our index soon.");
		}
	});
}

function sendInternalMsg() {
	var randNum = Math.round(Math.random()*1000000);
	$.ajax({
		type: "POST",
		url: "http://foodio54.com/ajax_sendmsg.php",
		data: "to-uid=" + $('#uid').val() + "&username=" + $('#username').val() + "&subject=" + $('#subject').val() + "&msg=" + $('#msg').val() + "&r=" + randNum,
		success: function(msg) {
			$('#to-uid').val("");
			$('#subject').val("");
			$('#msg').val("");
		}
	});
}

function getUsersForMsg() {
	var username = $('#username').val();
	var randNum = Math.round(Math.random()*1000000);
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajax_getusernames.php",
		data: "username=" + $('#username').val() + "&r=" + randNum,
		success: function(msg) {
			$('#possible-usernames').html(msg);
		}
	});
}

function getGetListing(q,loc) {
	var randNum = Math.round(Math.random()*1000000);
 	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajaxGetListing.php",
		data: "q=" + q + "&loc=" + loc + "&rand=" + randNum,
		success: function(msg) {
			$('#listing-results').html(msg);
		}
	});
}


function getLocationAndNearby(loc) {
	var randNum = Math.round(Math.random()*1000000);
 	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajaxLocationAndNearby.php",
		data: "loc=" + loc + "&rand=" + randNum,
		success: function(msg) {
			$('#location-results').html(msg);
			getListingPrice();
			checkAllAdsSelected();
		}
	});
}

function checkAllAdsSelected() {
	var cityArr = new Array();
	var citylist = $("#citylist").val();
	cityArr = citylist.split(";");

	var citycheckboxes = document.getElementById('location-results').getElementsByTagName('input');
	for (var i=0;i<citycheckboxes.length;i++) {
		found = false;
		for (j=0;j<cityArr.length;j++) {
			if (citycheckboxes[i].value == cityArr[j]) found = true;
		}
		if (found==true) citycheckboxes[i].checked = true;
	}
}

function addAdListing(loc) {
	var cityArr = new Array();
	var citylist = $("#citylist").val();
	cityArr = citylist.split(";");
	var found = false;
	for (var i=0;i<cityArr.length;i++) {
		if (cityArr[i]==loc) found=true;
	}
	if (found==false) {
		$("#citylist").val($("#citylist").val() + loc + ";");
	}
	getListingPrice();
}

function removeAdListing(loc) {
	var cityArr = new Array();
	var citylist = $("#citylist").val();
	var newcitylist = "";
	cityArr = citylist.split(";");
	for (var i=0;i<cityArr.length;i++) {
		if ((cityArr[i]!="")&&(cityArr[i]!=loc)) newcitylist += cityArr[i] + ";"
	}
	$("#citylist").val(newcitylist);

	var citycheckboxes = document.getElementById('location-results').getElementsByTagName('input');
	for (var i=0;i<citycheckboxes.length;i++) {
		if (citycheckboxes[i].value == loc) citycheckboxes[i].checked = false;
	}
}

function manageAdCheckbox(obj) {
	if (obj.checked==true) {
		addAdListing(obj.value);
	} else {
		removeAdListing(obj.value);
	}
	getListingPrice();
}

function getListingPrice() {
	var cityArr = new Array();
	var citylisthtml = "<br class='clear'/><ul>";
	citylist = $("#citylist").val();
	cityArr = citylist.split(";");
	for (var i=0;i<cityArr.length;i++) {
		if (cityArr[i]!="") {
			citylisthtml += "<li>" + cityArr[i] + " <a href=\"javascript:void(0);\" onclick=\"removeAdListing('" + cityArr[i] + "');getListingPrice();\">remove</a></li>";
		}
	}
	citylisthtml += "</ul>";

	var tot = 5 + ((cityArr.length-1) * 5);

	var pif = tot * 10;
	var savings = tot * 2;
	if (tot==5) {
		$('#listing-price').html("<h3 class='clear'>Listing Price</h3><p>Check as many cities as you'd like in the right hand column.</p>");
	} else {
		$('#listing-price').html("<h3 class='clear'>Listing Price</h3><p><strong>$"+tot+".00</strong> per month <strong style='padding:0 15px;'>/</strong> <strong>$"+pif+".00</strong> per year</p><p>Save <strong>$"+savings+".00</strong> by paying in full for a year!</p>" + citylisthtml);
	}
	$('#listing-price').show();
}

function actionNav(i,id) {
	$.ajax({
		type: "GET",
		url: "http://foodio54.com/ajaxInternalAction.php",
		data: "i=" + i + "&id=" + id,
		success: function(msg) {
			document.location = msg;
		}
	});
}