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 primaryImg;
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 = $nymag_j("#rotator-entries");
    $nymag_j("#rotator-controls li:eq(" + (curr+1) +")").addClass("active").siblings().removeClass("active");
	ul.fadeOut((scroll ? 1500 : 550),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($nymag_j.browser.msie) this.style.filter = ""; });
		if(scroll){
		    clearTimeout(windowTimer);
            windowTimer = setTimeout("switchTimer(" + (curr+1) + ")",4000);
		}
	});
}

function deleteTag(i){
		var p = $nymag_j(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($nymag_j.browser.msie && $nymag_j.browser.version==6) return;
	$nymag_j("#tab-list li > a").click(function(){
		clearTimeout(windowTimer);
		var curr = $nymag_j(this);
		var p = curr.parent();
		var tab_list = p.parent();
		if(p.hasClass("active")) return false;
		
		var chw = $nymag_j("#content-head-wrap");
		var ch = $nymag_j("#content-head");
		

		currTag = $nymag_j(this).attr("title").replace(/\+ /g,"").toLowerCase();
		currTag = (currTag=="all news") ? "" : currTag+"/";

		p.addClass("active").siblings().removeClass("active");
		document.location.hash = "/"+currTag;
		
		$nymag_j("#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){
    		$nymag_j.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];
        				ch.html(lede_d);
        				chw.removeClass("tmp_ldr").animate({height:ch.height()},400);    				    
                        
        				var opac = ($nymag_j.browser.msie) ? "show" : 1;
        				ch.animate({opacity:opac},350,function(){
        				    if($nymag_j.browser.msie) this.style.filter = "";
        				});
        			}
        			nymag.vulture.pagename = "http://nymag.com/daily/entertainment/" + currTag;
        			$nymag_j("#content-primary").html(content_d);
        			load_more = true;        			
        			window.nymag.dcads.reloadAds();
    		        $nymag_j(this).dequeue();
    		    });
    		});
		}

		if(p.hasClass("lede")){
		    var h = ch.height();
		    h = (h==0) ? 390 : h;
		    if(chw[0].style.display == "none"){
		    	jQuery("#content-head-wrap").animate({borderBottomColor: "#E3E1E2"},'fast');
    		    chw.css("height",h).slideDown(650,function(){
        		    chw.addClass("tmp_ldr");
    				var opac = ($nymag_j.browser.msie) ? "hide" : 0;
        		    ch.animate({opacity:opac},350);
        		    ajaxCall(ch);
    		    });		        
		    } else {
		        chw.addClass("tmp_ldr");
				var opac = ($nymag_j.browser.msie) ? "hide" : 0;
    		    ch.animate({opacity:opac},350);
    		    ajaxCall(ch);
		    }
		} 
		else{
		    ch.animate({opacity:0},350,function(){
                if(chw[0].style.display != "none") chw.slideUp(500);
                jQuery("#content-head-wrap").animate({borderBottomColor: "#000"},'fast');
                ajaxCall(chw);
		    });
		}
		
		return false;
	}).next("div.rm").children("i").click(function(e){ deleteTag(this);  return false; });

	var curr_tag = $nymag_j();
	
	$nymag_j("#add_tag")
	.origText()
	.focus(function(){
	    var ajax_img = $nymag_j("#add_tab > img");
	    $nymag_j(this.parentNode).addClass("focused");
	    $nymag_j("#choices").show(); 
	    $nymag_j("body").click(function(e){
	        curr_tag = e.target ? e.target : e.srcElement;
	        if(curr_tag.id!="add_tab" && !$nymag_j(curr_tag).parents("#add_tab").length){
	            $nymag_j("#add_tab").removeClass("focused");
	            $nymag_j("body").unbind("click");
	        }
	    });
	    if(!tagList.length){
	        ajax_img.show();
            $nymag_j.get("/daily/entertainment/feeds/toptags.txt",function(d){ 
                $nymag_j("body").append(d);
                $nymag_j("#add_tag").keyup();
                ajax_img.hide();
            });
	    }
	})
	.keyup(function(e){
		var key = e.keyCode;
		var txt = $nymag_j(this).val();
	
		if(e.keyCode == 13 && txt != ""){
			if(curr_tag.text() == ""){ alert("Sorry, that tag is currently unavailable. Please choose another."); $nymag_j(this).val(""); return; }
			$nymag_j(this).val(curr_tag.text());
			$nymag_j("#choices").html("");
			$nymag_j("#add_btn ").click();
		} else if(e.keyCode == 40){
			curr_tag = curr_tag.removeClass("active").next().addClass("active");
			if(!curr_tag.length) curr_tag = $nymag_j("#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 = $nymag_j("#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>";
			}
			$nymag_j("#choices").html(li);
			curr_tag = $nymag_j("#choices li:first").addClass("active");
		}
		
		return false;
	})
	
	if($nymag_j.browser.msie && $nymag_j.browser.version==7) ie_apply_zindex("#choices");
	$nymag_j("#choices").click(function(e){
		curr_tag = e.target ? $nymag_j(e.target) : $nymag_j(e.srcElement);
		curr_tag = curr_tag[0].tagName=="LI" ? curr_tag : curr_tag.parent();
		$nymag_j("#add_tag").val(curr_tag.text());
		$nymag_j("#choices").html("");
		$nymag_j("#add_btn").click();
		return false;
	});

	$nymag_j("#add_btn").click(function(){
	    if(!$nymag_j("#add_tab").hasClass("focused")) return false;
		var txt = $nymag_j("#add_tag");
		if(txt.val()=="Add More Tags") return false;
		var tags = readCookie("tabs");
		var item = $nymag_j("#tab-list li.highlight:first").clone(true);
		if(item.hasClass("last")) {
		    item = $nymag_j("#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();
		$nymag_j("#tab-list li.last").before(item);



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

}

function initRotators(){
	clearTimeout(windowTimer);
	curr=0;
	windowTimer = setTimeout("switchTimer(" + (curr+1) + ")",4000);
	$nymag_j("#rotator").hover(
		function(){ 
		    clearTimeout(windowTimer);
		    if(!$nymag_j.browser.msie || $nymag_j.browser.version!=6)
		        $nymag_j("#rotator-controls").fadeIn("fast"); },
		function(){
		    clearTimeout(windowTimer);
		    windowTimer = setTimeout("switchTimer(" + (curr+1) + ")",3000); 
            if(!$nymag_j.browser.msie || $nymag_j.browser.version!=6)
		        $nymag_j("#rotator-controls").fadeOut("fast");
		}
	);
	$nymag_j("#rotator-controls").click(function(e){
	    var curr_tag = e.target ? e.target : e.srcElement;
		if(curr_tag.tagName != "LI") return;
		
		var num = parseInt(curr_tag.id.substring(4));
		switch(curr_tag.className){
			case "prev": switchTimer(curr-1,false);
						 break;
			case "next": switchTimer(curr+1,false);
						 break;
			case "active": return;
			default: switchTimer(num-1,false);
			         break;
		}
	});
}

function initHovers(){
	$nymag_j("#party-lines,#interviews,#slideshows").hover(
		function(){
			$nymag_j(this).addClass("hover").stop().animate({"width":"713px"},200);
		},
		function(){
			$nymag_j(this).stop().css("width","119px").removeClass("hover");
		}
	);
	
    $nymag_j("#slideshows > div.head a").unbind("click").click(function(){
         $nymag_j("#tab-list li:eq(7) a").click();
         $nymag_j("html, body").animate({scrollTop: 0}, 400);
         return false;
    });
}

function initNewsletter(){
    $nymag_j("#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").length;
				
			if(!validEmail) {
				callError(newsletter_email, "Please enter valid E-mail");
			} else {
			    if(nymag.vulture.clicks.newsletter) nymag_recordLink(this, "Vulture - Newsletter Subscribe");
                newsletterGet();
			}
			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 quicksub(data){
	var newsletter_form = $nymag_j("#newsletter-subscribe");
	var newsletter_email = $nymag_j("#txt-newsletter-subscribe");
	if(data.status==0){
		callSuccess(newsletter_email, "Thank you for signing up");
	} else {
		callError(newsletter_email, "Email is already subscribed");
	}
	$nymag_j(".loading",newsletter_form).hide();
}

function newsletterGet(){
	var newsletter = $nymag_j("#newsletter-subscribe");
	$nymag_j(".loading",newsletter).show();
	$nymag_j.getJSON("https://secure.nymag.com/register/newsletter_quicksub?callback=?&"+newsletter.serialize());
}

$nymag_j(function(){

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

	var loading=false;
	$nymag_j(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/") ? $nymag_j("#people > li:last") : $nymag_j("#content-primary > div: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;
			
			$nymag_j("#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>");
			$nymag_j.get("/daily/entertainment/ajax/getEntries/"+currTag+entry_date+"/",function(d){
				loading=false;
				$nymag_j("#temp_ldr").remove();
				if($nymag_j.trim(d) == 0)
				    load_more=false;
				else
				    (currTag=="people/") ? $nymag_j("#people").append(d) : $nymag_j("#content-primary").append(d);
			});
		}
	});
	if($nymag_j.browser.msie && ($nymag_j.browser.version <= 7)){
//	    $nymag_j(document).click(){
//	        var c = $nymag_j(this);
//	        var i_img = c.parents("i.img")
//	    }
//		$nymag_j("div.module li a i.img").click(function(){
//			window.location = $nymag_j(this).parent().attr("href");
//		});
	}
})



$nymag_j.loader.init({
	"#add_tab" : initTags,
	"#interviews" : initHovers,
	"#blog-tools" : initNewsletter
});