// JavaScript Document
var currentModule = '';
var modulewrapper = '';
/*-----------------------------------------------------------------
loadButtons()

Called from loadListener

loadButtons() loops through the provided context, looking for div's with the class of "module-right".  If the divs exist, the function applies an eventListener to them that handles adding the associated modules to the user's "cart"
-----------------------------------------------------------------*/
function loadButtons() {
	/*if(Spry.$('left-module')) {
		var buttonCol = Spry.$('left-module').getElementsByTagName('img');
		for(i=0;i<buttonCol.length;i++) {
			if(buttonCol[i].parentNode.className == 'module-right-parent') {
				Spry.Utils.addEventListener(buttonCol[i], "click", fadeOutButton, false);
			}
			if(buttonCol[i].parentNode.className == 'module-right-parent saved') {
				Spry.Utils.addEventListener(buttonCol[i].nextSibling,'click',fadeOutButton, false);	
			}
		}
	}*/
	loadEventListeners();
	if(Spry.$('Show-Cart')) {
		Spry.Utils.addEventListener('Show-Cart','mouseover',swapImage,false);
		Spry.Utils.addEventListener('Show-Cart','mouseout',swapImage,false);
	}
}

function swapImage() {
	if(this.src.match('images/View-Cart.gif')) {
		this.src = '../images/View-Cart.gif';	
		return;
	}
	if(this.src.match('images/View-Cart.gif') != '') {
		this.src = '../images/View-Cart.gif';	
	}
}

function loadEventListeners() {
	if(Spry.$('left-module')) {
		modulewrapper = 'left-module';	
	}
	if(Spry.$('left')) {
		modulewrapper = 'left';	
	}
	if(Spry.$(modulewrapper)) {
		var buttonCol = Spry.$(modulewrapper).getElementsByTagName('img');
		for(i=0;i<buttonCol.length;i++) {
			if(buttonCol[i].parentNode.className == 'module-right-parent') {
				Spry.Utils.addEventListener(buttonCol[i], "click", fadeOutButton, false);
			}
			if(buttonCol[i].parentNode.className == 'module-right-parent saved') {
				Spry.Utils.addEventListener(buttonCol[i].nextSibling,'click',fadeOutButton, false);	
			}
		}
	}
}

function killEventListeners() {
	if(Spry.$(modulewrapper)) {
		var buttonCol = Spry.$(modulewrapper).getElementsByTagName('img');
		for(i=0;i<buttonCol.length;i++) {
			if(buttonCol[i].parentNode.className == 'module-right-parent') {
				Spry.Utils.removeEventListener(buttonCol[i], "click", fadeOutButton, false);
			}
			if(buttonCol[i].parentNode.className == 'module-right-parent saved') {
				Spry.Utils.removeEventListener(buttonCol[i].nextSibling,'click',fadeOutButton, false);	
			}
		}
	}
}
/*-----------------------------------------------------------------
fadeButton()

Called from user interaction with "save" buttons in module widgets

fadeOutButton() applies a fade effect to the clicked button, and removes the previously created eventListener so that the user cannot repeat the function again.  When the fade effect is finished, the function invokes "saveModule"
-----------------------------------------------------------------*/
function fadeOutButton() {
	currentModule = this;
	/*Spry.Utils.removeEventListener(currentModule, "click", fadeOutButton, false);*/
	killEventListeners();
	var name = splitString(currentModule.id,0);
	var num	= splitString(currentModule.id,1);
	if(name=='delete') {
		var fadeOut = new Spry.Effect.Fade(currentModule, {duration: 200, from: 100, to: 0, toggle:false, finish:removeModule});
		var fadeOut2 = new Spry.Effect.Fade(currentModule.previousSibling, {duration: 200, from: 100, to: 0, toggle:false});
		fadeOut2.start();
		fadeOut.start();
	}
	else {
		var fadeOut = new Spry.Effect.Fade(currentModule, {duration: 200, from: 100, to: 0, toggle:false, finish:saveModule});
		fadeOut.start();	
	}
}

/*-----------------------------------------------------------------
saveModule()

Called from fadeOutButton()

saveModule()'s only purpose is to handle the interaction with the webservice on the server.  It calls the checkCookie() function to determine if the user already has a cart saved in client memory.  Additionally, it parses the id of the object passed to it to determine the courseID that is to be written to the cart.  When saveModule() finishes, it invokes fadeInButton() to handle the visual confirmation for the user
-----------------------------------------------------------------*/
function saveModule() {	
	var CMID = splitString(currentModule.id,1);
	Spry.Utils.loadURL('POST','../cfc/wwo.cfc?method=saveToCart',false,fadeInButton, { postData: "cookieID="+checkCookie()+"&CMID="+CMID, headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }});
}
/*-----------------------------------------------------------------
removeModule()

Called from fadeOutButton()

saveModule()'s only purpose is to handle the interaction with the webservice on the server.  It calls the checkCookie() function to determine if the user already has a cart saved in client memory.  Additionally, it parses the id of the object passed to it to determine the courseID that is to be written to the cart.  When saveModule() finishes, it invokes fadeInButton() to handle the visual confirmation for the user
-----------------------------------------------------------------*/
function removeModule() {	
	var CMID = splitString(currentModule.id,1);
	Spry.Utils.loadURL('POST','../cfc/wwo.cfc?method=removeFromCart',false,fadeInButton, { postData: "cookieID="+checkCookie()+"&CMID="+CMID, headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }});
}

