//search input validation + submit
(function($) {
$.fn.origValidate=function(o){
	o = $.extend({
		form: null,
		errorMsg: false,
		origText: true,
		searchText: "Search",
		onSubmit: null
    }, o || {}); 


    return this.each(function(){
		var c = $(this);
		if(o.form){
			$(o.form).submit(function(){
				if((c.val() != o.searchText) && (c.val() != o.errorMsg)){
					if(typeof o.onSubmit == "function"){
						return o.onSubmit.call(this, o.form);
					} else {
						return true;
					}
				} else {
					if(o.errorMsg){
						c.addClass("error");
						c.val(o.errorMsg);
					}
					return false;
				}
			});		
		}
		$(this).focus(function(){
			if(o.origText) this.value=((this.value==o.searchText) || (this.value==o.errorMsg)) ? '' : this.value;
			if(o.errorMsg) c.removeClass("error");
		}).blur(function(){
			if(o.origText) this.value=(this.value=='') ? o.searchText : this.value;
		});
	});
}})(jQuery);

var pageads=new Array();

function updateTimeStamp() {

        var timestampEls = document.getElementsByName("timestamp");
        for (var i=0; i < timestampEls.length ; i++)
        {
                var timestampOldElems = timestampEls[i].innerHTML.split(" ");
				if(timestampOldElems.length > 3){
					var currentDate = new Date(('20'+timestampOldElems[0].split("/")[2])
                    	                            ,timestampOldElems[0].split("/")[0]-1,
                        	                        timestampOldElems[0].split("/")[1]);

	                var previousDate = new Date(currentDate.getTime() - (24*60*60*1000));

	                timestampEls[i].innerHTML = (previousDate.getMonth() + 1) + "/" + previousDate.getDate() + "/" +  previousDate.getFullYear().toString().substring(2) + " at " + timestampOldElems[2] + " " + timestampOldElems[3];
	            }

        }

}


