/****************************************************************
This jquery plugin makes all the forms in its wrapped set buyform enabled.
This means that the qty checks are done with an overlay for a display 
element

*************************************************************/

(function($){
	var settings = {
		overlayid: '#theoverlay',
		ajaxURL: '/ajax/getBuyData.cfm',
		postURL: '/buy.cfm',
		expose : {
			color: '#99ccff',
			opacity: 0.7,
			zIndex: 500
		}
	}
	
	// seperate handles for the overlay and its API. You make calls to the API. Set content in the overlay div
	var jQo, jQoAPI, buyData;
	
	// Some housekeeping commands
	_closeOverlay = function(){
		if(jQoAPI.isOpened()) jQoAPI.close();
	}
	
	_clearOverlay = function(){
		jQo.find(".overlaycontent").html('');
	}
				
	// This is how we write to the overlay 1. clear it 2. append to it.
	_writeToOverlay = function( content, width, height ){
		_clearOverlay();
		_appendToOverlay( content, width, height );
	}
	
	// This is how to add to the overlay it opens it if not showing yet.
	_appendToOverlay = function( content, width, height ){
		if(!jQoAPI.isOpened()) jQoAPI.load();
		jQo.find(".overlaycontent").append( content );
		jQo.find("button, img.button").bind('click.overlay', _overlayListener );		
	}
	
	// postback after ajax call to get qty scenarios for all buys. Remember all keys in buyData are upper case
	_processPostBack = function(json,success){
		var isError = false;
		for(key in json){ if( key == 'ERROR' ){ isError = true; break;} }
		
		if(isError){
			alert( json.ERROR );
			
		} else {	
			buyData = json;
			buyData.CURRENT = 0;
			_processBuyData();
		}
	}
	
	// Analyze what was returned and show dialog if we need to
	_processBuyData = function(next){
		var nextIndex = next ? ++buyData.CURRENT: buyData.CURRENT;
		var result;
		var keepgoing = true;
							
		for(x=nextIndex; x < buyData.BUYS.length; x++){
			buyData.CURRENT = x;
			result = '';
			keepgoing = false;
			var thisBuy = buyData.BUYS[ x ];
			
			switch( thisBuy.SCENARIO ){ 
				case 1: // min qty violation
				 	result += 'The ' + thisBuy.DESCRIPTION + ' has a minimum order quantity of ' + thisBuy.MINQTY + '.<BR>';
					result += 'Do you want to change your order to <input type="text" size="3" id="newqty" value="' + thisBuy.MINQTY + '"> of this item to ship on ' + thisBuy.SHIPDATE + '<BR>';
					//result += 'or cancel this portion of your order?<br><br>';
					result += 'or remove this item from your cart?<br><br>';
					if(thisBuy.PRODREF){
						result += '<br><br><img src="\/images\/cat_img\/' + thisBuy.PRODREF + '.jpg" border="0" alt="' + thisBuy.DESCRIPTION + '"><br>'
					};
					result += '<hr> <img class="button" id="btnChangeQty" src="/graphics/site/overlay/Change.gif"> <img class="button" id="btnAddNotOK" src="/graphics/site/overlay/Cancel.gif">';
				 break;
				 
				 case 5: // don't sell 
				 	result += 'Because of great popularity the ' + thisBuy.DESCRIPTION + ' is out of stock and will no longer be available. <br>';
					result += 'We apologize for any inconvenience.<br><br>';
					if(thisBuy.PRODREF){
						result += '<br><br><img src="\/images\/cat_img\/' + thisBuy.PRODREF + '.jpg" border="0" alt="' + thisBuy.DESCRIPTION + '"><br>'
					};
					result += '<hr> <img class="button" id="btnAddNotOK" src="/graphics/site/overlay/Cancel.gif" border="0">';
				 break;
				 
				 case 9: // don't sell past maxqty
				 	result += 'We only have ' + thisBuy.MAXQTY + ' of ' + thisBuy.DESCRIPTION + ' left. Would you like to change your order to <input type="text" size="3" id="newqty" value="' + thisBuy.MAXQTY + '"> of this item to ship on ' + thisBuy.SHIPDATE + ' or remove this item from your cart?<br><br>';
				 	//result += 'Because of great popularity, we have just ' + thisBuy.MAXQTY + ' of the ' + thisBuy.DESCRIPTION + ' left for this season.<BR>';
					//result += 'Do you want to change your order to <input type="text" size="3" id="newqty" value="' + thisBuy.MAXQTY + '"> of this item to ship on ' + thisBuy.SHIPDATE + ' ';
					//result += 'or cancel this portion of your order?<br><br>';
					if(thisBuy.PRODREF){
						result += '<br><img src="\/images\/cat_img\/' + thisBuy.PRODREF + '.jpg" border="0" alt="' + thisBuy.DESCRIPTION + '"><br>'
					};
					result += '<hr> <img class="button" id="btnChangeQty" src="/graphics/site/overlay/Change.gif" border="0"> <img  class="button" id="btnAddNotOK" src="/graphics/site/overlay/Cancel.gif" border="0">';
				 break;
				 
				 case 10: // sold out for the season
				 	result += thisBuy.DESCRIPTION + ' is currently out of stock. No expected ship date. <br><br>';
				 	//result += 'Because of great popularity the ' + thisBuy.DESCRIPTION + ' is sold out for the season. <br><br>';
					if(thisBuy.PRODREF){
						result += '<br><img src="\/images\/cat_img\/' + thisBuy.PRODREF + '.jpg" border="0" alt="' + thisBuy.DESCRIPTION + '"><br>'
					};
					result += '<hr> <img class="button" id="btnAddNotOK" src="/graphics/site/overlay/OK.gif" border="0">';
				 break;
				 
				 case 11: // less then min qty left treat as a 10
				 	result += 'The ' + thisBuy.DESCRIPTION + ' is sold out for the season. <br><br>';
					if(thisBuy.PRODREF){
						result += '<br><img src="\/images\/cat_img\/' + thisBuy.PRODREF + '.jpg" border="0" alt="' + thisBuy.DESCRIPTION + '"><br>'
					};
					result += '<hr> <img class="button" id="btnAddNotOK" src="/graphics/site/overlay/OK.gif" border="0">';
				 break;
				 
				 default: // to sell is ok just need to ok the shipdate (0,3,7,8)
				 	if(thisBuy.DAYSTOSHIP > 2){
						result += 'The ' + thisBuy.DESCRIPTION + ' can ship on ' + thisBuy.SHIPDATE + '.<br>';
						result += 'Can we add this to your order? <br><br>';
						if(thisBuy.PRODREF){
							result += '<br><img src="\/images\/cat_img\/' + thisBuy.PRODREF + '.jpg" border="0" alt="' + thisBuy.DESCRIPTION + '"><br>'
						};
						result += '<hr> <img class="button" id="btnAddOK" src="/graphics/site/overlay/Yes.gif" border="0"> <img class="button" id="btnAddNotOK" src="/graphics/site/overlay/No.gif" border="0">';
					} else {
						thisBuy.INCLUDE = true;
				 		keepgoing = true;
					}
			}// switch
			
			if(!keepgoing){ _writeToOverlay( result ); break;}
		}
		
		// If we got here while keepgoing then we are done so lets submit
		if(keepgoing){
			jQoAPI.close();
			_submitBuy()
		}
	} //_processBuyData
	
	
	_submitBuy = function(){
		// lets see if we have any buys remaining that are to be included. We may not have anything left to submit
		var haveItems = false;
		for(x = 0; x < buyData.BUYS.length; x++){
			if(buyData.BUYS[ x ].INCLUDE) { haveItems = true; break; }
		}
		
		// we want to move the browser to the regular buy page to merge with the regular flow again
		// so we build a form to post and then submit it as the browser.
		// the daystoship_ parameter is the flag for the buyhandler to skip the shipdate dialog.
		if(haveItems){ 
			var formstring = '';
			formstring += '<form action="' + settings.postURL + '" method="post" name="frmajxpost" id="frmajxpost">';
			formstring += '<input type="Hidden" name="s7code" value="' + buyData.S7CODE + '">';
			formstring += '<input type="Hidden" name="custdata" value="' + buyData.CUSTDATA + '">';
			formstring += '<input type="Hidden" name="compdata" value="' + buyData.COMPDATA + '">';
			// now add the included buys
			for(x = 1; x <= buyData.BUYS.length; x++){
				var thisBuy = buyData.BUYS[ x-1 ];
				if(	thisBuy.INCLUDE){ 
					formstring += '<input type="Hidden" name="qty_' + x + '" value="' + thisBuy.QTY + '">';
					formstring += '<input type="Hidden" name="buy_' + x + '" value="' + thisBuy.BUY + '">';
					formstring += '<input type="Hidden" name="design_' + x + '" value="' + thisBuy.DESIGN + '">';
					formstring += '<input type="Hidden" name="daystoship_' + x + '" value="' + thisBuy.DAYSTOSHIP + '">';
					if(thisBuy.PRODREF)
						formstring += '<input type="Hidden" name="prodref_' + x + '" value="' + thisBuy.PRODREF + '">';
				}
			}
			formstring += '<\/form>';
			$(formstring).appendTo( document.body );
			document.frmajxpost.submit();			
		}
	}		
	
	_overlayListener = function(e){
		e.stopPropagation(); // the overlay starts acting strange in FF if you don't
		// PageBus.dump(e,3);
		var thisBuy = buyData.BUYS[buyData.CURRENT];
		
		switch( e.target.id ){
			case 'btnAddOK': 
				thisBuy.INCLUDE = true;
				_processBuyData(true);
			break;
			
			case 'btnAddNotOK':
				thisBuy.INCLUDE = false;
				_processBuyData(true);
			break;
			
			case 'btnChangeQty':
				// there must be a newqty field on the overlay some where to get this button click 
				var theNewQty = parseInt( $(jQo).find("#newqty").val() );
				
				if(theNewQty > 0){	// You can't trust those buyers
				
					if(theNewQty < thisBuy.MINQTY){
						$(jQo).find("#newqty").val(thisBuy.MINQTY);
						alert( 'You can not order less than ' + thisBuy.MINQTY + ' of this item');
					} else if(theNewQty > thisBuy.MAXQTY){
						$(jQo).find("#newqty").val(thisBuy.MAXQTY);
						alert( 'You can not order more than ' + thisBuy.MAXQTY + ' of this item');
					} else {
						thisBuy.QTY = theNewQty;
						thisBuy.INCLUDE = true;
						_processBuyData(true);
					}
				} else {
					alert( 'You must enter a quantity or cancel' )
				}
			break;
			
			case 'btnCancel': 
				jQoAPI.close();
			break;
			
			default: jQo.find(".overlaycontent").html(e.target.innerHTML + '-ing')
		}
	}
	
	$.fn.buyform = function(opts){
		// merge the opts if any were passed in
		$.extend(settings, opts || {} );
		
		// instantiate the overlay with an expose no less ( colored background )
		// if no overlay div was established just add your own
		jQo = $( settings.overlayid );
		if(jQo.length == 0){
			jQo = $('<div class="anoverlay" id="theoverlay"><div class="overlaycontent"></div></div>').appendTo( document.body ).hide();
		}
		
		jQo.overlay({
			onBeforeLoad: function(){
				this.getBackgroundImage().expose( settings.expose );
			},
			onClose: function(){
				$.expose.close();
			}
		});
				
		// you must call overlay again to get handle on the api
		jQoAPI = jQo.overlay();	
			
		// lets make it chainable by returning to original wrapped set
		return this.each(function(){
			// alert( this.name );
			this.onsubmit = function(){
				
				var myfields = $(this).serialize();
				$.post(settings.ajaxURL, myfields, _processPostBack, 'json');
				//$.getJSON(settings.ajaxURL, myfields, _processPostBack);
				
				// gracefull degrade. If no javascript then the form submits as usual otherwise we hijack the post here
				return false;
			}			
		});
	}
	
	
	// just a function put in the $ scope so as not to splatter the global space. customizer uses it to submit data
	$.fireExternalForm = function( formhtml, id, btn ){
		frmid = id || '#frms7buy';	
		submitid = btn || '#frms7submit';
		
		$( frmid ).remove(); // remove any previous forms we may have already written but user cancelled out of
		$( document.body ).append( formhtml );
		$( frmid ).buyform();
		$( submitid ).click(); 
	}
	
})(jQuery);