<!--// 
String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}
// create trim function
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

/** Author: MJB 
 * 	Desc:	determines if element exists and adds to $. */
$.exists = function(selector) {return ($(selector).length > 0);}

$.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test($(elem)[attr.method](attr.property));
}

/**
 *	Extended to allow submission by code,qty in textarea. 
 *
	setup_quickorder( button_id, [Optional: true for assign to passed form name])
*/
function setup_quickorder( button_id ) { 

	// for each qoorder button, attach click event and call quickorder
		/** 
		 *	Form must be contructed as follows
		 * 	
		 *  <form name="quickorder_[UNIQUEINDEX]" method="post" action="/quickorder">
		 *		<input type="hidden" name="event" value="quickorder" />
		 *		<input type="hidden" name="qocode[UNIQUEINDEX]" title="Quick order" class="code" value="[CODE]"/>
		 * 		<input type="hidden" name="qoqty[UNIQUEINDEX]" class="qty" value="[QTY]"/>
		 *		<input name="qoorder" type="image" id="qoorder_<%= [UNIQUEINDEX] %>" tabindex="250" src="/<%= site %>/images/buttons/add-to-basket-btn.gif" alt="Add to basket" class="addtobtn"/>
		 *  </form>			
		 */
		
		var isSingle = (arguments.length > 1 && arguments[1]);
		var numbers = button_id.match(/\d+/g);
			
		if (!isSingle) {
    	if (numbers) // replace numbers
    		buttonId = button_id.replace(numbers, "");
    		
    	// build the button name from the form name and remove any numbers so can apply to all relevant buttons
			buttonId = button_id.substr(button_id.lastIndexOf("_"), button_id.length);
			buttonId = "qoorder" + buttonId;
    }
    //alert('buttonId: ' + buttonId);
		// check for button_id, if not exist then is a form potentially with other inputs... but named differently.
		// Example, quickorder_related0 passed, trigger button id for all _related0-n is qoorder_related0-n
		// If !isSingle then attempt to attach to qoorder + button_id e.g. qoorder_combos (0-n) 
		// where original button_id was quickorder_combos0 (1-n)
		
		var str = "";
		var multiple = new Array();
		var inputs = new Array();

		if (button_id != "multiple") {
		//alert($('form[id="' + button_id + '"]').length)
			
			// find the submit button(s)			
			if ($('form[id="' + button_id + '"]').length > 0) {
				var submitButton = null, imageTypeSubmit = null;
				// check within the form for an input
				inputs = $('form[id="' + button_id + '"]').find("input").filter(function() {
						if($(this).attr("type") == 'image') {
							return $(this);
						} else if ($(this).attr("type") == 'submit') { 
							return $(this);
						}
				});
			}
			
		} else if (button_id == "multiple") {
		// we are going to search the whole document and assign a click to each button with id following pattern "qoorder_[0-9]+"
			/*
			Grab multiple items that satisfy the rule id="qoorder_[0-9]+ and assign click to those as well
			*/
			multiple = $("input:[id]").filter(function() {
		 		var valid = (!isSingle) ? (this.id.match(/^qoorder_[0-9]+/) != null) : false; 
		  		
		 		// check for button_id + [0-9]+ and assign to each
		 		if (!isSingle && !valid) {
		 		  valid = (new RegExp("^" + buttonId + "[0-9]+","g").exec(this.id) != null);
		 		  str += "^" + buttonId + "[0-9]+\",\"g\"" + "\nthis.id: " + this.id;
		 		}
		 		return valid;
			});			
		}		
	
		// if setup for multiple that's all we're interested in	
		inputs = (multiple.length > 0) ? multiple : inputs;
		
		//alert('button_id: ' + button_id + 'inputs.length: ' + inputs.length);
		//alert("buttonId: " + buttonId + "\ninputs.length: " + inputs.length + "\nbutton_id: " + button_id + "\nmultiple.length: " + multiple.length );
		
	if (inputs.length > 0) {
		
		// reset binds to prevent multiple calls per query
		inputs.unbind();
		
		inputs.click(function(event) {

				event.preventDefault();
				// move the popup to where we can see it
				var adjStartY = $(window).scrollTop()+200;
				
				// get the id which will indicate the name or the form i.e quickorder_XX
				var id = this.id.substring(this.id.lastIndexOf("_")+1, this.id.length);
				
				//alert('the id: ' + id)
				
	 			if (id != null && id != "" ) {
				
					// Button name on shopping cart, form name is quickorder_cart but trigger btn is id="basketbtn"	
					if (id == "basketbtn") {
							if ($('#basketbtn').length > 0) id = "cart";
					} else if (id == "quickorder") {
							if ($('#basketbtn').length > 0) id = "quickorder";
					}					
					
					// Find the form this button is sitting inside.
					var children = $(this).parents('form:eq(0)').find(':input');
					
					// show adding to basket msg
					$('#qopopup_content').html('Adding items to your basket. Please Wait...');
					// add title
					$('#qopopuptitle').text("Quick Order Confirmation");
					$('#qopopup').css({top:adjStartY+'px'});
					
					if( !$('#qopopup').is(":visible")) {
						$('#qopopup').jqmShow();
					}
				 	
		 			var qs = "" ;
		 			var codes = new Array(), qtys = new Array();
		 			var mismatch = false; // used to validate code,qty pairs from textarea
				 	var valid = true;
				 	var stdValMsg = "Add one product per line: example:\n12345,1\n54321,3\n98765,2";
		 			
		 			//alert("$('#qof').is(':hidden'): " + $('#qof').is(':hidden') + " && $('#qoway1').is(':hidden'): " + $('#qoway1').is(':hidden'))
		 			
		 			var qoType = "single"; // values, single/multi
		 			
		 			// If showing the qof textarea then take values from that, code, qty, code, qty
		 			if (!$('#qof').is(':hidden') && $('#qoway1').is(':hidden')) {
		 				
		 				var values = $('#qof').val();
		 				
		 				qoType="multi";
		 				
		 		//alert('values original: \n\t' + values + '\nvalues.split("\t").join(",").split("\n").join(","): \n\t' + values.split("\t").join(",").split("\n").join(","))

						// strip invalid characters
						values = values.replace(/[^a-zA-Z 0-9\n\t\r,]+/g,'');
						
						// if stripped invalid characters, replace values in textarea with stripped version
						if (values != $('#qof').val())
							$('#qof').val(values);
						
		 				// make sure we're only dealing with , by replacing ,, , , \n \t \d
		 				try {
		 				// IE 6+ does not allow trim chaining, .split().join().trim().split so changed method
		 				
		 					values = values.replace(/\t+/g, ',');
		 					values = values.replace(/\n+/g, ',');
		 					
		 					values = values.replace(/,,+/g, '');

							values = values.replace(/\s/g, ',')
		 				
		 					// remove leading/trailing spaces, leading and ending commas
							if (values) values = values.replace(/^\s+/g, '').replace(/\s+$/g, '').replace(/,,/g, ',').replace(/, ,/g, ',').replace(/^,+/, '').replace(/,+$/g, '');
							
		 				} catch (err) {
		 					//alert('error: ' + err)
		 				}

						var entered = "";
						
						try {	

							mismatch = (values.split(",").length % 2 > 0);
							
			 				for (var i=0; i<values.split(",").length; i=i+2) {
			 					codes.push(values.split(",")[i]);
			 					if (!values.split(",")[i+1]) {
			 						valid = false;
			 						qtys.push("No Quantity Found.");
			 					} else
			 						qtys.push(values.split(",")[i+1]);
			 				}
			 				
			 				// validate quantity input
			 				for (var i=0; i<qtys.length; i++) {
			 					if (parseInt(qtys[i]) != qtys[i]) {
			 						qtys[i] = "Invalid Quantity: " + qtys[i] + ".";
			 						valid = false;
			 					}
			 				}
			 				
			 				var data = (codes.length > 0 || qtys.length > 0 );
			 				
			 				// add each code/qty pair to the querystring
			 				if ((!mismatch && valid) && codes.length > 0 && qtys.length > 0 && codes.length == qtys.length) {
			 					
			 					for (var i=0; i<codes.length; i++) {
			 						if (codes[i].trim() != "" && qtys[i].trim() != "")
			 							qs += "&qocode" + i  + "=" + codes[i] + "&qoqty" + i + "=" + qtys[i];
			 					}
			 				} else if (!valid || data) {
			 								 					
			 					entered += "\nProduct\tQuantity\n";
			 					
			 					var len = (codes.length >= qtys.length) ? codes.length : qtys.length;

			 					for (var i=0; i<len; i++) {
			 						if (codes[i]) entered += codes[i] + "\t"; else entered += "No Code Found\t";
			 						if (qtys[i]) entered += qtys[i] + "\n"; else entered += "No Quantity Found\n";
			 					}
			 					
			 					alert("One or more quantities could not be found.\n" + entered + "\nPlease check your entry and try again.\n\n" + stdValMsg);
			 					
			 					// hide the quickorder popup so the user doesn't have to close it on failed validation
			 					$('#qopopup').jqmHide();
			 					
			 				} else {
			 				
			 					alert("There was a problem adding your entered products.\n\nAdd one product per line: example: 12345,1,54321,3,98765,2.");
			 				}
			 				
		 				} catch(err) { }
		 			
		 				//alert("Codes(" + codes.length + ") qtys(" + qtys.length + ")")
		 			
		 			} // endif (!$('#qof').is(':hidden') && $('#qoway1').is(':hidden'))
		 			
		 			
		 			//alert("mismatch(" + mismatch + ") codes.length: (" + codes.length + ") qs: (" + qs + ") children.length("+ children.length +")");
		 			
		 			if(!mismatch && (codes.length > 0 && qs != "") || children.length > 0 ) { // loop through the fields and contruct the qs get the code and qty
		 			
		 				if (!$('#qof').is(':hidden') && $('#qoway1').is(':hidden')) {
		 				
							$('#qof').val("Add one product per line: example: 12345,1\n54321,3\n98765,2.");
							
		 				} else {
		 				
		 					//var str = "";
		 					
		 					// Comment: ...
		 					var doNotClearInputsAfterUse = $(this).parent(0).find('input[name="qodonotclearinputsafteruse"]').length > 0 || $('form[name="' + button_id + '"]').find('input[name="qodonotclearinputsafteruse"]').length > 0;
		 					//alert("doNotClearInputsAfterUse: " + doNotClearInputsAfterUse);

		 					// if no field override called 
		 					var itemSelected; // JB 01122011 Only add selected items to basket (or all if no selection available)
		 					var itemHeader; // JB 20122011 Replace code with header code if available
		 					children.each(function(item) {
				 				var name = $(this).attr('name') ;
								var val = $(this).val() ;
								
								var c1 = name.startsWith("selected") ;
								var c2 = name.startsWith("qoqty") ;
								var c3 = name.startsWith("qocode") ;
								var c4 = name.startsWith("qoheader") ;
								if ( !c1 && !c2 && !c3 && !c4 ) {
									itemSelected = true;
								} 
								else if ( name.startsWith("selected") ) {
									itemSelected = val;
								} 
								
								if( c4 && ( val == "true" || val == true ) ) {
									itemSelected = true;
								}
																
								str += "name: " + name + "\tvalue: " + val + "\n";
								str += "\tname.startsWith(\"qo\"): " + name.startsWith("qo");
								str += "\nsubstring 0,2: " + name.substring(0,2);
								if( name != "qof" && name.substring(0, 2) == "qo" && val != null && val != "" && (itemSelected == "true" || itemSelected == true)) {
									qs += "&" + name + "=" + val ;
									// for each found value, clear the fields so not left with old data
									// except when multiple or input within form set
									
									var skip = (name == "qoaddproduct" || name == "qodonotclearinputsafteruser");
									
									if (!doNotClearInputsAfterUse && !skip) {
											$(this).val(''); 
									}
								}
							}); 

							//alert(str)
						}
							
						//alert("calling ajax with qs(" +qs+")");
							
							// always add this - sets showSelection(false)
							qs += "&qoaddproduct=true";
							
							// add type here so we know which const to use for max lines
							qs += "&qoType=" + qoType;

							/* replaced with single fetch on field name
							 * if (button_id == "multiple") {

								if ($(this).parents('form:eq(0)').find('input[name="BV_SessionID"]').length > 0) {
									qs += "&BV_SessionID=" + $(this).parents('form:eq(0)').find('input[name="BV_SessionID"]').val();
									qs += "&BV_EngineID=" + $(this).parents('form:eq(0)').find('input[name="BV_EngineID"]').val();
								}
	
							// add session information if applic.
							} else if ($('form[name="' + button_id + '"]').find('input[name="BV_SessionID"]').length > 0) {
								// also validate there is a value
								qs += "&BV_SessionID=" + $('form[name="' + button_id + '"]').find('input[name="BV_SessionID"]').val();
								qs += "&BV_EngineID=" + $('form[name="' + button_id + '"]').find('input[name="BV_EngineID"]').val();
								//qs += "&ARCO_LOGIN_0=" + $('form[name="' + button_id + '"]').find('input[name="ARCO_LOGIN_0"]').val();	//SW26082011
							} */ 
								
							if ($('input[name="BV_SessionID"]').length > 0) {
								qs += "&BV_SessionID=" 	+ $('input[name="BV_SessionID"]').val();
								qs += "&BV_EngineID=" 	+ $('input[name="BV_EngineID"]').val();
								qs += "&ARCO_LOGIN_0=" + $('input[name="ARCO_LOGIN_0"]').val();
							}

							// add catid (single cat code)							
							if ($('form[name="sortnavform"]').find('input[name="catid"]').length > 0) {
								qs += "&catid=" + $('form[name="sortnavform"]').find('input[name="catid"]').val();
							}
							
							// add pcatid (cat group)
							if ($('form[name="sortnavform"]').find('input[name="pcatid"]').length > 0) {
								qs += "&pcatid=" + $('form[name="sortnavform"]').find('input[name="pcatid"]').val();
							}
							
			//alert("qs: " + qs + "\nbutton_id: " + button_id + "\n$(this).parents('form:eq(0)').find('input[name="BV_SessionID"]').length: " + $(this).parents('form:eq(0)').find('input[name="BV_SessionID"]').length);
							
							//alert("Calling POST with "+qs)
				 			$.ajax({
								type: "POST",
								url: "/ajax",
								data: "event=ajax&key=quickorder" + qs,
								success: function(data, status) 
								{
									var isOrderHistoryDetailsPage = ($('#qoorder_oh0').length > 0);

									// are we showing the confirmation page or the popup
									if (data != null && data.toLowerCase().match(/.*qochoose.*/) != null) { // popup

										$('#qopopup_content').html(data);
										
										// one scenario is successful addition of items amongst invalid items
										// displays this instead, does not update the items in cart message and also does not display the continue/view basket buttons (because thinks is a fail)
										
										// update items in cart
										var items = $('#successCount').val();
										var currentNrItems = $('a[name="dynItemsInCart"]').html().trim();
										currentNrItems = currentNrItems.substring(currentNrItems.indexOf("(")+1, currentNrItems.indexOf(")"));
										
										// set default on NaN
										if (parseInt(currentNrItems) != currentNrItems) currentNrItems = 0;

										var itemtext = 0 ;  // = "1 Item"
										if( items > 0 ) {
											itemtext = parseInt(currentNrItems) + parseInt(items) ; // items+ " Items"
											if ($('a[name="dynItemsInCart"]').length > 0) {
												$('a[name="dynItemsInCart"]').text("Shopping Basket (" + itemtext + ")");
											}
										} else {
											itemtext = currentNrItems;
											if ($('a[name="dynItemsInCart"]').length > 0) {
												$('a[name="dynItemsInCart"]').text("Shopping Basket (" + itemtext + ")");
											}
										}
										
		//alert('qochoose, orderTotal: ' + $('input[name="orderTotal"]').val());
										if ($('#dynBasketTotal').length > 0) {
											$('#dynBasketTotal').text($('input[name="orderTotal"]').val());
										}
										if (isOrderHistoryDetailsPage) { // send user back to order header
											$('#navContinueShopping').unbind().bind('click', function(e) {
												event.preventDefault();
												$('#qopopup').jqmHide();
												//history.go(-1);
												$('#backbtn').trigger('click'); // simulate back button
											});
										} else {
											// reset nav continue button
											$('#navContinueShopping').unbind().bind('click', function(e) {
												event.preventDefault();
												$('#qopopup').jqmHide();
												return false;
											});
										}
		
										var failureCount = parseInt($('#failureCount').val());
		
										// update the shopping cart if we are on the basket, 
										// unless failed to add 1 or more items, then display message and buttons, after that, update basket on close
										if ($('#updatebtn').length > 0) {
		
											//if ($('.message').length == 1) {											
												if (failureCount < 1) { // if no failure then refresh basket immediately
													$('#navContinueShopping, #navViewBasket').hide();
													$('#message').html('Updating your baskets view, please wait...');
													$(this).parents('form:eq(0)').submit();
												} else { 																										
													// assign above functionality to both buttons and close X
													$('#navContinueShopping, #navViewBasket').click(function(event) {
														event.preventDefault();
														$('#navContinueShopping, #navViewBasket').hide();
														$('#message').html('Updating your baskets view, please wait...');															
														$(this).parents('form:eq(0)').submit();
													});
												}
											//} 																								
										}
	
									} else if (data != null && data.toLowerCase().match(/.*qopopup.*/) != null) { // are we showing the confirmation page
																		
											// grab the number of items so we can update the left hand side
											var myregexp = /qopopup_cartitems" value="(.*)"/;
																					
											var match = myregexp.exec(data);
											var items = 1 ;
									
											if (match != null && match.length > 1) {
												items = match[1];
											}
											
											var currentNrItems = $('a[name="dynItemsInCart"]').html().trim();
											currentNrItems = currentNrItems.substring(currentNrItems.indexOf("(")+1, currentNrItems.indexOf(")"));
										
											// set default on NaN
											if (parseInt(currentNrItems) != currentNrItems) currentNrItems = 0;

											var itemtext = 1;  // = "1 Item"
											if( items > 0 ) {
												itemtext = parseInt(items); // items+ " Items"
											} else {
												if (currentNrItems > 0 && items == 1) itemtext = parseInt(currentNrItems) + parseInt(items);
											}
											
				//alert('qopopup, match: ' + match + '\ncurrentNrItems: ' + currentNrItems + '\nitems: ' + items + '\nitemtext: ' + itemtext);
				
							 				if (!$('#qof').is(':hidden') && $('#qoway1').is(':hidden')) {
					 							if (data.trim() != "No quantities could be found, please try adding your items again.") {
					 								$('#qof').val(stdValMsg);
					 							}
		 									}
											
											if ($('a[name="dynItemsInCart"]').length > 0) {
												$('a[name="dynItemsInCart"]').text("Shopping Basket (" + itemtext + ")");
											}
											
											$('#qopopup_content').html(data);
											
							//alert('qochoose, orderTotal: ' + $('input[name="orderTotal"]').val());
											if ($('#dynBasketTotal').length > 0) {
												$('#dynBasketTotal').text($('input[name="orderTotal"]').val());
											}
											
											// bind the click event so we can manually trigger it
											if (isOrderHistoryDetailsPage) {
												if ($('#backbtn').length > 0) {
													$('#backbtn').bind('click', function(e) {
														history.go(-1);
													});
												}
											}

											// Close the qopopup when clicking Continue Shopping Button											
											if ($('#navContinueShopping').length > 0) {
												$('#navContinueShopping').click(function(event) {
													event.preventDefault();
													if (isOrderHistoryDetailsPage) {
														$('#backbtn').trigger('click');
													}
								 					$('#qopopup').jqmHide();						 					
												});
											}
											
											var failureCount = parseInt($('#failureCount').val());
											
											// update the shopping cart if we are on the basket, 
											// unless failed to add 1 or more items, then display message and buttons, after that, update basket on close
											if ($('#updatebtn').length > 0) {
												if (failureCount < 1) { // if no failure then refresh basket immediately
													$('#navContinueShopping, #navViewBasket').hide();
													$('#message').html('Updating your baskets view, please wait...');
													$('#navViewBasket').parents('form:eq(0)').submit();
												} else { 
													$('#navContinueShopping, #navViewBasket').unbind('click');
													// assign above functionality to both buttons and close X
													$('#navContinueShopping, #navViewBasket').click(function(event) {
														event.preventDefault();
														$('#navContinueShopping, #navViewBasket').hide();
														$('#message').html('Updating your baskets view, please wait...');															
														$(this).parents('form:eq(0)').submit();
														$('#qopopup').jqmShow();
													});
												}
																								
											} else {
												// if we wanted to hide the window after a period of time we would do this here.
											}

								 			
									} else {
									
										// data can come back in the following:
										// {message:XXX} - display the message to the user
										
										var result = ($.browser.msie) ? $.parseJSON(data) : JSON.parse(data);
										if( result.message != null ) {
											$('#qopopup_content').html(result.message);
											
											//$('#qopopup').jqmShow();
										}
										
									}
								}
				 			}) ;
						}
				}
			  
				return false;
			});
		}
}

