var isPurchaseMode=false, requestedRemove=false, askedForCartRemoval=true, manDetsReq=false, curCalView="btn_classScheduleCnt", mocalShowDetails=false;

function getCk(iArg) {var i=j=0,arg=iArg+'=';while(i<document.cookie.length) {j=i+arg.length;if(document.cookie.substring(i,j)==arg)return unescape(document.cookie.substring(j,((document.cookie.indexOf(";",j)==-1)?document.cookie.length:document.cookie.indexOf(";",j))));i=document.cookie.indexOf("",i)+1;if(!i) break;}return null;}
function setCk(a,b,c) {document.cookie=a+"="+escape(b)+"; expires="+c;}
function getCkVal() {var a=unescape(getCk('aPlusCart'));return (a==null||/null/i.test(a)||!a.length)?"":a;}

function remCart(l) {
	if(!requestedRemove&&askedForCartRemoval) {
		askedForCartRemoval=false;
		if(!confirm("Remove class from cart?"))
			return;
	}
	requestedRemove=false;
	$("#inCart #c"+l).remove();
	$("#d"+l+", #w"+l+", #m"+l+"").css("backgroundImage","none");
	saveCart("");
}

function saveCart(l) {
	var arlene=[], outCode="";
	$("#inCart span").each(function(){
		arlene[arlene.length] = [  $(this).html().toString().substring(0,9).replace(/[^a-z0-9]/gi,"")+$(this).attr("id")  ,  $(this).attr("id") ];
	});
	arlene=arlene.sort().reverse();
	for(var sCursor in arlene)
		$("#"+arlene[sCursor][1]).prependTo("#inCart");
	$("#inCart span").each(function(){l+="---"+$(this).attr("id").toString().substring(1);});
	setCk("aPlusCart",escape(l.substring(3)), (new Date(2020,12,31)).toGMTString() );
	$("#cartCheckout").css("marginLeft", document.getElementById("inCart").getElementsByTagName("span").length>10?"809px":"801px");
	// alert("Exiting saveCart"); // TODO: Fix bug - sorting doesn't always work
}

function showAllFromCart() {
	$("#inCart span").each(function(){
		$("#sideDish input[@value="+$(this).html().toString().substring(0,9).replace(/[^a-z0-9]/gi,"")+"]").attr("checked",true);
		$("#cnt span."+$(this).html().toString().substring(0,9).replace(/[^a-z0-9]/gi,"")).removeClass("pseudoHidden");
	});
	var checkedCount=0, theSingleSel="";
	$("#sideDish input[class!=topCk]").each(function(){ if(this.checked) { ++checkedCount;theSingleSel=this.value; } });
	if(!manDetsReq)
		if( checkedCount<7&&$("#shMocalDets").css("opacity")==1 || checkedCount>6&&$("#shMocalDets").css("opacity")<1 )
			{ shMocalDetsF(); manDetsReq=false; }
	if(checkedCount==1)
		try {$("html,body").animate({scrollTop: $("#"+curCalView.substring(4)+" ."+theSingleSel+":first").offset().top-250},500);} catch(e) { $("#singClassNotViz").show().html("(No "+(theSingleSel.toUpperCase().substring(0,4)+" "+theSingleSel.substring(4))+" class on this view)");setTimeout('$("#singClassNotViz").fadeOut()',5555); }
}

$("#topCkToggle").click(function(){
	var temp =	$(this).attr("checked");
	if(temp)	$("#sideDish input").each(function(){ $(this).attr("checked",true); $("#cnt span."+$(this).val()).removeClass("pseudoHidden"); });
	else		$("#sideDish input").each(function(){ $(this).attr("checked",false);$("#cnt span."+$(this).val()).addClass("pseudoHidden");    });
	$("table span *").removeClass("pseudoHidden"); // webkit workaround
	$(this).next().html(temp?"UNCHECK ALL":"CHECK ALL");
	showAllFromCart();
});

$("input.topCk").click(function(){
	var temp =	$(this).attr("checked"), tempName=$(this).attr("name");
	if(temp)	$("#sideDish input."+tempName).each(function(){ $(this).attr("checked",true); $("#cnt span."+$(this).val()).removeClass("pseudoHidden"); });
	else		$("#sideDish input."+tempName).each(function(){ $(this).attr("checked",false);$("#cnt span."+$(this).val()).addClass("pseudoHidden"); });
	showAllFromCart();
});

$("#sideDish li ul li input[type=checkbox]").click(function(){ if($(this).attr("checked")) {$("#cnt span."+$(this).val()).removeClass("pseudoHidden");} else {$("#cnt span."+$(this).val()).addClass("pseudoHidden");}; showAllFromCart(); });