/*-----------------------------------------------------------------
fadeInButton()

Called from saveModule()

fadeInButtion() requires a single parameter, the response from the webservice call.  It parses the xhRequest to determine if the server call was successful.  If a message of success exists in the xhRequest, an additional class name is appended to the button for giving the user visual confirmation of a successful save.  

After the xhRequest is parsed, a final fade in effect is applied to redisplay the button.  If the xhRequest indicates success, a "Saved" button will be visible; if it fails, the original button will be re-faded in.
-----------------------------------------------------------------*/
function fadeInButton(req) {
	if(req.xhRequest.responseText=='success') {
		Spry.Utils.addClassName(currentModule.parentNode, 'saved');
		currentModule.src="../images/save_class_saved.png";
		Spry.Utils.addEventListener(currentModule.nextSibling, "click", fadeOutButton, false);
		/*var deleteButton = document.createElement('img');
		deleteButton.setAttribute('src','images/delete_module.png');
		deleteButton.setAttribute('class','module-delete');
		deleteButton.setAttribute('id','delete-' + splitString(currentModule.id,1));
		currentModule.parentNode.appendChild(deleteButton);*/
		updateMiniCart(splitString(currentModule.id,1),'add');
		
		var fadeIn = new Spry.Effect.Fade(currentModule, {duration: 200, from: 0, to: 100, toggle:false});
		var fadeIn2= new Spry.Effect.Fade(currentModule.nextSibling, {duration: 200, from: 0, to: 100, toggle:false,finish:loadEventListeners});
		fadeIn2.start();
		fadeIn.start();
	}
	if(req.xhRequest.responseText=='deleted') {
		Spry.Utils.removeClassName(currentModule.parentNode,'saved');
		currentModule.previousSibling.src="../images/save_class.png";
		Spry.Utils.addClassName(currentModule,'hidden');
		Spry.Utils.addEventListener(currentModule.previousSibling, "click", fadeOutButton, false);
		updateMiniCart(splitString(currentModule.id,1),'delete');
		var fadeIn = new Spry.Effect.Fade(currentModule.previousSibling, {duration: 200, from: 0, to: 100, toggle:false,finish:loadEventListeners});
		fadeIn.start();
	}	
}

function updateMiniCart(id,action) {
	count = Spry.$('cart-count');
	total = Spry.$('mini-cart-subtotal');
	cart = Spry.$('mini-cart');
	cartCol = cart.getElementsByTagName('li');					   
	for(i=0;i<cartCol.length;i++) {
		var cartItem = splitString(cartCol[i].id,1);
		if(action=='delete') {
			if(cartItem==id) {
				cart.removeChild(cartCol[i]);	
			}
		}
	}
	
	if(action=='add') {
		var miniID = 'minicart-' + id;
		var modtotal = Spry.$('moduletotal-'+id);
		var title = Spry.$('title-'+id);
		
		var newLI = document.createElement('li');
		newLI.setAttribute('id',miniID);
		
		var subID = 'subtotal-' + id;
		/*var newDIV = document.createElement('div');
		newDIV.setAttribute('style','display:none;visibility:hidden;');
		newDIV.setAttribute('className','hidden-totals');
		newDIV.setAttribute('id',subID);
		newDIV.innerHTML = modtotal.innerHTML.replace(/\$/,'');*/
		cart.appendChild(newLI);
		
		var liParent = Spry.$(miniID);
		
		
		var newA = document.createElement('a');
		newA.setAttribute('href','search_modules.cfm?course='+id);
		newA.innerHTML = title.innerHTML;
		
		
		liParent.appendChild(newA);
		/*liParent.appendChild(newDIV);*/
	}
	
	
	liCol = cart.getElementsByTagName('li');
	var subtotal = '';
	
	for(i=0;i<liCol.length;i++) {
		if(i!=(liCol.length-1)) {
		subtotal += splitString(liCol[i].id,1)+',';	
		}
		else {
		subtotal += splitString(liCol[i].id,1);		
		}
	}
	if(subtotal.length != 0) {
		var newTotal = new Number(getTotalCartCost(subtotal));
	}
	else {
		var newTotal = 0;
	}
	
	count.innerHTML = cartCol.length;
	if(newTotal != 0) {
		total.innerHTML = 'Your Cart Total:  $'+newTotal.toFixed(2);
	}
	else {
		total.innerHTML = 'Your Cart Total:  $0.00';
	}
	
}

function getTotalCartCost(list) {
	var request = Spry.Utils.loadURL('GET','../cfc/wwo.cfc?method=getTotalCartCost&ModuleList='+list,false);
	return request.xhRequest.responseText;
}
/*-----------------------------------------------------------------
checkCookie()

Called from saveModule()

checkCookie() sniffs the users' client, checking to see if the "CARTCLIENTID" exists.  If it does, checkCookie() returns the value of CARTCLIENTID; otherwise, it simply returns a null value.
-----------------------------------------------------------------*/
function checkCookie() {
	var name = 'CARTCLIENTID';
	if (document.cookie.length>0) {
  		c_start=document.cookie.indexOf(name + "=");
  		if (c_start!=-1) { 
    		c_start=c_start + name.length+1; 
    		c_end=document.cookie.indexOf(";",c_start);
    		if (c_end==-1) c_end=document.cookie.length;
    		return unescape(document.cookie.substring(c_start,c_end));
    	} 
  	}
	return "";
}

function splitString(ele,pos) {
	var stringArray = ele.split('-');
	return stringArray[pos];
}