// ------------------------------------------------------------------------//
// Global functions
// ------------------------------------------------------------------------//

var etcXhr = false;
var loading=false;


// ETC Dropdown Functions //
function etcOverlayCloseBtn() {
	$("#navGlobalEtcDrop").prepend("<a class=\"close\" href=\"#\">Close</a>").bind('click', function() {
		etcOverlayCollapse();
	});
}

function etcOverlayDrop() {
	//clear the ajax call timer
	clearTimeout(window.nymag.etcNavAjaxTimer);
	//clear the mouseleave timer
	clearTimeout(window.nymag.etcNavTimer);
	//cache the selector + addClass functions
	var etc = $("#navGlobalEtc");
	etc.addClass("hover");
	$("body").addClass("etcHover");
	//ie z-index fix
	if ($.browser.msie && $.browser.version<=7) ie_apply_zindex("#navGlobalEtcDrop",10,"body");
	//has content already been loaded?
	d = $("#navGlobalEtcDropInner").length;
	//set a timer for the ajax call to prevent multiple calls w/ hover event
	window.nymag.etcNavAjaxTimer = setTimeout(function(){
		if (!etcXhr && d <= 0) $.get("/includes/components/sect/vulture/navGlobalEtcDrop.html", function(data){
			$("#navGlobalEtcDropContent").append(data).children("#navGlobalEtcDropInner").fadeIn("fast");
			if($("html").hasClass("touchUI"))etcOverlayCloseBtn();
			var etcXhr = true;
		});
	},500);
}

function etcOverlayCollapse() {
	var etc = $("#navGlobalEtc");
	etc.removeClass("hover");
	$("body").removeClass("etcHover");
}

function etcOverlay() {
	var etc = $("#navGlobalEtc");
	var etcBtn = $("#navGlobalEtc #etcBtn");
	if($("html").hasClass("touchUI")) {
		etcBtn.toggle(function() {
			etcOverlayDrop(etc);
		}, function() {
	  		etcOverlayCollapse();
		});

	} else {
	etc.bind('mouseenter mouseleave', function(event) {
		etc = $(this);
		if (event.type == 'mouseenter') {
		window.nymag.etcNavHoverTimer = setTimeout(function(){
			etcOverlayDrop();
		},150);
		} else {
		clearTimeout(window.nymag.etcNavHoverTimer);
			window.nymag.etcNavTimer = setTimeout(function(){
				etcOverlayCollapse();
			},500);
		}
	});
	}
}
// end ETC Dropdown Functions //

/*-  override NYMag search dropdown function
----------------------------------------------------------------------*/
function swapSearchType( widget_name, search_type ) {
    var searchWidget = document.getElementById( widget_name );

    if (search_type == 'all') {
        searchWidget.action = "/search/search.cgi";
        searchWidget.search_type.value = 'sw';
        searchWidget.N.value = 0;
    }

    if (search_type == 'vulture') {
        searchWidget.action = "/search/search.cgi";
        searchWidget.search_type.value = 'sw';
        searchWidget.N.value = 272;
    }

}


// init after the header has loaded //
function initVultureHeader() {
    etcOverlay();
    nymag.nav.set();
	window.nymag.search.set();
	// login/logout functions
	$("#logged_out_bar").after("<div id='popup-lightbox'></div>");
	NYM.loginReg.updateLoginMessage();
	NYM.loginReg.initPopup();
	$("#logged_out_bar a.register-lightbox").click(function(){ return loadRegister("#popup-lightbox"); return false; });
	$("#logged_out_bar a.login-lightbox").click(function(){ return loadLogin("#popup-lightbox"); return false; });
	$("#logged_in_bar .logout a").click(function(){ logoutAll(); return false; });
}


// lazyload Images! //
lazyImgs = new Array();

function lazyload(){
    if(lazyImgs.length > 0){
        var curr = lazyImgs.shift();
        curr.obj.attr("src", curr.src);
        curr.obj.fadeIn("fast");
        curr.obj.removeClass("lazyload");
        curr.obj.prev("img.loader").remove();
        if(lazyImgs.length >0) setTimeout(lazyload, 300);
    }
}

function lazyLoadImages(){
	$("img.lazyload").each(function(){
	    var i = $(this);
	    var iSrc = i.attr("data-imgpath");
	    if(iSrc.length > 0){
	        lazyImgs.push({
	            obj: i,
		    src: iSrc
		    });
	    }
	});
	var timer = setTimeout(lazyload, 300);
}

// NEWSLETTER

function initNewsletter(){
    var newsletter_ids="";
    $("#txt-newsletter-subscribe").origValidate({
    	form: "#newsletter-subscribe",
    	searchText: "Enter your e-mail address",
    	errorMsg: "E-mail address is required",
    	onError: callError,
    	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");

    		if(!validEmail) {
    			callError(newsletter_email, "Please enter valid E-mail");
    		} else if(!checkCount.length){
    			callError(newsletter_email, "Please select a newsletter");
    		} else {
    		    newsletter_ids="";
    			checkCount.each(function(){
    				if(newsletter_ids != "") newsletter_ids += "&";
    				newsletter_ids += "newsletter_"+this.value+"=1";
    			});
    			
    		    nymag_recordLink(this, "Newsletters - Vulture Homepage");
    		    $(".loading",newsletter).show();
                $.getJSON("https://secure.nymag.com/register/newsletter_process?callback=?&"+newsletter_ids+"&newsletter_email_address="+newsletter[0].email.value+"&source="+newsletter[0].source.value,
                    function(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).hide();
                    }
                );
    		}
    		return false;
    	}
    });
}

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 newsletterSub(data){
	var newsletter_form = $("#newsletter-subscribe");
	var newsletter_email = $("#txt-newsletter-subscribe");
	if(data.status==0){
		document.getElementById("signup_btn").src='/images/2/btn-thankyou.gif';
		document.getElementById("signup_btn").onclick=function(){ return false; }
		callSuccess(newsletter_email, "Thank you for signing up");
	} else {
		callError(newsletter_email, "Email is already subscribed");
	}
	$(".loading",newsletter).hide();
}



