/**
 * @author mamihod
 * @namespace YAHOO.Sun
 * @projectDescription Javascript for the Sun Shop portion of the site.
 *  
 */
$SS = YAHOO.namespace("Sun.shop");

$SS.handleSuccess = function(o){
	
	if(o.responseText !== undefined){
		//indexOf doesn't work for IE out of box - so the snippet is in shortcuts 
		//to add that to array object if its not available.
		
		//This first one handled standard add to reqs, and updates the sidebar shopping cart.

		if(o.argument.indexOf('responseDiv') > -1){
			var divindex = 	(o.argument.indexOf('responseDiv')) + 1;
			var div = window.document.getElementById(o.argument[divindex]);
			
			div.innerHTML = o.responseText;
			
			//And trigger the Button Anim
			var divindex = 	(o.argument.indexOf('requester')) + 1;
			$SS.buttonFlash(o.argument[divindex]);
			
			//And trigger the cart flash
			div = window.document.getElementById('cartitem_'+o.argument[divindex]);
			$SS.flashEl(div, '#ff0','#E0E1E2');	
			
		}
		else if(o.argument.indexOf('tocDiv') > -1){ //TOC Request?
			var divindex = 	(o.argument.indexOf('tocDiv')) + 1;
			var div = window.document.getElementById(o.argument[divindex]);

			div.innerHTML = o.responseText;

			if(div.className == 'issue_toc'){
				div.innerHTML += '<p><a href="#" class="caps" id="close_'+o.argument[divindex]+'">Close Table of Contents</a><p>'; 
				//new YAHOO.widget.Effects.BlindDown(div, {ghost: true});
				$D.setStyle(div,"opacity","0");
				var anim = new YAHOO.util.Anim(div, {opacity: { to: 1 }, height:{ from: 0 , to: 100, unit: '%'} } , 3, YAHOO.util.Easing.easeOut);
				anim.animate();
				$D.setStyle(div, 'visibility', 'visible');
				$D.setStyle(div, 'display', 'block');
//				new YAHOO.widget.Effects.BlindDown(div, {ghost: true});
				
			}

		}
		else if(o.argument.indexOf('update') > -1) {  //An Update request?
			var response = eval('('+o.responseText+')');
			//Update the item total
			var div = window.document.getElementById('subtotal_'+response.update);
			div.innerHTML = response.itemTotal;
			$SS.flashEl(div, '#ff0','#fff');	

			//reuse div
			div = window.document.getElementById('subholder');
			div.innerHTML = response.subtotal;
			
			$SS.flashEl(div, '#ff0','#fff');
			
		} else if(o.argument.indexOf('remove') > -1) {  //A Remove request?
			
			$SS.removeFromPage(o);
	
		}
	}
};

$SS.handleFailure = function(o){

	if(o.responseText !== undefined){
		var divindex = (o.argument.indexOf('responseDiv')) + 1;
		var div = document.getElementById(o.argument[divindex]);

		div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
		div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
		div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
	}
};

$SS.callback = {
  success:$SS.handleSuccess,
  failure:$SS.handleFailure
};


$SS.addToCart = function(updateId){
	
	//Certain Assumptions are made here, since the add to cart forms follow a specific pattern:
	//orderform_productcodeId

	var formid = "orderform_"+updateId
	var sUrl = "action/add_to_cart/";

	//Set where the response should be written to - this is picked up by success/failure handlers to know where to write too.
	$SS.callback.argument = ["responseDiv", "shopping_cart", "requester", updateId];
	
	//Roll up the form.
	YAHOO.util.Connect.setForm(formid);

	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, $SS.callback);
	
}


$SS.removeFromCart = function(removeId) {

	var formid = "orderform_"+removeId;
	var sUrl = "action/update_cart/";

	$SS.callback.argument = ["remove"];

	//Roll up the form.
	YAHOO.util.Connect.setForm(formid);

	//This is to 'trick' the php - for some reason, form rollup doesnt include the buttons themselves in the post,
	//so this makes it compatible with non-javascript
	var extradata = "remove_"+removeId+"=1";

	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, $SS.callback, extradata);

}

$SS.removeFromPage = function(o) {
	
	var response = eval('('+o.responseText+')');
	var div = window.document.getElementById('detail_'+response.remove);

	var shopcatalogue = div.parentNode;

	div.parentNode.removeChild(div);
	
	if(response.subtotal == '0.00'){
		shopcatalogue.innerHTML = 'Your have nothing in your cart.' + shopcatalogue.innerHTML;
	}

	// //lets not forget the subtotal.
	// //reuse div
	div = window.document.getElementById('subholder');
	div.innerHTML = response.subtotal;

}

$SS.updateToCart = function(updateId){

	var formid = "orderform_"+updateId;
	var sUrl = "action/update_cart/";

	//In case someone puts a quantity of 0 for an update, send the request to remove item instead.
	var theform = $D.get(formid);
	if(theform.quantity.value == 0){

		$SS.removeFromCart(updateId);
	}
	else {
	
		//Set where the response should be written to - this is picked up by success/failure handlers to know where to write too.
		$SS.callback.argument = ["update"];
		
		//Roll up the form.
		YAHOO.util.Connect.setForm(formid);
	
		//This is to 'trick' the php - for some reason, form rollup doesnt include the buttons themselves in the post,
		//so this makes it compatible with non-javascript
		var extradata = "update_"+updateId+"=1";
	
		var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, $SS.callback, extradata);
	}
}