$("#cartCheckout").mousedown(function(){

	return alert("This feature is currently in the works - please try again in a few days"); // TODO: Remove

	// TODO: Checkout process
	// 1. Capture all classes details
	// 2. Login, or confirm password, or create an A+ account
	if(!document.getElementById("inCart").getElementsByTagName("span").length)
		return alert("Your cart is currently empty: double-click on the classes you would like to purchased and then checkout.");

	$("#cart, #inCart, #sideDish, #calControls, #hodieView, #mocalCnt, table.classSchedule").hide();

	var clarray=[], i=-1, temp="", outCode="";
	$("#inCart span").each(function(){
		temp = $(this).attr("id").toString().substring(1);
		// TODO: only add 2 and 3 if clarray[i].length>x
		clarray[++i] = ( $("#m"+temp+" strong").html()+"\n"+$("#m"+temp).attr("title").toString()+"\n"+$(this).html().toString().substring($(this).html().toString().toLowerCase().lastIndexOf("<br>")+4).replace(/ \/ /g,"-")+"\nClassroom "+temp.charAt(temp.length-1)+"\n"+$("#m"+temp).attr("name")+"-"+temp ).replace(/\n\n/g,"\n").split("\n");
		// outCode += "<div class='preCheckoutItem'><strong>"+clarray[i][0]+"</strong><br/><span>"+clarray[i][2]+"<br/>"+(clarray[i].length>5?clarray[i][3]:"")+"<br/>"+(clarray[i].length>6?clarray[i][4]:"")+"</span><br/>"+clarray[i][ (clarray[i]).length-2 ]+" &nbsp;@&nbsp; "+clarray[i][1]+"<br/>"+clarray[i][ (clarray[i]).length-1 ] + "<br/><textarea>"+clarray[i].join("###")+"</textarea></div>";
		// TODO: add id to remove classes from here
		outCode += "<div class='preCheckoutItem' name='"+clarray[i][ (clarray[i]).length-1 ]+"'><strong>"+clarray[i][0]+"</strong><br/><span>"+clarray[i][2]+(clarray[i].length>6?" &nbsp;&bull;&nbsp; "+clarray[i][3]:"")+(clarray[i].length>7?" &nbsp;&bull;&nbsp; "+clarray[i][4]:"")+"</span>"+clarray[i][ (clarray[i]).length-3 ]+"<br/>"+clarray[i][1].replace(/-/,'<img src="/i/cartArr.gif" alt="&rarr;" />')+"<br/>"+clarray[i][ (clarray[i]).length-2 ]+"<br/><textarea>"+clarray[i].join("###")+"</textarea></div>";
	});
	outCode = outCode.replace(/<br\/><br\/>/g, "<br/>").replace(/<br\/><br\/>/g, "<br/>");

	$("#preCheckout").html('<div id="pckControls"><img src="/i/backToSchedule.gif" id="backToSchedule" onmousedown="goBackToSchedule()" alt="Back to class schedule" /><img src="/i/proceedToPayment.gif" id="proceedToPayment" onmousedown="proceedToPayment()" alt="" /><p>Please review the content of your cart and proceed to payment</p></div>'+outCode+'<br style="clear:both"/>').show();

});

function goBackToSchedule() {
	$("#preCheckout").hide();
	$("#cart, #inCart, #sideDish, #calControls, #hodieView, #mocalCnt, table.classSchedule").show();
	$("#"+curCalView).mousedown();
	$("#preCheckout").html("");
}


function proceedToPayment() {
	$("#preCheckout textarea").each(function(){
		//alert(this.value);
	});
	document.location="/notYetSet/";
}


function getCal(timeFrame,e) {
	var temp = e.src, tempObj=timeFrame=="week"?"#classScheduleCnt":(timeFrame=="month"?"#mocal":"#hodieView");
	$("#tentativeNotice").show().fadeTo("fast",1);
	setTimeout('$("#tentativeNotice").fadeTo("fast",0.5)',5555);
	e.src="/i/loadingCal.gif";
	//$.post("calOps.php?jnk="+(new Date()),{"calType":timeFrame,"startDate":e.name},function(data){
	$.get("calOps.php?jnk="+(new Date()),{"calType":timeFrame,"startDate":e.name},function(data){
		if(/ErrorID CPS/i.test(data))
			{ e.src=temp; return alert("Could not load the schedule: please try again later."); }
		$(tempObj).html(data);
		setTimeout("sideDishUpdate('"+tempObj+"')",1);
	});
}