function reloadAds() {
	$("div.adContainer div.content").each(function(){

	    var first_obj = this.children[0];
	    var rand_num = Math.round( Math.random()*1000000000 );

	    if(first_obj.tagName=="IFRAME"){
	    	first_obj.src = first_obj.src.replace(/o=\d+/,"o="+rand_num);
	    } else{
	    	first_obj = this.children[1];
			var new_src = first_obj.src.replace(/o=\d+/,"o="+rand_num).replace(/ord=\d+/,"ord="+rand_num);
	    	var sz = first_obj.src.match(/sz=(\w+)/)[1];
	    	this.innerHTML = "<iframe src='" + new_src.replace(/\/adj\//,"/adi/") + "' width='"+sz.split("x")[0]+"' height='"+sz.split("x")[1]+"' frameborder='no' border='0' marginwidth='0' marginheight='0' scrolling='no'></iframe>";
		}
	}); 
}

function reloadSpecificAd(sz){
	$("div.ad-"+sz+".adContainer div.content").each(function(){
		//Needed for Firefox 2.0/3.0 because it doesn't support ".children"
	    var first_obj = this.children ? this.children[0] : ((this.childNodes.length > 1) ? this.childNodes[1] : this.childNodes[0]);
	    var rand_num = Math.round( Math.random()*1000000000 );

		if(this.offsetHeight){
	    	if(first_obj.tagName=="IFRAME"){
	    		first_obj.src = first_obj.src.replace(/o=\d+/,"o="+rand_num).replace(/ord=\d+/,"ord="+rand_num);
	    	} else{
	    		first_obj = first_obj.nextSibling;
				var new_src = first_obj.src.replace(/o=\d+/,"o="+rand_num).replace(/ord=\d+/,"ord="+rand_num);
	    		var sz = first_obj.src.match(/sz=(\w+)/)[1];
	    		this.innerHTML = "<iframe src='" + new_src.replace(/\/adj\//,"/adi/") + "' width='"+sz.split("x")[0]+"' height='"+sz.split("x")[1]+"' frameborder='no' border='0' marginwidth='0' marginheight='0' scrolling='no'></iframe>";
			}
		}
	});
}

function nymag_setMetadata( metadata ) {
	mp_setMetadata(metadata);
}
function nymag_pageView(){
	mp_pageView();
}

function loadNav(){
	if($(this).find("div").length <= 1){
		$(this).append("<div id=\"nav-loader\"><img src=\"/gfx/ico/loading.gif\" width=\"32\" height=\"32\" /></div>");
		setTimeout ( "ajaxMagNav()", 1100 );
		} else {
		$("#nav").fadeIn("fast");
		}
}

function ajaxMagNav(){
	var ajaxNav = "/includes/components/mast/nav/navbar-only.txt"
	$("#nymag-nav").load(ajaxNav, function(){ 	
		$("#nav-loader").css("display","none");
		$("#nav").css("display","none").fadeIn("fast");
		$("#nav li.top").hover(function(){
			$(this).addClass("hover");
		},function () {
			$(this).removeClass("hover");
		});
	});
}

function collapseNav(){
	$("#nymag-nav").css("display","none");
}

function callError(input, msg){
	input.val(msg).addClass("error").effect("highlight", {color: "#ffe400"}, 1200).focus(function(){
		this.value = "";
		input.removeClass("error");
	});
}

function callSuccess(input, msg){
	input.val(msg).addClass("success").effect("highlight", {color: "#ffe400"}, 1200).focus(function(){
		this.value = "";
		input.removeClass("success");
	});
}



function mp_newsletter_widget(data){
	var newsletter_form = $("#newsletter-subscribe")
	var newsletter_email = $("#txt-newsletter-subscribe")
	if(data.status=="0"){
		callSuccess(newsletter_email, "Thank you for signing up");
	} else {
		callError(newsletter_email, "Email is already subscribed");
	}
	$(".loading",newsletter_form).hide();
}

function quicksub(data){
	var newsletter_form = $("#newsletter-subscribe")
	var newsletter_email = $("#txt-newsletter-subscribe")
	if(data.status=="0"){
		callSuccess(newsletter_email, "Thank you for signing up");
	} else {
		callError(newsletter_email, "Email is already subscribed");
	}
	$(".loading",newsletter_form).hide();
}

function newsletterGet(){
	var newsletter = $("#newsletter-subscribe");
	$(".loading",newsletter).show();
	if (cityslug == "newyork"){
		$.getJSON("http://membership.nymetro.com/register/newsletter_quicksub?callback=?&"+newsletter.serialize());
	} else {
		$.getJSON("http://menupages.com/newsletter/subscribe?callback=?&"+newsletter.serialize());
	}
}
$(function() {

	$("#toggle-nym-nav").click(function() {
		var t = $(this);
		var p = $("#nymag-nav");
		var ajaxNav = "/includes/components/mast/nav/navbar-only.txt"
		if(p.hasClass("active")){
			p.removeClass("active");
			p.animate({height:"0"},300,"easeInQuint",collapseNav);
			$("body").unbind("click");
		} else {
			p.addClass("active");
			p.css("display","block").animate({height:"53px"},600,"easeOutExpo",loadNav);
			$("body").click(function(){ t.click(); });
		}
	return false;
	});

	$("#city-context-switcher").click(function(e) {
		var p = $(this);
		if(p.hasClass("active")){
			p.removeClass("active");
			p.children(".uberselect-panel").slideUp(100);
			$("body").unbind("click");
		} else {
			p.addClass("active");
			p.children(".uberselect-panel").slideDown(200);
			$("body").click(function(){ p.click(); });
			e.stopPropagation();
		}
	});

	$("#grub-home").hover(function(){
		$("p.homelink a").addClass("underline");
	},function () {
		$("p.homelink a").removeClass("underline");
	});
	

	$(".blog-index img.primaryimg").each(function(){
		var i = $(this);
		var imgSrc = i.attr("longdesc");
		if(imgSrc.length > 0){
			i.attr("src", imgSrc);
			i.css("visibility","visible");
			i.prev("img.loader").remove();
		}
	});
	
	//mapnav function
	$("#mapnav-toggle").hover(
		function(){
			$(this).addClass("content-active");
		},
		function () {
			$(this).removeClass("content-active");
		}
	).find("a").hover(
		function(){
			$("#mapnav-toggle").addClass(this.className);
		},
		function () {
			$("#mapnav-toggle").removeClass(this.className);
		}
	);
		



	//tab function
	$('div.modtabs').each(function(){
		var startTab = 0;
		tabInfo = $(this);
		var pos = tabInfo.attr("class").search("startTab");
		startTab = parseInt(tabInfo.attr("class").substring(pos).substring(8));
		$(this).tabs({ selected: startTab });
		$(this).removeClass("pretab");
	});

	var search_dishes = ["chicken marsala", "beef wellington", "oysters rockefeller", "clams casino", "bananas foster", "eggs benedict", "mac & cheese", "butternut squash soup", "arroz con pollo", "ceviche", "saag paneer", "moo goo gai pan", "panang curry", "chiles rellenos", "jalapeno poppers", "lasagna", "falafel", "bouillabaisse"];
	var rn=Math.floor(Math.random()*search_dishes.length);
	var search_food_text = "(example: " + search_dishes[rn] + ")";
	var search_name_text = "Type restaurant name";
	
	var current_search = "txt-mp-search";
	var current_search_text;
	current_search_text = search_name_text;	
	var search_subdomain = cityslug;
	if(search_subdomain=="newyork") search_subdomain = "www";
	
	$("#mp-search-form").attr("action","http://" + search_subdomain + ".menupages.com/restaurants/search");
	$("#search-box a").click(function(i){
		$(this).parent().addClass("active");
		$(this).parent().siblings().removeClass("active");
		if(this.id !== current_search){
			current_search = this.id;
			if(this.id === "food-mp-search"){
				$("#txtHeaderSearch").hide().attr("value","");
				$("#txtCategoryOrItem").show().attr("value",search_food_text);
				$("#search-box").addClass("food-search").removeClass("std-search");
				$("#mp-search-form").attr("action","http://" + search_subdomain + ".menupages.com/foodsearch/post").attr("method","post");
				$("#txtCategoryOrItem").origValidate({
					form: "#mp-search-form",
					searchText: search_food_text,
					errorMsg: "type name of food, please"
				});
			} else {
				$("#txtCategoryOrItem").hide().attr("value","");
				$("#txtHeaderSearch").show().attr("value",search_name_text);
				$("#search-box").addClass("std-search").removeClass("food-search");
				$("#mp-search-form").attr("action","http://" + search_subdomain + ".menupages.com/restaurants/search").attr("method","get");
			}
		}
		return false;
	});
				

	
	$("#tx-search-nym").origValidate({
		form: "#nym-search-form",
		searchText: "By name",
		errorMsg: "Type restaurant name, please"
	});

	$("#txtHeaderSearch").origValidate({
		form: "#mp-search-form",
		searchText: "Type restaurant name",
		errorMsg: "Type restaurant name, please"
	});
	
	$("#txt-newsletter-subscribe").origValidate({
		form: "#newsletter-subscribe",
		searchText: "Enter your e-mail address",
		errorMsg: "E-mail address is required",
		onSubmit: function(){
			var newsletter_email = $("#txt-newsletter-subscribe");
			var validEmail = (newsletter_email.val().search(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i) >= 0) ? true : false;
			var newsletter = $("#newsletter-subscribe");
			var checkit = newsletter.attr("class");
			var checkCount = newsletter.find("input:checkbox:checked").length;
				
			if(!validEmail) {
				callError(newsletter_email, "Please enter valid E-mail");
			} else {
				if(checkit == "multi-newsletter") {
					if(checkCount == 0)  {
						callError(newsletter_email, "Select a newsletter");
					} else {
						newsletterGet();
						return false;
					};
					
				} else {
				newsletterGet();
				}
			}
			return false;
		}
	});
	


	$("#restaurant-search h6").click(function (e) {
		var p = $(this);
		var content = p.parents(".content");
		if(p.hasClass("active")){
			$("body").unbind("click");
			e.stopPropagation();
			p.removeClass("active").addClass("selected").next("div.uberselect-panel").css("display","none");
			if(content[0].id=="search-nym")	content.animate({ height:"69px" },300);
			else content.animate({ height:"91px" },300);
		} else {
			if($.browser.msie){}else{$("body").unbind("click");}
			$("div.uberselect-panel").fadeOut("slow").prev().removeClass("active");
			p.parent().removeClass("iezindex").siblings().addClass("iezindex");
			p.addClass("active");
			if(content[0].id=="search-nym") content.animate({ height:"210px" },300);
			else content.animate({ height:"232px" },600);
			p.next("div.uberselect-panel").slideDown(120, function(){  
				$("#restaurant-search .uberselect div.uberselect-panel").unbind("click").click(function(e){ e.stopPropagation(); });
				if($(this).find("li").length <= 1){
					var ajaxFile = "/includes/components/sect/blogs/grubstreet-" + cityslug + "/" + p.parent()[0].id + ".txt"
					$(this).children("ul").load(ajaxFile, function(){
						$(this).fadeIn("slow");
					});
				} else {
					$(this).children("ul").fadeIn("slow");
				}
			});
			e.stopPropagation();
			$("body").click(function(){ p.click(); });
		}
	});
	


		
		$(".blog-index img.primaryimg").each(function(){
			var i = $(this);
			var imgSrc = i.attr("longdesc");
			if(imgSrc.length > 0){
				i.attr("src", imgSrc);
				i.fadeIn("fast");
				i.prev("img.loader").remove();
			}
		});
		
		var emailScramble = $("#scramble").attr("rel");
		$("#scramble").attr("href","mailto:" + cityslug + "@grubstreet.com");	

});

if(typeof window.nymag == 'undefined') window.nymag = {};
window.nymag.dcads = { reloadAds : function() { reloadAds() } }