/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// the section below defines classes offered
//
// classes should be entered as follows:
// { id:###, name:"XXXXXXXX", cost:###.##, active:#, description:"XXXXXXXX" }
//
//  - id:			a unique id for each class.  once set / used, DON'T EVER CHANGE IT!
//  - name:			the name of the class
//  - cost:			how much the class costs per person (not including any discounts)
//  - active:		either 1 for active or 0 for inactive
//  - description:	junk that might not get used
//    (optional)
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var cdbcClasses =
	[
		{id:1,   name:"Tango 101",                                 cost:120.00,  active:0,  description:"This is a beginning open-embrace Argentine Tango class focusing on frame, embrace, ochos, paradas and basic footwork."},
		{id:2,   name:"Tango 102",                                 cost:120.00,  active:1,  description:"This is a beginning open-embrace Argentine Tango class focusing on basic walking movements, double times, amagues, molinettas, and calicitas as well as the techniques to make them smooth and musical."},
		{id:3,   name:"Tango 103",                                 cost:60.00,   active:0,  description:"This is a beginning open-embrace Argentine Tango class where we begin to learn the 'cross' system."},
		{id:13,  name:"Tango FUNdamentals",                        cost:50.00,   active:0,  description:"Learn the core principles of Argentine Tango basics in a fun a friendly environment."},
		{id:14,  name:"Tango FUNdamentals - Student Discount",     cost:40.00,   active:0,  description:"Learn the core principles of Argentine Tango basics in a fun a friendly environment."},

		{id:8,   name:"Tango Technique (single class pass)",       cost:12.00,   active:1,  description:"Learn independent exercises so that you can practice without a partner and make your tango look like tango."},
		{id:9,   name:"Tango Technique (class card)",              cost:50.00,   active:1,  description:"Learn independent exercises so that you can practice without a partner and make your tango look like tango."},

		{id:4,   name:"Close Embrace Tango",                       cost:100.00,  active:1,  description:"This is close-embrace Argentine Tango class focusing the 'close' embrace and how to do various steps while in this particular embrace."},
		{id:18,  name:"Close Embrace - Level 2",                   cost:100.00,  active:0,  description:"We will continue building upon the basics learned in the Close Embrace Level 1 class."},
		{id:61,  name:"Close Embrace - Milonga Basics",            cost:50.00,   active:0,  description:"Learn the basics that will get you through a set of fast-paced 'Milonga' songs."},
		{id:74,  name:"Close Embrace - Intermediate Milonga Traspie", cost:50.00, active:0, description:"Add ocho cortados, ochos, syncopation, different rhythms, and rotating resolutions to your milonga."},
		{id:17,  name:"Intermediate Close Embrace",                cost:100.00,  active:1,  description:"Learn more advanced techniques for close-embrace tango."},
		{id:11,  name:"Intermediate Tango Close Embrace Combo",    cost:180.00,  active:0,  description:"Combination Close Embrace and Tango Intermediate special."},
		{id:12,  name:"Tango 100 series and Close Embrace combo",  cost:180.00,  active:0,  description:"This is a beginning open-embrace Argentine Tango class where we begin to learn the 'cross' system."},

		{id:7,   name:"Intermediate Tango (Colgadas y Enganches)", cost:120.00,  active:0,  description:"In this class we develop the fundamentals of the intermediate level movement. This session, we will work on colgadas and enganches."},
		{id:19,  name:"Intermediate Tango (Ganchos y Linear Boleos)", cost:120.00, active:0, description:"Learn the dynamics of Ganchos and Linear Boleos - everything from embrace changes to the foot and body placement that makes them possible."},
		{id:60,  name:"Intermediate Tango (Boleos y Volcadas)",    cost:120.00,  active:1,  description:"Develop techniques to use off axis movements that add drama and excitement to the dance."},
		{id:73,  name:"Intermediate Tango (Sacadas)",              cost:120.00,  active:0,  description:"Sacadas are one of the concepts that really define tango.  We will explore back, front and side sacadas for both the lead and follow."},
		{id:72,  name:"Intermediate Tango Introduction to Opposition", cost:75.00, active:0, description:"The idea of this class is to learn what opposition is, how it works and how to apply it to dance so that leading and following becomes more organic."},
		{id:88,  name:"Intermediate Tango (Barridas y Soltadas)",  cost:60.00,   active:0,  description:"Learn about Soltadas and Barridas."},
		{id:75,  name:"Tango Musicality",                          cost:60.00,   active:0,  description:"Learn how tango music is structured and how to use the regular and irregular double times in your dance."},

		{id:10,  name:"Tango Adv Int",                             cost:120.00,  active:1,  description:"Not for the feint of heart."},
		
		{id:15,  name:"Leading for Women",                         cost:60.00,   active:0,  description:"This Argentine tango class is for women that have studied the role of the follower but would like to understand the entire picture better."},
		{id:16,  name:"Following for Men",                         cost:60.00,   active:0,  description:"This Argentine tango class is for men that have studied the role of the leader but would like to understand the entire picture better."},
		{id:62,  name:"Topic - Dancing Big in Small Spaces",       cost:15.00,   active:0,  description:"Focus on embrace, posture and foot placement to create dynamic presence in small spaces."},
		{id:63,  name:"Topic - Classic Boleos",                    cost:15.00,   active:0,  description:"Learn the basic principles of boleos to give you an overview of what they really are, how they work, and when to use them."},
		{id:64,  name:"Topic - Cozy Tango",                        cost:15.00,   active:0,  description:"Learn the tricks on how to make an ok dance really nice and even fun!"},
		{id:65,  name:"Topic - Gancho Sacada Combos",              cost:15.00,   active:0,  description:"This class will play with both concepts in interesting combinations."},
		{id:66,  name:"Topic - How to Make Her Smile",             cost:15.00,   active:0,  description:"In the ideal tango we are beautifully connected and musical and this makes her smile."},
		{id:67,  name:"Topic - Milonga Traspie I",                 cost:15.00,   active:0,  description:"The basics of traspie. This class will be fun fast and furious!"},
		{id:68,  name:"Topic - Milonga Traspie II",                cost:15.00,   active:0,  description:"Part 2 of the Milonga Traspie class."},
		{id:69,  name:"Topic - Playing with the Embrace",          cost:18.00,   active:0,  description:"Learn about the concept of changing the embrace. We will examine when it is practical as well as when it simply adds to the experience of the dance."},
		{id:70,  name:"Topic - The Tango Processor",               cost:15.00,   active:0,  description:"Also known as unnecessary and crazy, this class will help develop the foundation of beginner / intermediate tango material in both entertaining and sometimes impractical ways."},
		{id:71,  name:"Topic - Introduction to Opposition",        cost:15.00,   active:0,  description:"*1 CLASS ONLY*  The idea of this class is to learn what opposition is, how it works and how to apply it to dance so that leading and following becomes more organic."},
		{id:76,  name:"Topic - Find the Swing of Vals",            cost:15.00,   active:0,  description:"Learn new material that suits the rhythm of a vals."},
		{id:77,  name:"Topic - Linear Boleos",                     cost:15.00,   active:0,  description:"Learn the technique of linear boleos and 3 different variations to use out on the dance floor."},
		{id:78,  name:"Topic - Amagues as Entrances",              cost:15.00,   active:0,  description:"Use amagues as entrances into boleos, sacadas, or enganches."},
		{id:79,  name:"Topic - Changing the Embrace",              cost:15.00,   active:0,  description:"Work on two variations of embrace changes that make difficult moves possible and comfortable."},
		{id:80,  name:"Topic - Soltadas",                          cost:15.00,   active:0,  description:"Spice up your tango by adding underarm turns and turns that break the normal embrace."},
		{id:81,  name:"Topic - Embellishments",                    cost:15.00,   active:0,  description:"Create embellishments that flow with the music and material and learn where they make most sense to use them."},
		{id:86,  name:"Topic - Embellishments- Part 2",            cost:15.00,   active:0,  description:"Expand upon what was learned in the initial embellishments class."},
		{id:82,  name:"Topic - Overcoming Height Differentials",   cost:15.00,   active:0,  description:"Sometimes height differences make dancing tango difficult.  This class focuses on tools you can use to make the dance comfortable and enjoyable."},
		{id:83,  name:"Topic - Jewels for the Crowded Dance Floor",cost:15.00,   active:0,  description:"Moves that not only save you from crashing into couples in front of you, but ones that are also fun, musical, and enjoyable for both partners."},
		{id:84,  name:"Topic - Physics of Tango",                  cost:15.00,   active:0,  description:"How and when to use opposition, counterbalance, grounding and momentum."},
		{id:85,  name:"Topic - Solo Exercises For Tango Dancers",  cost:15.00,   active:0,  description:"This popular class is both helpful in developing strength and balance while also creating an entertaining and engaging practice regimen."},
		{id:87,  name:"Topic - Folkloric",                         cost:50.00,   active:0,  description:"The chacarera, zamba and gato are some of the Argentine folkloric dances that began Argentine Tango as we know it today.  Learn how to do these dances so you can join in next time!"},
		{id:89,  name:"Topic - Boleo Technique for Couples",       cost:50.00,   active:0,  description:"Focus on boleo vocabulary and really feel like you can get it without being distracted by other combinations."},
		{id:90,  name:"Topic - Dancing to the Melody I",           cost:18.00,   active:0,  description:"Work on being active during the pause, leading slow pivots, embellishing, and more."},
		{id:91,  name:"Topic - Dancing to the Melody II",          cost:18.00,   active:0,  description:"A continuation of Dancing to the Melody I developing presence during the pause, embellishments, and the pivots."},
		{id:92,  name:"Topic - Irregular Double-Times",            cost:18.00,   active:0,  description:"Focus on two songs and play with rhythmic variations outside of the basic amague timing."},
		{id:93,  name:"Topic - Barrida Technique",                 cost:18.00,   active:0,  description:"Lead a clean barrida. We'll take a strong look at the use of the knee for leaders and followers, pivot, and alignment."},
		{id:94,  name:"Topic - Getting Grounded",                  cost:45.00,   active:0,  description:"Build a stronger foundation of the standing leg and collection in order to create energy and stronger movements."},
		{id:95,  name:"Topic - Vals",                              cost:50.00,   active:0,  description:"Learn different timing and moves suited to three-quarter-time (Vals) style tango."},
		{id:96,  name:"Topic - Vals Swirls and Curls",             cost:50.00,   active:0,  description:"Add to your Vals vocabulary with moves covered in this class."},

		{id:20,  name:"Monday Club Salsa 1",                       cost:100.00,  active:1,  description:"This is a great class for new salsa students!"},
		{id:21,  name:"Thursday Club Salsa 1",                     cost:100.00,  active:0,  description:"This is a great class for new salsa students!"},
		{id:22,  name:"Club Salsa 2",                              cost:100.00,  active:1,  description:"This class works on basic and more advanced spins while taking the fundamentals and complicating them."},
		{id:23,  name:"Mixed Latin Class",                         cost:50.00,   active:0,  description:"Learn some fundamentals of other latin dances outside of salsa that are sometimes played at club dances."},
		
		{id:30,  name:"Yoga - Tuesdays",                           cost:50.00,   active:0,  description:"Yoga is ideal for students of dance who simply wish to explore the possibility of becoming more aware of themselves."},
		{id:31,  name:"Yoga - Thursdays",                          cost:50.00,   active:0,  description:"Yoga is ideal for students of dance who simply wish to explore the possibility of becoming more aware of themselves."},

		{id:140,  name:"Bellydancing",                             cost:100.00,  active:1,  description:"Take an 8-week course to get into shape and have some fun learning how to belly dance."},

		{id:40,  name:"From the Ballroom to the Bar",              cost:90.00,   active:1,   description:"This class introduces you to partner dancing while learning the fundamentals of social dancing."},
		{id:110, name:"Swing / Lindyhop 101",                      cost:100.00,  active:1,   description:"This class introduces you to partner dancing while learning the fundamentals of social dancing."},

		{id:50,  name:"Latin Sampler",                             cost:120.00,  active:0,   description:"Check out the latin styles of dance and get an overview of what dances are done in the latin clubs today."}
	];

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// the section below defines discounts offered
//
// discounts should be entered as follows:
// { id:###, type:"XXXXXXXX", classes:[###,###,###,###], discount:###.##, description:"XXXXXXXX" }
//
//  - id:			a unique id for each discount.
//  - type:			the type of discount being offered. valid options include:
//					"package": a discount for taking certain classes together
//  - classes:		a list of class ids (see above class definitions) that comprise the package
//  - discount:		how much money should be deducted from the total cost when the discount is applied
//  - description:	description that will be displayed on the cart page(s)
//    (optional)
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var cdbcDiscounts =
	[
		{id:1, type:"package", classes:[2,4],    discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:3, type:"package", classes:[60,4],   discount:40.00,  description:"Close-embrace and open-embrace int. combination package"},
		{id:8, type:"package", classes:[2,17],   discount:40.00,  description:"Close-embrace int. and open-embrace combination package"},
		{id:17,type:"package", classes:[60,17],  discount:40.00,  description:"Close-embrace int. and open-embrace int. combination package"},
		{id:10,type:"package", classes:[3,95],   discount:20.00,  description:"Cross-system tango and Vals package"},
		{id:11,type:"package", classes:[3,96],   discount:20.00,  description:"Cross-system tango and Vals package"},

		{id:20, type:"quantity",  minQty:3,  classes:[62,63,64,65,66,67,68,70,71],     discount:3.00,  description:"3 or more topic-class discount"},
		{id:21, type:"quantity",  minQty:3,  classes:[69,90,91,92,93,94],              discount:3.00,  description:"3 or more topic-class discount"}
	];