// ------------------------------------------------------------------------//
// Homepage functions
// ------------------------------------------------------------------------//

// start LEDE Rotator JS

var ledeData;
var totalItems;
var pauseRotator=false;
var currPos;
var buttonsActive = true;
var isFocused = true;

function onBlur() {
    isFocused = false;
    pauseRotator = true;
    window.onfocus = onFocus;
    clearTimeout(startRotate);
};

function onFocus(){
	isFocused = true;
	pauseRotator = false;
	rotateLede();
};


function initLede() {
       $.ajax({url:"/daily/entertainment/json/lede/", cache:false, dataType: "json",
        success: function(data){
          $.each(data.items, function(i,item){
                 ledeData = data;
                 var headline = this.headline;
                 var imagePath = this.image;
                 var link = this.link;
		 var rubric = this.rubric;
                 headline = "<h3><span><a href=\'" + link + "\'>" + rubric + "</a></span><br><a class=\'headline\' href=\'"+link+"\'>"+headline+"</a></h3>";
                 imagePath = "<a class=\'image\' href=\'"+link+"\'><img src=\'"+imagePath+"\'/></a>";
                 var article = "<article onclick=\'window.location.href=\"" + link + "\"\' pos=\'" + i + "\'>" + imagePath + headline + "</article>";
                 if($.browser.msie && parseInt($.browser.version, 10) < 9) article = $(innerShiv(article, false));
                 $("#content-head #article-container").append(article);

          });
                $("#content-head article:first").addClass("active");
                totalItems = data.items.length;
                        if (totalItems > 1) {
                                setButtons();
                                $("#content-head").hover(function() {
                                        pauseRotator=true;
                                        clearTimeout(startRotate);
                                 }, function() {
                                        pauseRotator=false;
                                        rotateLede();
                                });
                               	rotateLede();
                        }
        }});
}

function initLedeCQ() {
        $.ajax({url:"/content/nymag/daily/entertainment/json/lede.vulture.json", cache:false, dataType: "json",
        success: function(data){
          $.each(data.items, function(i,item){
                 ledeData = data;
                 var headline = this.headline;
                 var imagePath = this.image;
                 var link = this.link;
                 var rubric = this.rubric;
                 headline = "<h3><span><a href=\'" + link + "\'>" + rubric + "</a></span><br><a class=\'headline\' href=\'"+link+"\'>"+headline+"</a></h3>";
                 imagePath = "<a class=\'image\' href=\'"+link+"\'><img src=\'"+imagePath+"\'/></a>";
                 var article = "<article onclick=\'window.location.href=\"" + link + "\"\' pos=\'" + i + "\'>" + imagePath + headline + "</article>";
                 if($.browser.msie && parseInt($.browser.version, 10) < 9) article = $(innerShiv(article, false));
                 $("#content-head #article-container").append(article);

          });
                $("#content-head article:first").addClass("active");
                totalItems = data.items.length;
                        if (totalItems > 1) {
                                setButtons();
                                $("#content-head").hover(function() {
                                        pauseRotator=true;
                                        clearTimeout(startRotate);
                                 }, function() {
                                        pauseRotator=false;
                                        rotateLede();
                                });
                                rotateLede();
                        }
        }});
}


function getLedeItem(pos) {
        // deactivates buttons during animation
        buttonsActive = false;
        if (!pos) {
                pos = $("#content-head article[class=active]").attr("pos");
                pos = (parseInt(pos) + 1);
                if (pos == totalItems) { pos = 0; }
        }
        if($.browser.msie && $.browser.version <= 7) {
                $("#content-head article[class=active]").css("z-index", "200");
                activeZindex = 200;
                $("#content-head article[pos=" + pos + "]").css("z-index", activeZindex + 1);
                $("#content-head article[class=active] h3").hide();
        } else {
                $("#content-head article[class=active] h3").hide("slide", { direction: "left", easing: "easeOutCubic"}, 300);
        }
        $("#content-head article[class=active] img").hide("slide", { direction: "right", easing:"easeOutCubic" }, 300, function() { $(this).parent().parent().removeClass("active"); });

        $("#rotator-controls li[class=active]").removeClass("active");
        $("#content-head article[pos=" + pos + "] img").show("slide", { easing:"easeOutCubic" }, 300);
        $("#content-head article[pos=" + pos + "] h3").show("slide" , { direction: "right", easing: "easeOutCubic" }, 300, function() { $(this).parent().addClass("active"); buttonsActive = true;});
        $("#rotator-controls li#ctrl" + pos).addClass("active");
        rotateLede();
}

var ulWidth = 0;

function setButtons() {
                // set up button dots
                $.each(ledeData.items, function(i,item){
                        var buttonPos = (i);
                        var button = "<li id=\'ctrl" + buttonPos +"\'>"+ buttonPos +"</li>";
                        $("#rotator-controls ul").append(button);
                });
		var buttonCount = $("#rotator-controls ul li").size();
		var rotatorWidth = buttonCount * 18;
                rotatorLeft = ((480-rotatorWidth)/2);
		rotatorLeft = rotatorLeft + "px";
		$("#rotator-controls").attr("style", "padding-left:" + rotatorLeft);
		$("#rotator-controls").css("padding-left", rotatorLeft);
                $("#rotator-controls li:first").addClass("active");

                $("#rotator-controls li:not(.active)").live("click", function() {
                                var sequence = $(this).attr("id");
                                sequence = sequence.substring(4);
                                if (buttonsActive == true) {
                                        getLedeItem(sequence);
                                } else {
                                        return false;
                                }
                });

}

