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 = $("#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 = $("#lede-items-wrap");
		var ch = $("#lede-items-wrap");
		currTag = $(this).attr("title").replace(/\+ /g,"").toLowerCase();
		currTag = (currTag=="all news") ? "" : 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){
    		$.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) lede_d = $(innerShiv(lede_d, false));
					//$("#lede-items-wrap").html(lede_d);
        				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 = currTag.replace("/","");
                        $("#navGlobal").removeAttr("class");
                        $("#navGlobal").addClass(navSection);
    		        $(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.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},350,function(){
                if(chw[0].style.display != "none") chw.slideUp(500);
                jQuery("#content-head-wrap").animate({borderBottomColor: "#fff"},'fast');
                ajaxCall(chw);
		    });
		}
		
		return false;
	}).next("div.rm").children("i").click(function(e){ deleteTag(this);  return false; });

	var curr_tag = $();
	
	$("#add_tag")
	.origText()
	.focus(function(){
    	if($.browser.msie && $.browser.version==7) ie_apply_zindex("#choices");
	    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;
	})
	
	$("#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 initRotators(){
	clearTimeout(windowTimer);
	curr=0;
	max=$("#rotator-entries").children().length;
	windowTimer = setTimeout("switchTimer(" + (curr+1) + ")",4000);
	$("#rotator").hover(
		function(){ 
		    clearTimeout(windowTimer);
		    if(!$.browser.msie || $.browser.version!=6)
		        $("#rotator-controls").fadeIn("fast"); },
		function(){
		    clearTimeout(windowTimer);
		    windowTimer = setTimeout("switchTimer(" + (curr+1) + ")",3000); 
            if(!$.browser.msie || $.browser.version!=6)
		        $("#rotator-controls").fadeOut("fast");
		}
	);
	$("#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(){
	$("#party-lines,#interviews,#slideshows").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;
    });
}

function initNewsletter(){
    var txtBox = document.getElementById("txt-newsletter-subscribe");
    $(txtBox).hide();
    nym.origValidate(txtBox,{
		form: document.getElementById("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;
		}
	});
	$(txtBox).fadeIn("slow");
}
function callError(input, msg){
    if(!input.jquery) input=$(input);
	input.val(msg).addClass("error").effect("highlight", {color: "#ffe400"}, 1200).focus(function(){
		this.value = "";
		input.removeClass("error");
	});
}

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

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();
	$.getJSON(nymag.domains.secure+"/register/newsletter_quicksub?callback=?&"+newsletter.serialize());
}


// ETC Dropdown Functions //

var etcXhr = false;

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");
	//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");
	if($("html").hasClass("touchUI")) {
		etc.toggle(function() {
			etcOverlayDrop(etc);
		}, function() {
	  		etcOverlayCollapse();
		});
	} else {
	etc.bind('mouseenter mouseleave', function(event) {
		etc = $(this);
		if (event.type == 'mouseenter') {
			etcOverlayDrop();
		} else {
			window.nymag.etcNavTimer = setTimeout(function(){
				etcOverlayCollapse();
			},500);
		}
	});
	}
}   
 

function initVultureHeader() {
	
	etcOverlay();
	
	window.nymag.search.set();

	// login/logout functions
	$("#logged_out_bar").after("<div id='popup-lightbox'></div>");
	updateLoginMessage();
	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; });
	
}

$(function(){

	//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));
		tabInfo.tabs({ selected: startTab });
		tabInfo.removeClass("pretab");
	});

	var loading=false;
	$(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") : $("#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;
			
			$("#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>");
			$.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);
			});
		}
	});
	if($.browser.msie && ($.browser.version <= 7)){
//	    $(document).click(){
//	        var c = $(this);
//	        var i_img = c.parents("i.img")
//	    }
//		$("div.module li a i.img").click(function(){
//			window.location = $(this).parent().attr("href");
//		});
	}
})

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

