<!--// 
String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}

/** 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>			
		 */

		// hack to make close button work on Xtreme styling changes
		//$('#closepopup').click(function(event) {
			//$('#qopopup').jqmHide();
		//});
		
		var isSingle = (arguments.length > 1 && arguments[1]);
		var numbers = button_id.match(/\d+/g);
			
		//alert('isSingle (exp f): ' + isSingle);
		
		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 = 0;
		
		var 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;
		});
		
	var inputs = (multiple.length > 0) ? multiple : $('input[id="'+button_id+'"]') ;
	
	//alert("inputs.length: " + inputs.length);
	
	if (inputs.length > 0) {		
		
		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";
					}
					var children = $('form[id="quickorder_' + id + '"]').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'))
		 			
		 			// 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();
		 				
		 		//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);
						
						//alert("minus special chars\n" + values)
		 				// make sure we're only dealing with , by replacing ,, , , \n \t \d
		 				values = values.split("\t").join(",").trim().split("\n").join(",").trim().split(",,").join(",").trim().split(", ,").join(",").trim().split(" ").join("").trim();
		 				
		 				if (values.lastIndexOf(",") == values.length) values = values.substring(0, values.length-1); // remove last comma if exists
		 				//alert(values)
		 				//alert("values.lastIndexOf(\",\"): " + values.lastIndexOf(",") + " - values.length-1: " + values.length-1 + "\n\nremoved last .?\n" + values)
						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'))
		 			
		 			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,54321,3,98765,2");
							
		 				} else {
		 				
				 			children.each(function(item) {
				 				var name = $(this).attr('name') ;
								var val = $(this).val() ;
								if( name != "qof" && name.startsWith("qo") && val != null && val != "") {
									qs += "&" + name + "=" + val ;
									// for each found value, clear the fields so not left with old data
									// except when multiple
									if (multiple.length == 0)
										$(this).val(''); 
								}
							}); 
							
							//alert("qs: " + qs)
						}
							
							alert("calling ajax with qs(" +qs+")");
							 
				 			$.ajax({
								type: "POST",
								url: "/ajax",
								data: "event=ajax&key=quickorder" + qs,
								success: function(data, status) 
								{

									// are we showing the confirmation page or the popup
									if (data != null && data.toLowerCase().match(/.*qochoose.*/) != null) {
										$('#qopopup_content').html(data);
										//IXH Dont know why we need to call show here??
										//$('#qopopup').jqmShow(); MJB before modal.js was fixed with highslide the jqm functionality didn't work properly...
								 		
									} else if (data != null && data.toLowerCase().match(/.*qopopup.*/) != null) { // are we showing the confirmation page or the popup
											// 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 = 0 ;
											if (match != null && match.length > 1) {
												items = match[1];
											}
											
											var itemtext = "1 Item" ; 
											if( items > 1 ) {
												itemtext = items+ "  Items" ; 
											}
											
							 				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"]')) {
												$('a[name="dynItemsInCart"]').text(itemtext);
											}
											
											$('#qopopup_content').html(data);
											
											// update the shopping cart if we are on the basket
											
											if ($('#updatebtn').length > 0) {
												if ($('.message').length == 1) {
														$('#navContinueShopping, #navViewBasket').hide();
														$('.message').html('Updating your baskets view, please wait...');
																
												}
												
												$('#navViewBasket').click();
												
											} else {
												// if we wanted to hide the window after a period of time we would do this here.
											}

											//$('#qopopup').jqmShow();
								 			
									} else {
									
										// data can come back in the following:
										// {message:XXX} - display the message to the user
										
										//alert(data) ;
										
										var result = ($.browser.msie) ? $.parseJSON(data) : JSON.parse(data);
										
										if( result.message != null ) {
											$('#qopopup_content').html(result.message);
											
											//$('#qopopup').jqmShow();
										}
									}
								}
				 			}) ;
						}
				}
			  
				return false;
			});
		}
}
//-->