/* MJB - moved from cart/quickorder.js */
function validateQuickOrder(theForm){
	
	var oneValidEntry = false;
	
	for(var i = 0; i < 10; i++){
		var atLeastOneCode = false;
		var atLeastOneQty = false;
		var code = document.getElementById('qocode'+i);
		var qty = document.getElementById('qoqty'+i);;
		if(!code || (code.value == "" && qty.value == ""))
			continue;
			
		if(removeLeadingWhiteSpace(code.value) == ""){
			alert("Please enter a product code");
			code.select();
			code.focus();
			return false;
		}
		else
			atLeastOneCode = true;
		
		if(qty.value == "" || parseFloat(qty.value) % 1 != 0 || parseFloat(qty.value) < 1){
			alert("Please enter a whole number into this quantity field");
			qty.select();
			qty.focus();
			return false;
		}
		else
			atLeastOneQty = true;
			
		oneValidEntry = atLeastOneCode && atLeastOneQty;
	}
	
	return oneValidEntry;
}

function addQoLine(maxLines){
	
	if(!document.getElementById('qodiv'))
		return;
	
	var qoway1 = document.getElementById('qodiv');
	
	var len = qoway1.getElementsByTagName("label").length / 2;
	if(len >= (maxLines)){
		alert("The maximum number of items your can quick order at once is " + maxLines + ".\nPlease use the quick order function again if you require more.");
		return;	
	}
	
	var labelQ = document.createElement("label");
	var labelC = document.createElement("label");
	var code = document.createElement("input");
	var qty = document.createElement("input");
	
	labelC.innerHTML = "Code";
	labelC.className = "nolabel";
	labelC.htmlFor = "qocode" + (len + 1);
	
	labelQ.innerHTML = "Qty";
	labelQ.className = "nolabel";
	labelQ.htmlFor = "qoqty" + (len + 1);
	
	code.type = "text";
	code.name = "qocode" + (len + 1);
	code.className = "code";
	code.id = "qocode" + (len + 1);
	code.tabIndex = "206";
	
	qty.type = "text";
	qty.name = "qoqty" + (len + 1);
	qty.className = "qty";
	qty.id = "qoqty" + (len + 1);
	qty.tabIndex = "206";
	
	qoway1.appendChild(labelC);
	qoway1.appendChild(code);
	qoway1.appendChild(labelQ);
	qoway1.appendChild(qty);
						
	//drawPlusMinus();
}

function removeQoLine(){
	var qoway1 = document.getElementById('qodiv');
	var labels = qoway1.getElementsByTagName("label");
	var inputs = qoway1.getElementsByTagName("input");
	
	if(labels.length <= 4)
		return;
		
	var chillun = qoway1.childNodes;
	var removeCount = 0;
	for(var i = chillun.length; i > 0; i--){
		//alert(chillun[i-1].tagName);
		if(chillun[i-1] && chillun[i-1].tagName){
			if(chillun[i-1].tagName.toLowerCase() == "input" || chillun[i-1].tagName.toLowerCase() == "label"){
				qoway1.removeChild(chillun[i-1]);
				removeCount++;
			}
		}
		
		if(removeCount == 4)
			break;
	}
	
	//drawPlusMinus();
}
//-->