function rotateLede() {
	if (!$.browser.msie) { window.onblur = onBlur; }
	
	if (pauseRotator == false && isFocused==true) {
	        startRotate = setTimeout("getLedeItem();", 5500);
	} else {
	        return;
	}
}
// end LEDE Rotator JS


// start homepage content functions

$.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};


function matchArticles(columnToResize , articleDiv , columnToMatch) {

	// HEIGHT OF COLUMN TO MATCH
	nymag.matchHeight = $(columnToMatch).height();

	// RESET ARTICLES FROM LAST MATCH
	$('#feature-clickables article').removeClass('last').show();

	// ITERATE THROUGH ARTICLES IN REVERSE
	$( $(articleDiv).get().reverse() ).each( function(){


	        if( $(columnToResize).height() > nymag.matchHeight ) {
	                // HIDE ARTICLE IF TOO TALL
	                $(this).hide();
	        } else {
	                // ADD LAST CLASS TO FINAL ONE
	                $(this).addClass('last');
	                return false;
	        }

	});
}

function initTopFeatures() {
	matchArticles('#top-features .col-a','#feature-clickables article','#top-features .col-b');

	// TAB CALLBACKS
	$('#top-features #feature-recaps').bind('tabsshow', function(event, ui) {
		matchArticles('#top-features .col-a','#feature-clickables article','#top-features .col-b');
	});

	// TAB BACKGROUND OFFSET
	$('#top-features .feature-recaps ul.tabs li').each(function() {
		var parentOffset = $('#top-features .feature-recaps ul.tabs').position().left;
		var backOffset = $(this).position().left + parentOffset + 1;

		$(this).css("background-position", "-" + backOffset + "px 100%");
	});

	// RESET FIRST CLASS (can't have ">" because of CQ divs)
	$('#top-features .col-b section').removeClass('first');
	$('#top-features .col-b section:first').addClass('first');
}

 function initFeatureReviews() {
 	// TAB BACKGROUND OFFSET
 	$('#features-wrap .feature-reviews ul.tabs li,#content-secondary .feature-reviews ul.tabs li').each(function() {
 		var parentOffset = $(this).parent().position().left;
 		var backOffset = $(this).position().left + parentOffset + 1;

 		$(this).css("background-position", "-" + backOffset + "px 100%");
 	});
 }


 // pics and video js - dc

var pausePicsRotator=false;

 function initPics() {
         $("#feature-pics nav .next, #feature-pics nav .prev").bind("click", function() {
                 var state = $(this).attr("class");
                 picsRotate(state);
         });

	$("#feature-pics").hover(function() {
		pausePicsRotator=true;
		clearTimeout(startPicsRotate);
	}, function() {
		pausePicsRotator=false;
		cyclePics();
	});
	cyclePics();


		// RANDOM ROTATE PICS
		nymag.picsTilts = ["1.3deg" , "1.5deg" , "-1deg" , "-1.5deg" , "-1.3deg"];

		$("#feature-pics article div.holder:gt(0)").each(function() {

			var picsTilt = nymag.picsTilts[ Math.floor( Math.random() * nymag.picsTilts.length ) ];
			var picsIndex = nymag.picsTilts.indexOf(picsTilt);
			if(picsIndex != -1) { nymag.picsTilts.splice(picsIndex, 1); }

			$(this).css("transform","rotate(" + picsTilt + ")");
			$(this).css("-moz-transform","rotate(" + picsTilt + ")");
			$(this).css("-webkit-transform","rotate(" + picsTilt + ")");
		});
 }

 function initVideoCarousel(){
 	$("#feature-video .carousel").jCarouselLite({
         btnNext: "#feature-video .next",
         btnPrev: "#feature-video .prev",
         visible: 3,
         easing: "easeOutExpo",
         speed: 600,
         scroll: 3
  	});
  }

 function picsRotate(state) {
	var transitionTime = 400;
	if($.browser.msie && $.browser.version==8) var transitionTime = 1;

                        if (state == "next") {
                                if ($("#feature-pics .on").next(".pic-entry").length) {
                                        $($("#feature-pics .on")).fadeOut(transitionTime, function() {
                                                $(this).removeClass("on");
                                        });
                                        $($("#feature-pics .on")).next(".pic-entry").fadeIn(transitionTime, function() {
                                                $(this).addClass("on");
                                        });

                               } else {
                                        $($("#feature-pics .on")).fadeOut(transitionTime, function() {
                                                $(this).removeClass("on");
                                        });
                                        $("#feature-pics .pic-entry:first").fadeIn(transitionTime, function() {
                                                 $(this).addClass("on");
                                        });
                               }

                        } else {
                                if ($("#feature-pics .on").prev(".pic-entry").length) {
                                        $($("#feature-pics .on")).fadeOut(transitionTime, function() {
                                                $(this).removeClass("on");
                                        });
                                        $($("#feature-pics .on")).prev(".pic-entry").fadeIn(transitionTime, function() {
                                                $(this).addClass("on");
                                        });

                               } else {
                                        $($("#feature-pics .on")).fadeOut(transitionTime, function() {
                                                $(this).removeClass("on");
                                        });
                                        $("#feature-pics .pic-entry:last").fadeIn(transitionTime, function() {
                                                 $(this).addClass("on");
                                        });
                               }
                        }
			cyclePics();
}

function cyclePics() {
        if (pausePicsRotator == false) {
                startPicsRotate = setTimeout("picsRotate('next');", 10000);
        } else {
                return;
        }
}


// ------------------------------------------------------------------------//
// Vulture FEED
// ------------------------------------------------------------------------//


var curr=0;
var max=5;
var next = true;
var windowTimer;
var tagList = new Array();
var currTag = "";
var tgs = readCookie("tabs");
var tgs_li = "";
var load_more = true;
var entry_id=0;