////////////////////////////////////////////////////////////////////
//
//	*** DO NOT MODIFY ANY OF THE FOLLOWING CODE ***
//
//////////////////////////////////////////////////////////////////

var cart = null;

var addClassToCart = function(classId, classCost)
{
	if(cart == null)
		loadCart();
	cart.addClass(classId, classCost);
	saveCart();
	showViewCartLink();
};

var saveCart = function()
{
	createCookie("classCart", escape(JSON.stringify(cart.classes)), 7);
	createCookie("discountCart", escape(JSON.stringify(cart.discounts)), 7);
};

var clearCart = function()
{
	cart = getEmptyCart();
	saveCart();
};

var getEmptyCart = function()
{
	return {
		classes:[],
		coupons:[],
		discounts:[],
		getClassIndex: function(classId)
		{
			for(var index=0; index < this.classes.length; index++)
			{
				if(classId == this.classes[index].id)
					return index;
			}
			return -1;
		},
		totalCost: function() {
			var classTotal = 0.00;
			for(var classIndex=0; classIndex < this.classes.length; classIndex++) {
				classTotal += (this.classes[classIndex].qty * this.classes[classIndex].cost);
			}
			for(var discountIndex=0; discountIndex < this.discounts.length; discountIndex++) {
				discount = getCdbcDiscount(this.discounts[discountIndex]);
				if(discount != null)
				    classTotal -= calculateDiscountAmount(discount);
			}
			return classTotal;
		},
		addClass: function(classId, classCost) {
			var cIndex = this.getClassIndex(classId);
			if(cIndex > -1)
			{
				this.classes[cIndex].qty++;
			}
			else
			{
				this.classes[this.classes.length] = {id:classId, qty:1, cost:classCost};
			}
			return true;
		},
		removeClass: function(classId) {
			var cIndex = this.getClassIndex(classId);
			if(cIndex > -1)
			{
				this.classes.splice(cIndex,1);
				return true;
			}
			return false;
		},
		updateQty: function(classId, newQty) {
			if(newQty == 0)
				return this.removeClass(classId);
			var cIndex = this.getClassIndex(classId);
			if(cIndex > -1)
			{
				this.classes[cIndex].qty = newQty;
				return true;
			}
			return false;
		},
		classIds: function() {
			var ids = [];
			for(var classIndex=0; classIndex < this.classes.length; classIndex++) {
				ids.push(this.classes[classIndex].id);
			}
			return ids;
		},
		expandClassArray: function() {
			var expandedArray = [];
			for(var classIndex=0; classIndex < this.classes.length; classIndex++) {
				for(var qtyCounter=0; qtyCounter < this.classes[classIndex].qty; qtyCounter++) {
					expandedArray.push(this.classes[classIndex].id);
				}
			}
			return expandedArray;
		}
	}
};