function sideDishUpdate(tgt) {
	handleTitles();
	$("#sideDish input").each(function(){ if(this.checked)	$(tgt+" span."+$(this).val()).removeClass("pseudoHidden"); });
	if(tgt=="#mocal"&&mocalShowDetails)
		{ shMocalDetsF();mocalShowDetails=!mocalShowDetails; }

	var checkedCount=0, theSingleSel="";
	$("#sideDish input[class!=topCk]").each(function(){ if(this.checked) { ++checkedCount;theSingleSel=this.value; } });
	if(checkedCount==1)
		try {$("html,body").animate({scrollTop: $("#"+curCalView.substring(4)+" ."+theSingleSel+":first").offset().top-250},500);} catch(e) { $("#singClassNotViz").show().html("(No "+(theSingleSel.toUpperCase().substring(0,4)+" "+theSingleSel.substring(4))+" class on this view)");setTimeout('$("#singClassNotViz").fadeOut()',5555); }

}


function handleTitles() {
	$("#cnt td span").each(function(){ $(this).attr("title", $(this).attr("title").toString().replace(/---/g," \n").replace(/ \n \n/g,"\n")); if($(this).attr("title").replace(/\s/g,"")==""){$(this).attr("title","");} });
}


$("#calControls img").mousedown(function(){
	if($(this).attr("id")=="buySeasonPass")
		return document.location="/prices/index.php?q=buySeasonPass";
	else if($(this).attr("id")=="buyTicket") {
		//return $("#cnt td span").before("<button class='buyTkt' onclick='buyTkt(this)'>Buy</button>");
		$(this).hide();
		$("#cart, #inCart").toggle();
		$("#buySeasonPass").css("marginLeft","486px");
		$("#sideDish").css("marginTop",$("#cart").css("display")=="none"?"-25px":"-130px");
		isPurchaseMode = $("#cart").css("display")!="none";
		return;
	} else if($(this).attr("id")=="showHideCourseSelector") {
		if ($("#sideDish").css("display") != "none") {$(this).attr("src", "/i/showCourseSelector.gif")} else {$(this).attr("src","/i/hideCourseSelector.gif")}
		return $("#sideDish").toggle();
	}
	$("#calControls img").each(function(){ $(this).attr("src",$(this).attr("src").replace(/On.gif/,"Off.gif")); });
	$(this).attr("src",$(this).attr("src").replace(/Off.gif/,"On.gif"));
	curCalView = $(this).attr("id");
	$("#mocalCnt, #classScheduleCnt, #hodieView").hide();
	$("#"+$(this).attr("id").substring(4)).show();
});

// TODO: relegate all free spirits to docReady()
$("#cnt td span").dblclick(function(){
	return; // TODO: Remove return
	$(this).html($(this).html()); // <=> selCollapse in nonIE
	var tid = $(this).attr("id");
	var arl = tid.substring(1).split("_");
	var loq = new Date( arl[0],(parseInt(arl[1])-1),arl[2],arl[3]<24?arl[3]:23 ); //alert( arl[0]+","+(parseInt(arl[1])-1)+","+arl[2]+","+arl[3]<24?arl[3]:23 );
	var mnd = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
	// TODO: Activate prevent adding past classes
	//if( loq.getTime() < (new Date()).getTime() )
	//	return alert("This class that has already taken place!");
	// TODO: Confirm with Ali - Prevent purchasing concurrent classes
	if(/addedToCart/i.test($(this).css("backgroundImage")))
		return confirm("This class is already in your cart :)\n\nOK to keep the class\nCANCEL to remove the class from your cart")?true:(requestedRemove=true)&&$("#c"+tid.substring(1)).dblclick();
	if(!isPurchaseMode)
		if(confirm("Add class to cart?"))	$("#buyTicket").mousedown();
		else								return;
	var temp = tid.substring(1);
	$("#d"+temp+", #w"+temp+", #m"+temp).css("backgroundImage","url(/i/addedToCart.gif)");
	$("#inCart").html( $("#inCart").html()+"<span id='c"+tid.substring(1)+"' style='color:"+$(this).css("color")+";background:"+$(this).css("backgroundColor")+";border-color:"+$(this).css("borderTopColor")+" "+$(this).css("borderRightColor")+" "+$(this).css("borderBottomColor")+" "+$(this).css("borderLeftColor")+"' ondblclick='remCart(this.id.substring(1))'>" + ( $("#m"+temp+" strong").html() +"<br/>"+ $("#m"+temp).attr("title").toString().substring(0,$("#m"+temp).attr("title").toString().indexOf("\n")) ) + "<br/>" + mnd[loq.getDay()+12] + " " + mnd[loq.getMonth()] + " " + loq.getDate() + "</span>" );
	saveCart("");
	$("#cartInstructions").attr("src","/i/cartInstructionsRemove.gif");
});