tgs = (tgs==null || tgs=="") ? "" : tgs.split(",");
nymag.vulture = {
    clicks : {
        partylines : true,
        slideshows : true,
        interviews : true,
        lede_right : true,
        rotator : true,
        videos_mod: true,
        newsletter: true
    },
    pagename : "http://nymag.com/daily/entertainment/" + currTag
}


function switchTimer(i, scroll){
	scroll = (typeof scroll=="undefined") ? true : scroll;
	curr = (i<0) ? max-1 : i;
	curr = (curr==max) ? 0 : curr;
	next = (!next || i==max) ? false : curr+1;
	var ul = $("#rotator-entries");
    $("#rotator-controls li:eq(" + (curr+1) +")").addClass("active").siblings().removeClass("active");
	ul.fadeOut((scroll ? 500 : 350),function(){
		var img = ul.find("li:eq(" + curr + ")");
		img.css("visibility","visible").siblings().css("visibility","hidden");

		if(img.attr("src")=="") img.find("img").attr("src",img.attr("title"));

		if(next){
			img = img.next().find("img");
			if(img.attr("src")=="") img.attr("src",img.attr("title"));
		}
		ul.css("left",(-483*curr)+"px").fadeIn(300,function(){ if($.browser.msie) this.style.filter = ""; });
		if(scroll){
		    clearTimeout(windowTimer);
            windowTimer = setTimeout("switchTimer(" + (curr+1) + ")",4000);
		}
	});
}

function deleteTag(i){
		var p = $(i).parent().parent();
		var p_text = p.text();
		var li = p_text.substring(0,p_text.length-1).replace(/ /g,"_");
		var re = new RegExp("::"+li);
		var re2 = new RegExp(li+"::");
		var tgs = readCookie("tabs").replace(re,"").replace(re2,"").replace(li,"");
		setCookie("tabs",tgs,365);
		p.fadeOut("slow",function(){p.remove();});
		return false;
}

function initTags(){
    if($.browser.msie && $.browser.version==6) return;
	$("#tab-list li > a").click(function(){
		clearTimeout(windowTimer);
		var curr = $(this);
		var p = curr.parent();
		var tab_list = p.parent();
		if(p.hasClass("active")) return false;

		var chw = $("#feedLede-items");
		var ch = $("#feedLede-items");
		currTag = $(this).attr("title").replace(/\+ /g,"").toLowerCase();
		currTag = (currTag=="all news") ? "feed" : currTag+"/";
		p.addClass("active").siblings().removeClass("active");
		document.location.hash = "/"+currTag;

		$("#content-primary").html("<div id='temp_ldr' style='clear:both;font-size: 20px;text-align:center;'><img src='http://images.nymag.com/gfx/sect/vulture/loading.gif' /></div>");
		var ajaxCall = function(q){
		currTag = (currTag=="feed") ? "" : currTag;
    		$.get("/daily/entertainment/ajax/getEntries/"+currTag,function(d){
    		    q.queue(function(){
        			content_d = d;
        			if(p.hasClass("lede")){
        				tmp = d.split("<!--BREAK-->");
        				lede_d = tmp[0];
        				content_d = tmp[1];
					if($.browser.msie && parseInt($.browser.version, 10) < 9) lede_d = $(innerShiv(lede_d, false));

        				ch.html(lede_d);
        				chw.removeClass("tmp_ldr").animate({height:ch.height()},400);

        				var opac = ($.browser.msie) ? "show" : 1;
        				ch.animate({opacity:opac},350,function(){
        				    if($.browser.msie) this.style.filter = "";
        				});
        			}
        			nymag.vulture.pagename = "http://nymag.com/daily/entertainment/" + currTag;
        			$("#content-primary").html(content_d);
        			load_more = true;
        			window.nymag.dcads.reloadAds();
                        navSection = currTag.replace("/","");
                        $("#navGlobal,#content").removeAttr("class");
                        if(currTag ==""){
                        	$("#navGlobal,#content").addClass("feed");
                        }else{
                        	$("#navGlobal,#content").addClass(navSection);
                        }
    		        $(this).dequeue();
    		        lazyLoadImages();
    		    });
    		});
		}

		if(p.hasClass("lede")){
		    var h = ch.height();
		    h = (h==0) ? 390 : h;

		    if(chw[0].style.display == "none"){
		    	jQuery("#content-layout-wrap").animate({borderTopColor:"#8c8c8c",borderTopWidth:"1px"},'fast');
			chw.slideDown(650,function(){
        		    chw.addClass("tmp_ldr");
    				var opac = ($.browser.msie) ? "hide" : 0;
        		    ch.animate({opacity:opac},350);
        		    ajaxCall(ch);
    		    });
		    } else {
		        chw.addClass("tmp_ldr");
				var opac = ($.browser.msie) ? "hide" : 0;
    		    ch.animate({opacity:opac},350);
    		    ajaxCall(ch);
		    }
		}
		else{
		    ch.animate({opacity:0},100,function(){
                if(chw[0].style.display != "none") chw.slideUp(500);
                jQuery("#content-layout-wrap").animate({borderTopColor:"#ffffff",borderTopWidth:"0"},800);
                ajaxCall(chw);
		    });
		}

		return false;
	}).next("div.rm").children("i").click(function(e){ deleteTag(this);  return false; });

	var curr_tag = $();

	$("#add_tag")
	.origText()
	.focus(function(){
	    var ajax_img = $("#add_tab > img");
	    $(this.parentNode).addClass("focused");
	    $("#choices").show();
	    $("body").click(function(e){
	        curr_tag = e.target ? e.target : e.srcElement;
	        if(curr_tag.id!="add_tab" && !$(curr_tag).parents("#add_tab").length){
	            $("#add_tab").removeClass("focused");
	            $("body").unbind("click");
	        }
	    });
	    if(!tagList.length){
	        ajax_img.show();
            $.get("/daily/entertainment/feeds/toptags.txt",function(d){
                $("body").append(d);
                $("#add_tag").keyup();
                ajax_img.hide();
            });
	    }
	})
	.keyup(function(e){
		var key = e.keyCode;
		var txt = $(this).val();

		if(e.keyCode == 13 && txt != ""){
			if(curr_tag.text() == ""){ alert("Sorry, that tag is currently unavailable. Please choose another."); $(this).val(""); return; }
			$(this).val(curr_tag.text());
			$("#choices").html("");
			$("#add_btn ").click();
		} else if(e.keyCode == 40){
			curr_tag = curr_tag.removeClass("active").next().addClass("active");
			if(!curr_tag.length) curr_tag = $("#choices li:first").addClass("active");
		} else if(e.keyCode == 38) {
			curr_tag = curr_tag.removeClass("active").prev().addClass("active");
			if(!curr_tag.length) curr_tag = $("#choices li:last").addClass("active");;
		} else {
			var li = "";
			for(var i=0; i<tagList.length; i++){
				var mtch = new RegExp("^(" + txt + ")","i");
			  	if(mtch.test(tagList[i]) || txt == "") li += "<li>" + tagList[i].replace(mtch,"<b>"+RegExp.$1+"</b>") + "<a href='#' class='add_btn'></a></li>";
			}
			$("#choices").html(li);
			curr_tag = $("#choices li:first").addClass("active");
		}

		return false;
	})

	if($.browser.msie && $.browser.version==7) ie_apply_zindex("choices");
	$("#choices").click(function(e){
		curr_tag = e.target ? $(e.target) : $(e.srcElement);
		curr_tag = curr_tag[0].tagName=="LI" ? curr_tag : curr_tag.parent();
		$("#add_tag").val(curr_tag.text());
		$("#choices").html("");
		$("#add_btn").click();
		return false;
	});

	$("#add_btn").click(function(){
	    if(!$("#add_tab").hasClass("focused")) return false;
		var txt = $("#add_tag");
		if(txt.val()=="Add More Tags") return false;
		var tags = readCookie("tabs");
		var item = $("#tab-list li.highlight:first").clone(true);
		if(item.hasClass("last")) {
		    item = $("#tab-list li.sub:last").clone(true);
		    item.removeClass("sub").addClass("highlight").append("<div class='rm'><i>x</i></div>").children("div.rm").children().click(function(){ deleteTag(this); return false; });
		}
		item.removeClass("active").removeClass("lede").children("a").attr("title",txt.val()).html("<span>"+txt.val()+"</span>").end();
		$("#tab-list li.last").before(item);



		tags = (tags==null || tags=="") ? txt.val().replace(/ /g,"_")+"::" : tags+txt.val().replace(/ /g,"_")+"::";
		setCookie("tabs",tags,365);
		$("#add_tab").removeClass("focused");
		txt.val("Add More Tags");
		$("#choices").html("");
        nymag_recordLink(this, "Vulture - Add UG Tab");
        item.children("a").click();
	});
}

