/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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:1,  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:0,  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: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 Volcadas)",  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 volcadas."},
		{id:19,  name:"Intermediate Tango (Ganchos y Enganches)",  cost:120.00,  active:0,  description:"Learn the dynamics of Ganchos and Enganches - everything from embrace changes to the foot and body placement that makes them possible."},
		{id:60,  name:"Intermediate Tango (Boleos)",               cost:60.00,   active:0,  description:"Learn the dynamics of Boleos - how to use opposition for more subtle, yet powerful, boleos."},
		{id:73,  name:"Intermediate Tango (Sacadas)",              cost:120.00,  active:1,  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: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:15.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: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: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:40,  name:"Ballroom Basics",                           cost:120.00,  active:0,  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:2, type:"package", classes:[30,31],  discount:20.00,  description:"Yoga twice a week discount"},
		{id:3, type:"package", classes:[7,4],    discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:4, type:"package", classes:[19,18],  discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:6, type:"package", classes:[1,18],   discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:7, type:"package", classes:[1,4],    discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:8, type:"package", classes:[1,17],   discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:9, type:"package", classes:[73,4],   discount:40.00,  description:"Close-embrace and open-embrace combination package"},
		{id:10,type:"package", classes:[73,17],  discount:40.00,  description:"Close-embrace and open-embrace combination package"},

		{id:20, type:"quantity",  minQty:3,  classes:[62,63,64,65,66,67,68,69,70,71],  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();