$SS.clickHandler = function(e){
	//get the target

	var elTarget = $E.getTarget(e);
	var passThru = false;
	
	//There seems to be some discrepencies on how safari vs. ff and ie get the element
	//safari returns img, but FF/IE return the button element. 
	//This is a hack to fix it - if its an image, lets check if the parent is a button.
	//It also seems certain console.log calls can make safari crash - :(
	if(elTarget.tagName.toLowerCase() == 'img' && elTarget.parentNode.tagName.toLowerCase() == 'button') {
		elTarget = elTarget.parentNode;
	}

	if( elTarget.tagName.toLowerCase() == 'a' || elTarget.tagName.toLowerCase() == 'button' ){
		var command = elTarget.id.split('_')[0];
		var issueId = elTarget.id.split('_')[1];

		switch(command){
			
			case('add'):
				$SS.addToCart(issueId);
				break;
			case('update'):
				$SS.updateToCart(issueId);
				break;
			case('remove'):
				$SS.removeFromCart(issueId);
				break;
			case('toc'):
			
				var togglerEl = $D.get("tocdiv_"+issueId);

				if($D.getStyle(togglerEl,'visibility') != 'visible'){
					$SS.toc(issueId);	
				} else {
				 	//So now, title will behave like a toggle
				 	$SS.closeDiv(togglerEl, issueId);
				 }
				break;
			case('close'):
				//pull the issue id
				issueId = elTarget.id.split('_')[2];
				$SS.closeDiv(elTarget.parentNode.parentNode, issueId);
				break;
			default:
			//Anything not matching, i want to allow through. So, will use a flag tocontrol stop event, rather than scattering that call around.
				passThru = true;

		}	

		//Since we target the listens wit a div wrapper, some links creep into the content. 
		//This makes sure if its not a recognized command, that the default for the element clicked get fired.
		if(passThru == false ) $E.stopEvent(e);
	}
	
}

$SS.closeDiv = function(el, issueId) {
	//var anim = new YAHOO.util.Anim(el, { opacity: { to: 0 }, height: {to: 0 } }, 3, YAHOO.util.Easing.easeOut);
	//anim.animate();
	$D.get('arrowIcon_'+issueId).src = '_images/common/arrow_collapse.gif';
	new YAHOO.widget.Effects.BlindUp(el, {ghost: true});
}

$SS.animDoneHandler = function (type,args) {
	//var theTarget = $E.getTarget(e,1);
	var el = this.getEl();
	el.parentNode.removeChild(el);
}
	

$SS.buttonFlash = function(id) {

	var imgButton = $D.get('addto_'+id);

	var addedDiv = document.createElement('div');
	addedDiv.innerHTML = '<img id="addedto_add_1" alt="Added to cart" src="_images/common/added_to_cart.gif" />';

	//Set it position to absoute
	//and set its position to that of the image button.
	//Then append it to the doc
	$D.setStyle(addedDiv,"position","absolute");
	document.body.appendChild(addedDiv);
	$D.setXY(addedDiv,$D.getXY(imgButton));

	var anim = new YAHOO.util.Anim(addedDiv, { opacity: { to: 0 } }, 2, YAHOO.util.Easing.easeOut);
	anim.onComplete.subscribe($SS.animDoneHandler);
	
	/*IMPORTANT - USE CLOSURE HERE TO DEAL WITH SETTIMEOUT SCOPING 'ISSUES' */
	setTimeout(function(){anim.animate();},1000);
	//$SS.setTimeout(anim);
}

$SS.flashEl = function(el, fromColour, toColour) {
	
	if(typeof toColour == 'undefined'){
		toColour = '#fff';
	}
	if(typeof fromColour == 'undefined'){
		fromColour = '#ff0';
	}
	
	$D.setStyle(el,'background-color',fromColour);
	
	var attributes = {
      backgroundColor: { from: fromColour, to:  toColour}
	};
   
	var anim = new YAHOO.util.ColorAnim(el, attributes,3);
	anim.animate();
}

$SS.toc = function(issueId){

	//change arow to expand
	$D.get('arrowIcon_'+issueId).src = '_images/common/arrow_expand.gif';

	//Fetch toc html
	//insert into tocdiv_issueId
	var sUrl = "action/issue_toc/";
	var postData =  'issue_id='+issueId;
	$SS.callback.argument = ["tocDiv", "tocdiv_"+issueId];

	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, $SS.callback,postData);

}

$SS.init = function(){

	//Anything that needs init-ing

	//$E.on('back_issues_shop', "click", $SS.clickHandler); 

	//Listen to the catalogue, if it exists.
	$E.on('shop_catalogue', "click", $SS.clickHandler); 

}

 
$E.onDOMReady($SS.init); 