function morepostsScroll(){

	nymag_recordLink(this, "Vulture - More Posts on Scroll");

	// GET COMMENT COUNTS
    NYM.echo.loadCommentTouts({displayLink: true});

    lazyLoadImages();

}


function initHovers(){
	$("#party-lines,#interviews,#slideshows").unbind('mouseenter mouseleave').unbind('hover').hover(
		function(){
			$(this).addClass("hover").stop().animate({"width":"713px"},200);
		},
		function(){
			$(this).stop().css("width","119px").removeClass("hover");
		}
	);

    $("#slideshows > div.head a").unbind("click").click(function(){
         $("#tab-list li:eq(7) a").click();
         $("html, body").animate({scrollTop: 0}, 400);
         return false;
    });
}


// FEED AJAX LOADR // REVERTED 10/8
/*
function initAjaxFeed(){
	$(window).scroll(function(){
		if(!load_more) return;
		var ch = document.documentElement.scrollHeight;
		var st = (typeof(window.scrollY)=='number') ? window.scrollY : document.documentElement.scrollTop;
		var sh = document.documentElement.clientHeight;
		var pos = ch-(st+sh);
	
		if(pos <= 500 && !loading) { 
			loading=true;
			var e = (currTag=="people/") ? $("#people > li:last") : $("div.entry:last");
			var entry_date;
	
			if(e.length){
	            entry_id = e[0].id.substr(6);
	            entry_date = e[0].className.match(/dt\d+/)[0].substring(2);
			} else return;
			
			$("#content-primary").append("<div id='temp_ldr' style='clear:both;font-size: 20px;text-align:center;'><img src='http://images.nymag.com/gfx/sect/vulture/loading.gif' /></div>");
			currTag = (currTag=="All News/") ? "" : currTag;
			$.get("/daily/entertainment/ajax/getEntries/"+currTag+entry_date+"/",function(d){
				loading=false;
				$("#temp_ldr").remove();
				if($.trim(d) == 0)
				    load_more=false;
				else
				    (currTag=="people/") ? $("#people").append(d) : $("#content-primary").append(d);
			});
		}
	});

}
*/

// FEED AJAX LOADR
function initAjaxFeed(){
    var loading = false;
    var loadMore = true;
    $(window).scroll(function() {
        if (!loadMore) {
            return;
        }

        var ch = document.documentElement.scrollHeight;
        var st = typeof(window.scrollY) === 'number' ? window.scrollY : document.documentElement.scrollTop;
        var sh = document.documentElement.clientHeight;
        var pos = ch - (st + sh);

        if (pos <= 500 && !loading) {
            loading = true;
            var jq = $("div[id*='entry-']:last");
            var publishDateTime = jq.attr("data-publish-datetime");
            if (loadMore) {
                $("#content-primary").append("<div id='temp_ldr' style='clear:both;font-size: 20px;text-align:center;'><img src='http://images.nymag.com/gfx/sect/vulture/loading.gif' /></div>");
            }
            var url = window.location.pathname.replace(/(\/+|\.[^/]+)$/, '');//remove trailing space or extensions
            url += (".more.from=" + publishDateTime + ".html");
            $.get(url, function(resp) {
                $("#temp_ldr").remove();
                if ($.trim(resp) === 0) {
                    loadMore = false;
                }
                $("#content-primary").append(resp);
                loading = false;
                window.nym.echo.loadCommentTouts({displayLink: true});
            });
        }
    });

}