var loadCart = function()
{
	cart = getEmptyCart();
	var cookieCart = readCookie("classCart");
	if(cookieCart != null)
	{
		var cartClasses = JSON.parse(unescape(cookieCart));
		cart.classes = cartClasses;
	}
	cookieCart = readCookie("discountCart");
	if(cookieCart != null)
	{
		var cartDiscounts = JSON.parse(unescape(cookieCart));
		cart.discounts = cartDiscounts;
	}
};

var getCdbcItem = function(cdbcArray, itemId) {
	for(var i=0; i < cdbcArray.length; i++) {
		if(cdbcArray[i].id == itemId) {
			return cdbcArray[i];
		}
	}
	return null;
};

var getCdbcClass = function(classId) {
	return getCdbcItem(cdbcClasses, classId);
};

var getCdbcDiscount = function(discountId) {
	return getCdbcItem(cdbcDiscounts, discountId);
};

Array.prototype.index = function(val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == val) return i;
	}
	return null;
};

Array.prototype.include = function(val) {
	return this.index(val) !== null;
};

Array.prototype.intersect = function(array){
	var common = [];
	for(var i=0;i<this.length;i++){
		if(array.include(this[i]))
			common.push(this[i]);
	}
	return common;
};

var calculateDiscounts = function() {
	if(cart == null)
		loadCart();
	cart.discounts = [];
	var selectedClasses = cart.expandClassArray();

	for(var i=0;i<cdbcDiscounts.length;i++) {
		if(cdbcDiscounts[i].type == "package") {
			if(cdbcDiscounts[i].classes.intersect(selectedClasses).sort().join() == cdbcDiscounts[i].classes.sort().join()) {
				//classes qualify for discount; add discount to cart
				cart.discounts.push(cdbcDiscounts[i].id);
				//classes not eligible for other discounts, so remove them
				for(j=0;j<cdbcDiscounts[i].classes.length;j++) {
					selectedClasses.splice(selectedClasses.indexOf(cdbcDiscounts[i].classes[j]), 1);
				}
				i--;	//need to test this one again just in case if there are multiple quantities
			}
		}
		else if(cdbcDiscounts[i].type == "quantity") {
			var eligibleClasses = selectedClasses.intersect(cdbcDiscounts[i].classes);
			if(eligibleClasses.length >= cdbcDiscounts[i].minQty) {
				//this cart has met the min requirments for the quantity discount
				cart.discounts.push(cdbcDiscounts[i].id);
			}
		}
	}
};