function whereIsIt(l) {
	window.open("/i/classroomMap.php?q="+(l>3?l-3:l),null,"width=532, height=439, scrollbar=0, left="+parseInt((screen.width-532)/2)+", top="+parseInt((screen.height-419)/2));
}

function shMocalDetsF() {
	if($("#shMocalDets").css("opacity")<1) {
		$("#shMocalDets").css("opacity",1).attr("title","Show class details");
		$("#mocal span").each(function(){ $(this).html($(this).children("strong").html()); });
	} else {
		$("#shMocalDets").css("opacity",.5).attr("title","Hide class details");
		$("#mocal span").each(function(){ $(this).html( "<strong>" + $(this).html() + "</strong><br/><em>" + $(this).attr("title").toString().replace(/\n/g,"<br/>")+"</em>" ); });
	}
	manDetsReq=true;
	mocalShowDetails=!mocalShowDetails;
}

$(function() {
	$.fn.outerHTML=function(){return $('<div>').append(this.eq(0).clone()).html();};
	$("#sideDish input").attr("checked",true);

	//$("#btn_hodieView").mousedown();
	$("#btn_classScheduleCnt").mousedown();
	//$("#btn_mocalCnt").mousedown();

	setTimeout('try {if(requestedFilter!=""&&$("#cnt ."+requestedFilter).offset().top!=null) {$("html,body").animate({scrollTop: $("#classScheduleCnt ."+requestedFilter).offset().top-250},500);var temp=$("#classScheduleCnt ."+requestedFilter).offset().top-378;$("#showSingleClassNotice").show().css("marginTop",temp>55?temp:55+"px");setTimeout("$(\'#showSingleClassNotice\').fadeOut()",6666)} } catch(e) {}', 123);
	handleTitles();
	//TODO: Confirm before page unload on notEmptyCart
	//TODO: Trigger cart msg when $_GET['q']=className
	//TODO: Add navigation links in classroom calendars
	//TODO: Add "Where is it?" link next to each classroom
	//$("#buyTicket").mousedown();
	if(/msie/i.test(navigator.userAgent))
		document.onselectstart = new Function("return false");

	if(navigator.cookieEnabled&&getCkVal().length) {
		$("#buyTicket").mousedown();
		for(var i=0, l=getCkVal().split("---"), j=l.length; i<j; ++i)
			$("#m"+l[i]).dblclick();
	}

	if(screen.width>1024)	{$("#showHideCourseSelector").hide();}
	else					{$("#sideDish").css({margin:"-9px 0 0 -1px",paddingRight:"2px"});}

	if(requestedFilter!="") {
		try {
			if($("#cnt ."+requestedFilter).offset().top!=null) {
				$("#sideDish input[type=checkbox]").attr("checked",false);
				$("#topCkToggle").click().attr("checked",false);
				$("#sideDish input[value="+requestedFilter+"]").trigger("click");
				$("#cnt ."+requestedFilter).removeClass("pseudoHidden");
				showAllFromCart();
			}
		} catch(e) {
			$("#showSingleClassNotice").hide();alert("No "+requestedFilter.toUpperCase().replace(/(\d+)/, " $1")+" class this week!");
		}
	}

	/* TODO: Uncomment this for purchasing
	if(requestedAction=="buy") {
		$("#buyTicket").mousedown();
	}
	*/

	$("table td").each(function(){ // March 26, 2010: Make TD higher for 3-hour class - TODO: modularize the function
		if(this.rowSpan==3&&$(this).children("span")!=null)
			$(this).children("span").css("height",82);
	});

	window.onbeforeunload = function() { try { if(document.getElementById('inCart').getElementsByTagName('span').length&&!navigator.cookieEnabled) return "*** You have currently classes in your cart ***"; } catch(e) {return e;} }
	window.onresize       = function() { $("#sideDish").css("marginLeft",$("body").width()<1085?"2px":"-111px") }

	// TODO: Hide empty classroom schedules from print

	// TODO: Remove the following
	// $("#showHideCourseSelector").hide(); // Used for what? Only small-res testing?

	//$("#cartCheckout").mousedown();

	// TODO: Remove
	$("h1").css("visibility","visible");
	$("#buyTicket, #buySeasonPass").hide();

});