// ------------------------------------------------------------------------//
// Best Lines + Vulture Recommends + Anticipation FILTER
// ------------------------------------------------------------------------//


function initBlogFilter() {
	nymag.lastFilter = "filter-";
	nymag.didFirstRows = 0;

	$("#filter-nav a[class*='filter-']").click(function(evt) {
		// UPDATE PERMALINK HASH
		thisClass = $(this).attr("class");

		if( thisClass == "filter-all" ) {
			window.location.hash = "";
			nymag.lastFilter = "filter-";

			$('#table-24hrs').removeClass("notAll");
			$('#table-7days').removeClass("notAll");

		} else {
			window.location.hash = thisClass.replace("filter-","");
			nymag.lastFilter = thisClass;

			$('#table-24hrs').addClass("notAll");
			$('#table-7days').addClass("notAll");
		}




		// SELECT THIS ONE
		$("#filter-nav a[class*='filter-']").parent().removeClass('selected');
		$(this).parent().addClass('selected');

		// HIDE ALL
		$("#filter-content div[class*='filter-'], #filter-content section[class*='filter-'], #filter-content tr[class*='filter-']").hide();

		// GET CLASSES & ITERATE THROUGH EACH
		var filterClasses = $(this).attr('class').split(' ');
		$.each(filterClasses, function(index,value) {
			if ( value == "filter-all" ) {

				// SHOW ALL
				$("#filter-content div[class*='filter-'], #filter-content section[class*='filter-']").fadeIn();

				// SHOW ALL FOR 1-25 TABLE ROWS
				showFirstRows();

			} else if( value.substring(0,7) == "filter-" ) {

				// SHOW FILTER
				$("#filter-content div." + value + ", #filter-content section." + value ).fadeIn();

				// SHOW FILTER FOR 1-25 TABLE ROWS
				showFirstRows();
			}
		});

		// RESET "first" CLASS
		$("#filter-content div[class*='filter-'], #filter-content section[class*='filter-']").removeClass('first');
		$("#filter-content div[class*='filter-']:visible:first, #filter-content section[class*='filter-']:visible:first").addClass('first');

		// FALSE
		return false;
	});

	// RESET "first" CLASS
	$("#filter-content div[class*='filter-'], #filter-content section[class*='filter-']").removeClass('first');
	$("#filter-content div[class*='filter-']:visible:first, #filter-content section[class*='filter-']:visible:first").addClass('first');

	// HIGHLIGHT PERMALINKED FILTER
	currHash = window.location.hash.substr(1);

	if(currHash.length >= 2) {
		$("#filter-nav a[class*='filter-" + currHash + "']").click();

	}
}

// ------------------------------------------------------------------------//
// TV RECAP
// ------------------------------------------------------------------------//


//context switcher
function initTVRecapSwitcher(){
	$("#context-switcher").click(function(e) {
		var p = $(this);
		if(p.hasClass("active")){

			p.find(".uberselect-panel ul").animate({"height":0},100, function() {
				p.removeClass("active");
			}); // 100

			$("body").unbind("click");
		} else {
			var contentHeadHeight = $("#content-head").height();
			$("#content-head h2").height( contentHeadHeight );

			p.addClass("active");

			// $('#content-head').height( $('#content-head').height() );
			p.find(".uberselect-panel ul").animate({"height":240},200); // 200
			$("body").click(function(){ p.click(); });
			e.stopPropagation();
		}
	});
}


// CHECK TAB TEXT
function initRecapTabs(){
	$('#recaps').tabs({ selected: 0, cache: true });
	$('#recaps .meta .title').each(function(i) {
		var r = $(this);
		var charLimit = 50;

		var titleText = r.html();

		if( titleText.length >= charLimit ) {
			r.html(
				r.html().substr(0,charLimit) +
				"<span class='ellipse'>...</span><span class='more' style='display:none'>" +
				r.html().substr(charLimit) +
				'</span>'
			);

			r.parent().parent().parent().hover(
				function(){
					$('.meta .title .ellipse',this).css('display','none');
					$('.meta .title .more',this).css('display','inline');

				} ,
				function(){
					$('.meta .title .ellipse',this).css('display','inline');
					$('.meta .title .more',this).css('display','none');
				}
			);
		}
	});


}

//more/collapse show meta info
function initShowMeta(){
	$('#more-show-meta').click(function(e) {
			$('#more-show-meta').slideUp(200);
			$('#show-meta .more').slideDown(200);
	});

	$('#collapse-show-meta').click(function(e) {
			$('#show-meta .more').slideUp(100);
			$('#more-show-meta').slideDown(100);
	});
}

function initVultureVideoCarousel(){
	$("#vulture-video .carousel .content").jCarouselLite({
		 btnNext: "#vulture-video .next",
		 btnPrev: "#vulture-video .prev",
		 visible: 3,
		 easing: "easeOutExpo",
		 speed: 600,
		 scroll: 3
	});
}

function initRecapsFoot(){
	$("#recaps-footer .content").jCarouselLite({
		 btnNext: "#recaps-footer .next",
		 btnPrev: "#recaps-footer .prev",
		 visible: 6,
		 easing: "easeOutExpo",
		 speed: 600,
		 scroll: 3
	});
}

// ------------------------------------------------------------------------//
// RANDOM BODY CLASS
// ------------------------------------------------------------------------//