var calculateDiscountAmount = function(cdbcDiscount) {
	if(cdbcDiscount.type == "package")
		return cdbcDiscount.discount;
	else if(cdbcDiscount.type == "quantity") {
		var eligibleClasses = cart.expandClassArray().intersect(cdbcDiscount.classes).length;
		return eligibleClasses * cdbcDiscount.discount;
	}
	return 0;
};




//cookie functions courtesy of Quirksmode
function createCookie(name,value,days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// page setup functions
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var setupClassLinks = function() {
	var classLinks = document.getElementsByTagName("a");
	var linkIndex = 0;
	while(linkIndex < classLinks.length) {
		var classNames = classLinks[linkIndex].className || "";
		var classNameArray = classNames.split("_");
		if(classNameArray[0] == "cdbcClass")
		{
			var classParent = classLinks[linkIndex].parentNode;
			var classId = classNameArray[1];
			var cdbcClass = getCdbcClass(classId);

			// add html elements for cart
			// create class info container div
			var classContainer = document.createElement("div");
			classParent.replaceChild(classContainer, classLinks[linkIndex]);

			// add classname
			var classSpan = document.createElement("span");
			classSpan.className = "className";
			classSpan.appendChild(document.createTextNode(cdbcClass.name + ": "));
			classContainer.appendChild(classSpan);

			if(cdbcClass.active == 1) {
				// next the price
				var classPrice = document.createElement("span");
				classPrice.className = "classPrice";
				classPrice.appendChild(document.createTextNode("$" + cdbcClass.cost));
				classContainer.appendChild(classPrice);

				// and add-to-cart button
				classContainer.appendChild(document.createElement("br"));
				var addToCartButton = document.createElement("input");
				addToCartButton.setAttribute("type", "image");
				addToCartButton.setAttribute("src", "/images/addToCart_bl.png");
				//addToCartButton.setAttribute("onclick", "this.onclick='';this.src='/images/addToCart_grey.png';addClassToCart(" + cdbcClass.id + "," + cdbcClass.cost + ");");
				addToCartButton.setAttribute("classid", cdbcClass.id);
				addToCartButton.setAttribute("classcost", cdbcClass.cost);
				addToCartButton.onclick = function(){this.onclick = null;this.src='/images/addToCart_grey.png';addClassToCart(this.attributes["classid"].value, this.attributes["classcost"].value);};
				classContainer.appendChild(addToCartButton);
			}
			else {
				var notAvailable = document.createElement("span");
				notAvailable.className = "classNotActive";
				notAvailable.appendChild(document.createTextNode("not currently being offered"));
				classContainer.appendChild(notAvailable);
			}
		}
		else {
		    linkIndex++;
		}
	}
};

var setupViewCartLink = function() {
	loadCart();
	showViewCartLink();
}

var showViewCartLink = function() {
	if(cart.classes.length > 0) {
		var viewCartLink = document.getElementById("viewCartLink");
		if(viewCartLink != null)
			viewCartLink.style.display = "";
	}
};

setupClassLinks();
setupViewCartLink();

