// JavaScript Document for adding products to user's cart
// NOTE: This file implies that the user will include jQuery and form validation prior to including this file.
// 	Otherwise, this file acts almost independently on its own to validate the form product add submission(s)

$(document).ready( function(){
	// First we want to add a custom-validation rule
	jQuery.validator.addMethod( 'item_number', function( value, element){
		// First check our current form to see if this is a grouping item
		return ( ( element.selectedIndex != null && element.value.length > 4 ) || element.selectedIndex == null );
	},'Please make a selection for this item');
	// Next we want to create a handle on our form for appropriate validation
	$('form.product_form').each( function(){
		// Here we have to nest our result to consider the possibility of multiple forms per page( like a search result -OR- even a category page )
		// Make sure we have our "key" form elements
		if( this.qty != null ){
			// First check to make sure that our user has specified the minimum for this product, otherwise we must use 1 as our value
			qtyObj = $(this.qty);
			if( qtyObj.attr('min') == null || +qtyObj.attr('min') <= 0 ){
				qtyObj.attr('min',1);
			}// End min attribute look-up
			// Now we can add valdiation to our result
			$(this).validate({
				showErrors: function(errorMap, errorList){
					if( errorList.length >= 1 ){
						// First determine if we already have created an element for the errors
						objForm = $(this.currentForm);
						// Here we have two possibilities, either our form is wrapped around the table cell, OR the table cell is wrapped around the form
						if( objForm.find('td').length >= 1 ){
							// Here the form is wrapped around the table cell
							objParent = objForm;
						}
						else{
							objParent = objForm.parent();
						}// End conditional for the nesting of our elements
						// Now localize our potential error element
						objError = objParent.find('ul.product_add_error');
						// Now we need to check our current error list to see if it exist or not
						if( objError.length == 0 ){
							// Here we must determine how we will place our current error message( note: goal is to have it inside the current table cell )
							var newElement = '<ul class="product_add_error"></ul>';
							// We expect that our form is either inside a table cell -OR- the table cell is inside the form
							if( objForm.find('td').length >= 1 ){
								objError = objForm.find('td:last-child').append(newElement).find('ul.product_add_error');
							}
							else{
								// The parent here might be our TD cell itself, OR it will be the table
								objError = objForm.parent();
								if( objError.attr('tagName').toLowerCase() == 'td' ){
									objError = objError.append(newElement).find('ul.product_add_error');
								}// End td cell hierarchy
							}// End td cell conditional
						}// End non-existing list condition
						else{
							// Clear entire list( don't worry we'll rebuild )
							objError.empty();
						}// End length check for ul.product_add_error
						// Now add our elements
						jQuery.each( errorList, function(index,value){
							objError.append('<li>'+value.message+'</li>');
						});// End error list output loop
					}// End errorlist length check
				}// End customized showError function
				,submitHandler: function(form){
					// First create a handle of our form object
					var formObj = $(form);
					// First remove our error messages
					// Next check if we have a message to show the user
					if(		typeof(formObj.attr('stock_message')) != 'undefined'
						&&	formObj.attr('stock_message').toUpperCase() == 'Y' )
						alert('NOTICE: The item you have selected is a non-stock item and will have to be special ordered by one of our Customer Service Representatives.\n\nOnce your order is submitted, we will contact you with detailed information including the estimated arrival date of your product.');
					// Check to see if user accepts cookies
					if( document.cookie ){
						// Promote our form to a jQuery object
						if( formObj.ajaxSubmit != null && formObj.attr('ajax') != null && Boolean(formObj.attr('ajax')) == true )
							formObj.ajaxSubmit();
						else if( formObj.ajaxSubmit != null && formObj.attr('nosubmit') != null && Boolean(formObj.attr('nosubmit')) == true )
							return false;
						else
							form.submit();
						return true;
					}// End true clause
					else{
						alert('You must have cookies enabled to access the cart function of our site.\n\nPlease enable cookies before adding items to your cart.');
					}// End false caluse
					// Return status
					return false;
				}// End submitHandler
				,rules:{
					item_number: 'item_number'
					,qty:{
						digits: true
						,required: true
					}// End qty
				}// End rules
				, messages: {
					item_number: 'Please make a selection for this item'
					,qty:{
						min: jQuery.format('You must purchase at least {0} unit(s)')	
						,digits: 'Please enter only digits inside this field'
						,required: 'Please enter a qty to purchase this item'
					}// End qty message
				}// End message
			});// End form validation invocation
		}// End our structure integrity check
	});// End our each function
	// Now over ride our onchange functionality
	$('form.product_form select.suffix_dropdown').change( function(e,v){
		// First localize our item number
		item_number = this.value.toLowerCase().substring(0,12).replace(/^\s+|\s+$/,'');
		suffix = this.value.toLowerCase().replace(item_number,'').replace(/^\s+|\s+$/,'').toUpperCase();
		// Next check to see if we have already accomplished the task at hand, sadly we only will look our suffix value
		if( this.form.suffix.value == suffix )
			return true;
		
		// First check to see if we have our data store on tap
		if( suffixObj != null && suffixObj[item_number] != null ){
			// Localize our current query row
			productObj = suffixObj[item_number];
			currentObj = '';
			// Now that we have found our grouping product, locate current suffix
			for( index in productObj ){
				if( productObj[index]['suffix'] == suffix ){
					// Localize our current object
					currentObj = productObj[index];
					break;
				}// End suffix check
			}// End item traversing
			// Make sure we have our index available
			if( currentObj == '' ){
				this.form.suffix = 0;	// Should flag our form validation as bad selection
				this.selectedIndex = 0;
				return false;
			}
			else{
				// Here we attempt to update our values, if unsuccessful we will pull out
				try{
					// Finally we need to update our current form feed information
					objForm = this.form;
					objForm.uom.value = currentObj['uom'];
					objForm.price.value = currentObj['price'];
					objForm.weight.value = currentObj['weight'];
					objForm.shipping.value = currentObj['ups_ship_type'];
					objForm.suffix.value = currentObj['extended_suffix'];
					objForm.description.value = currentObj['description'];
					// Lets update our preview picture
					jqueryForm = $(objForm);
					jqueryForm.find('img:first-child').eq(0).attr('src','/images/'+currentObj['thumbnail']);
					if( jqueryForm.find('li.companion_product_price').length == 1 && $().formatCurrency != null  )
						jqueryForm.find('li.companion_product_price').html( currentObj['price'] ).formatCurrency({ useHtml: true }).append('/'+currentObj['uom']);
					else if( ( jqueryForm.find('p.price').length == 1 || jqueryForm.find('li.search_product_price').length ==1 ) && $().formatCurrency != null  ){
						// First localize our current selector for the price( difference amongst grid VS normal listing )
						var jQElement = jqueryForm.find('p.price');
						if(		jQElement.length == 0 )
							jQElement = jqueryForm.find('li.search_product_price')
						// Here we most likely are inside of a category listing, start with price
						jQElement.html( currentObj['price'] ).formatCurrency({ useHtml: true }).append('/'+currentObj['uom']);
						// First lets clear out any instance of our special case discount scenarios
						jqueryForm.find('p.special_case span.ormore,p.special_case span.onsale').remove();
						// Next check to see if we have a sale price, and it is greater than zero
						if(		typeof(currentObj['saleprice']) != 'undefined'
							&&	currentObj['saleprice'] > 0 )
							jQElement.before('<p class="special_case"><span class="onsale">On Sale!</span></p>');
						// Create a regular expression object such that we can use for a test
						reBoolean = new RegExp(/^[0|1]$/);
						// Next check to see if we should add discount qty( if available )
						if(		currentObj['discount_qty_start'] != null
							&&	currentObj['discount_qty_price'] != null
							&&	currentObj['discount_qty_lots'] != null
							&&	currentObj['price'] > currentObj['discount_qty_price']
							&&	currentObj['discount_qty_price'] > 0
							&&	currentObj['discount_qty_start'] > 0
							&&	reBoolean.test( currentObj['discount_qty_lots'] )  ){
							// Here we need to place this new string AFTER current price that we just placed
							jQElement.after('<p class="special_case"><span class="ormore">'+currentObj['discount_qty_price']+'</span></p>');
							jqueryForm.find('p.special_case span.ormore').formatCurrency({ useHtml: true }).append(' '+currentObj['uom']+' for '+currentObj['discount_qty_start']+(currentObj['discount_qty_lots'] == 0 ? ' or more' : ''  )+'!');
							//alert('Buy '+currentObj['discount_qty_start']+' for $'+currentObj['discount_qty_price']);
						}// End discount qty check
					}// End price insertion check
					// Finally we will see if this item is a special order
					jqueryForm.attr('stock_message',(currentObj['stock_flag'].toUpperCase()=='N')?'Y':'N');
					return true;
				} catch( err ){
					this.form.suffix = 0;	// Should flag our form validation as bad selection
					this.selectedIndex = 0;
					return false;
				}
			}// End object integrity check
		}// End suffix object data integrity check
		else{
			// Revert selection back to "no-suffix" because we cannot find our target
			this.form.suffix.value = 0;	// Should flag our form validation as bad selection
			this.selectedIndex = 0;
			return false;
		}// End else clause for data integrity check
	}).keyup( function(){
		$(this).change();
	}).change();// End onchange override
	// Here we will create our info box hover capability
	$('a.filter_info').unbind('hover').hover( function(){
		// First set all of our z-indexes to a lower level
		$('a.filter_info').parent().parent().css('z-index',1).css('position','relative');
		// Localize current element
		var jQElement = $(this).parent().parent().css('z-index',1000).find('dl.filter_info_box').fadeIn(200);
		// Return true
		return true;
	}, function(){
		// Localize current element
		var jQElement = $(this).find('dl.filter_info_box').fadeOut(200);
		// Return false
		return false;
	});// End more information hover event
});