function initRandomLayout() {
	// RANDOM CLASSES
	nymag.randomClasses = [" " , "rand-layout-1" , "rand-layout-2" , "rand-layout-3" , "rand-layout-4" , "rand-layout-5" , "rand-layout-6" , "rand-layout-7"];

	// GET RANDOM
	var randomClass = nymag.randomClasses[ Math.floor( Math.random() * nymag.randomClasses.length ) ];

	// ASSIGN CLASS TO BODY
	$("body").addClass(randomClass);

	// DISPLAY
	$("body.home #mast span.tagline").show();
}



// ------------------------------------------------------------------------//
// DOM Ready
// ------------------------------------------------------------------------//



$(function(){
    $("#top-stories-promo a").nymAnalytics({"link_track":"Vulture: Story: Top Stories"});
    $("#tab-viewed a").nymAnalytics({"link_track":"Vulture: Story: Most Popular: Most Viewed"});
    $("#content-wrap-1 nav.entry-tags a").nymAnalytics({"link_track":"Vultur: Story: Get More"});

	// GET COMMENT COUNTS
	//var commentParams={parentElements:"article,li,header",threshold:5,showCommentLink:false};
	//if($("body").hasClass("blog-index")) commentParams={parentElements:"div.entry",threshold:1,showCommentLink:true};
    //$("a.permalink").getCommentTouts(commentParams);


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

		nymag.startIndex = 100;
		$("ul.tabs li",$(this)).each(function() {
			$(this).css('z-index', nymag.startIndex);
			nymag.startIndex = nymag.startIndex -5;
		});
	});


	lazyLoadImages();



})

// ------------------------------------------------------------------------//
// Tracking Functions Homepage
// ------------------------------------------------------------------------//




function initHomeTracking() {
	$("#navGlobalEtcDrop a").live("click", function() {
    	nymag_recordLink(this, "Vulture – Nav Home – Etc");
	});
	$("#navGlobal .navPrimary li a").live("click", function() {
        var sect = $(this).parent().attr("id");
        sect = sect.substring(9);
        nymag_recordLink(this, "Vulture – Nav Home – " + sect);
	});
	$("#navGlobal .navPrimary li a").live("click", function() {
        var sect = $(this).parent().attr("id");
        sect = sect.substring(9);
        nymag_recordLink(this, "Vulture – Nav Home – " + sect);
	});

	$("#btn-ny-search").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Home – Search");
	});

	$("#navGlobal .hotTopics dd a").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Home – Hot Topic");
	});

/* Home page modules Tracking */

	$("#content-head article").live("click", function() {
        var pos = $("#content-head article.active").attr("pos");
        pos = parseInt(pos)  + 1;
        // tracks by position
        nymag_recordLink(this, "Vulture - Home Rotating Lede(" + pos + ")");
        // tracks by total
        nymag_recordLink(this, "Vulture - Home Rotating Lede");
	});


    $(".latest-news li a").live("click", function() {
    	nymag_recordLink(this, "Vulture - Home Latest News");
    });

	$("#feed article a").live("click", function() {
        nymag_recordLink(this, "Vulture - Home Mini Feed Post");
	});

	$("#feed h2:first a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Mini Feed More (Top)");
	});

	$("#feed .more a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Mini Feed More (Bottom)");
	});

    $("#feature-clickables header h2 a").live("click", function() {
    nymag_recordLink(this, "Vulture – Home –  Clickables Logo Top");
    });

	$("#clickables-wrap a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Clickables");
	});

    $("#feature-clickables .more a").live("click", function() {
    nymag_recordLink(this, "Vulture – Home –  Clickables More");
    });

	$("#feature-recaps article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Recaps");
	});

	$("#feature-pics article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Slideshows Unit");
	});

	$(".feature-reviews article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  New Reviews");
	});

	$("#feature-recommends article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Recommends");
	});

	$(".feature-verticals section li a").live("click", function() {
        var section = $(this).parents("section").attr("class");
        nymag_recordLink(this, "Vulture – Home –  Vertical Headline " + section);
	});

	$("#feature-video article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home – Video Unit");
	});

	$("#feature-secondary-promo article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Feature Unit");
	});

	$(".promo-mini article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Slim Unit");
	});

    $(".feature-starmarket article a").live("click", function() {
    nymag_recordLink(this, "Vulture – Home –  Star Market Gallery");
    });

	$("#content-secondary .vulture-talk article a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Talk Bubbles");
	});

	$("#content-secondary .follow-twitter a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Twitter");
	});

	$("#content-secondary .follow-rss a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  RSS");
	});

	$("#content-secondary #most-popular #tab-viewed li a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Most Viewed");
	});

	$("#content-secondary #most-popular #tab-commented li a").live("click", function() {
        nymag_recordLink(this, "Vulture – Home –  Most Commented");
	});
}

function initFeedTracking() {
	$("body.blog-index #navGlobalEtcDrop a").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Feed – Etc");
	});
	$("#navGlobal .navPrimary li a").live("click", function() {
        var sect = $(this).parent().attr("id");
        sect = sect.substring(9);
        nymag_recordLink(this, "Vulture – Nav Feed – " + sect);
	});
	$("#btn-ny-search").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Feed – Search");
	});
	$("#mast h1.brand").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Feed – Home Button");
	});
	$("#lede-items article a").live("click", function() {
		var ledeSection = $("#content").attr("class");
                	nymag_recordLink(this, "Vulture – Feed – " + ledeSection + " Spot 1-4");
	});
        $("#lede-feature article a").live("click", function() {
                var ledeSection = $("#content").attr("class");
                nymag_recordLink(this, "Vulture – Feed – " + ledeSection + " Spot 5");
        });
        $("#tab-list li a").bind("click", function() {
        nymag_recordLink(this, "Vulture – Feed – Filter");
        });
}

function initArticleTracking() {
	$("#navGlobalEtcDrop a").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Article – Etc");
	});
	$("#navGlobal .navPrimary li a").live("click", function() {
        var sect = $(this).parent().attr("id");
        sect = sect.substring(9);
        nymag_recordLink(this, "Vulture – Nav Article – " + sect);
	});
	$("#btn-ny-search").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Article – Search");
	});
	$("#navGlobal .hotTopics dd a").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Article – Hot Topic");
	});
	$("#mast h1.brand").live("click", function() {
        nymag_recordLink(this, "Vulture – Nav Article – Home Button");
	});
}

function aboutRatingTimeout() {
	$('#about_rating_popup').hide();
}

function initAnticipationIndex() {
	$('#txt-anticipation').origText();

	nymag.currList = "24hrs";
	showFirstRows("nofade");

	// ABOUT RATING
	$('#about_rating').hover(function() {
		$('#about_rating_popup').show();

		window.clearTimeout(nymag.aboutRatingTimer);
	});

	$('#about_rating').mouseout(function() {
		nymag.aboutRatingTimer = window.setTimeout(aboutRatingTimeout, 1000);
	});

	// POPUP
	$('#about_rating_popup').hover(function() {
		window.clearTimeout(nymag.aboutRatingTimer);
	});

	$('#about_rating_popup').mouseout(function() {
		nymag.aboutRatingTimer = window.setTimeout(aboutRatingTimeout, 1000);
	});




	$('#filter-toggle input[type=radio]').change(function() {
		// console.log( $(this).val() );

		thisToggle = $(this).val();

		if(thisToggle == "24") {
			nymag.currList = "24hrs";

			$('#filter-content table.table-24hrs').show();
			$('#filter-content table.table-7days').hide();
		} else	if(thisToggle == "7") {
			nymag.currList = "7days";

			$('#filter-content table.table-24hrs').hide();
			$('#filter-content table.table-7days').show();
		}

		showFirstRows();

	});


	$('#more-items').click(function() {
		showNextRows();

		// $('#filter-content tbody[id^="list-' + nymag.currList + '-"]').each(function() {
		// 	if( $(this).css('display') == 'none' ) {
		// 		$(this).show();
		//
		// 		console.log( nymag.currList + " // " + $(this).attr('id') );
		//
		// 		if( $(this).attr('id') == "list-" + nymag.currList + "-4") {
		// 			$('#more-items').hide();
		// 		}
		//
		// 		return false;
		// 	}
		// });



	});
}

function showFirstRows(nofade) {
	$("#filter-content tr[class*='filter-']").hide();
	$("#filter-content tbody[id*='list-']").show();

	$("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']").each(function(i,v) {
		$(".rank",this).html( i+1 );

		if( $("#table-24hrs").hasClass("notAll") ) {
			thisPrev = $(".prev",this).html();
			$(".prev",this).attr("data-prev" , thisPrev);

			$(".prev",this).html( "" );

			$("#table-24hrs th.prev-head").html( "" );
		} else {
			thisPrev = $(".prev",this).attr("data-prev");
			$(".prev",this).html( thisPrev );

			$("#table-24hrs th.prev-head").html( "24&nbsp;Hrs Ago" );
		}





	});

	$("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']").each(function(i,v) {
		if(nofade) {
			$(this).show();
		} else {
			$(this).fadeIn();
		}



		if(i >= 24) {
			return false;
		}
	});

	if( $("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']").length <= 25 ) {
		$('#more-items').hide();
	} else {
		$('#more-items').show();
	}

	// ADD HOVER
	$("#filter-content tbody tr[class*='filter-']:visible").mouseenter(function() {
		$(this).addClass('hover');
	});

	$("#filter-content tbody tr[class*='filter-']:visible").mouseleave(function() {
		$(this).removeClass('hover');
	});


	// RESET ODD/EVEN ROWS

	$("#filter-content tbody tr[class*='filter-']:visible:odd").removeClass('odd').addClass('even');
	$("#filter-content tbody tr[class*='filter-']:visible:even").removeClass('even').addClass('odd');

	nymag.didFirstRows = 1;
}

function showNextRows() {
	$("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']").not(":visible").each(function(i,v) {
		$(this).fadeIn();

		if(i >= 24) {
			return false;
		}
	});

	// ADD HOVER
	$("#filter-content tbody tr[class*='filter-']:visible").mouseenter(function() {
		$(this).addClass('hover');
	});

	$("#filter-content tbody tr[class*='filter-']:visible").mouseleave(function() {
		$(this).removeClass('hover');
	});

	// RESET ODD/EVEN ROWS
	$("#filter-content tbody tr[class*='filter-']:visible:odd").removeClass('odd').addClass('even');
	$("#filter-content tbody tr[class*='filter-']:visible:even").removeClass('even').addClass('odd');




	// HIDE MORE
	if( $("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']:visible").length >= 100 ) {
		$('#more-items').hide();

		$("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']:visible").each(function(i,v) {
			if( i >= 100 ) {
				$(this).hide();
			}
		});

	} else if( $("#filter-content tbody[id*='list-" + nymag.currList + "'] tr[class*='" + nymag.lastFilter +"']").not(":visible").length <= 0 ) {
		$('#more-items').hide();
	} else {
		$('#more-items').show();
	}

}


$(document).ready(function() {
if($("body").hasClass("home")) initHomeTracking();
if($("body").hasClass("blog-index")) initFeedTracking();
if($("body").hasClass("individual-entry-archive")) initArticleTracking();
if ($.browser.msie && $.browser.version<=7) ie_apply_zindex("#sub_nav_mynewyork");
$("#top-stories-promo a").nymAnalytics({"link_track":"Vulture: Story: Top Stories"});
$("#tab-viewed a").nymAnalytics({"link_track":"Vulture: Story: Most Popular: Most Viewed"});
$("#content-wrap-1 nav.entry-tags a").nymAnalytics({"link_track":"Vulture: Story: Get More"});

});



