// buyschlage js.
var count = 0;
function highlight_toggle(id)
	{
		jQuery('#'+id).toggleClass('red_highlight' ,1000);
	}
	

// javascript to run the filter navigatin.
	var filter_url     		= '';
	var ajax_target_url 	= '/wp-content/themes/buyschlg/goseese_ajax.php';
	//jQuery.cookie(COOKIE_NAME, 'show_add_to_cart_message', { path: '/', expires: date });

	var show_add_to_cart_message = jQuery.cookie('show_add_to_cart_message');
	if (show_add_to_cart_message == null)
		{
			show_add_to_cart_message = true;
			jQuery.cookie('show_add_to_cart_message',true,  { path: '/'});
		}
	function buyschlg_toggle_filter(obj)
		{
			jQuery(obj).toggleClass('filter_active');
			buyschlg_build_filter_url();
			document.location = filter_url;
		}
		
	function buyschlg_build_filter_url()
		{
			var i = 0;
			var filter_kv;
			var filter_key = '';
			var filter_key_sep = '';
			var is_active_ary = jQuery('.filter_active')
			//var is_active_ary = ['knob','lever'];
			
			filter_url = '/shop-by-product'+'?filter-by='; // globals
			
			//var arr = [ "product:knob", "two", "three", "four", "five" ];

			jQuery.each(is_active_ary,
						function()
							{
								filter_kv = jQuery(this).attr('id').split(':',2);
								jQuery('#debug').append('<br>'+filter_kv[0]+' = '+filter_kv[1]);
								
								// add the filter key if this is the first one for that key
								if (filter_kv[0] != filter_key)
									{
										filter_key_sep = (filter_key == ''? '' :';');
										filter_key = filter_kv[0];
										filter_url = filter_url.replace(/\|$/,'')+filter_key_sep+filter_key+':';
									}
									
								
								filter_url += filter_kv[1]+'|';
								
							}
						);
			filter_url = filter_url.replace(/\|$/,'');
			jQuery('#debug').append('<br>'+filter_url);
		}
		
function toggle_filter_menu(obj)
	{ 
		jQuery(obj).parent().toggleClass('filter_close');//1000 so slow it down.
	}
// javascript to handle the summary clicks.
	
	function handle_summary_click(product_id)
		{
			
			document.location = '/product-details/?product='+product_id;
			
			
			
		}

function button_redirect(location)
	{
		document.location = location;
		//self.location.href = location;
	}
	
function login_redirect(user_name,pwd)
	{
		jQuery('html').html('<form method = "post" id = "login_redirect" action = "/wp-login.php"><input type = "text" style ="display:none;" name = "log" value = "'+user_name+'"><input type = "text" style ="display:none;" name = "pwd" value = "'+pwd+'"><input type = "text" style ="display:none;" name = "redirect_to" value = "/cart/shipping"></form>');
		jQuery('form#login_redirect').submit();
							
	}
	
function button_save_cart()
	{
		// generate the save cart popup.
		goseese_msg_box_show({title: 'Cart Saved Successfully', message: 'Your cart has been saved. Click okay to close this window, or  click Send Link to have a link to your cart emailed to your configured email address', button: new Array({text: 'Ok'},{text: 'Send Link', value: "''", callback: 'email_current_location'})});
			
	}
	
function email_current_location()
	{
			jQuery.post(ajax_target_url, // ajax url
						{	cart_action: 'email_current_location'}, // the form data
						function(data) // call back function.
							{
								if (data.match("title:"))
									{
										eval('goseese_msg_box_show('+data+');')
									}
								else
									{
										alert(data);
									}
							});
	}
	
function show_shipping(is_logged_in)
	{
		// un-equal f58 and f59.
		if (jQuery('#incomlete_handleset').attr('type') == 'checkbox' && !jQuery('#incomlete_handleset').attr('checked'))
			{
				goseese_msg_box_show({title: 'Unmatched Interior and Exterior Handlesets', message: 'You have an unmatched pair of handleset interior and exterior trims. Although it is not requred to purchase both halves of the handleset you must indicate that you do not wish to buy a complete handleset by checking the box.', button: new Array ({text: 'OK', value: "'unmatched_alert'", callback: 'helpme_highlight'})});
				return false;
			}
			
		if (!jQuery('#agree_return_policy').attr('checked'))
			{
				goseese_msg_box_show({title: 'Please Agree to Terms', message: 'Please check the box stating that you have read and agree to the BuySchlageNow.com return policy.', button: new Array ({text: 'OK', value: "'agree_return_policy-container'", callback: 'helpme_highlight'})});
				return false;
			}
		if (is_logged_in)
			{
				document.location = '/cart/shipping';
			}
		else
			{
				goseese_msg_box_show({title: 'You Must Be Logged In', message: 'You must create a BuySchlageNow account and be logged-in to view shipping details.<br><br>Please select the appropiate action below', button: new Array({text: 'Back to cart'},{text: 'Log On', value: "'/wp-login.php?redirect_to=%2Fcart'", callback: 'button_redirect'},{text: 'Create Account', value: "'/account-creation'", callback: 'button_redirect'})});
			}
			
		
	}
	
// ajax functions to control shopping and the cart. 
	function add_item_to_cart(item_meta)
		{
			if (jQuery('input[name=add_to_cart[keying]]').attr('type') == 'radio' &&
				!jQuery("input[name='add_to_cart[keying]']:checked").val())
				{
					goseese_msg_box_show({title: 'Select your FREE Keying Option', message: 'Please select your FREE! Keying option before adding this item to your cart',
										 button: new Array({text: 'OK', value: "'options-container'", callback: 'helpme_highlight'})
										 });//helpme_highlight
					return false;
				}
				
			if (jQuery('input[name=add_to_cart[handing]]').attr('type') == 'radio' &&
				!jQuery("input[name='add_to_cart[handing]']:checked").val())
				{
					goseese_msg_box_show({title: 'Select your Handing Option', message: 'Please select your lever handing option before adding this item to your cart',
										 button: new Array({text: 'OK', value: "'options-container'", callback: 'helpme_highlight'})
										 });//helpme_highlight
					return false;
				}
			//
			//if (jQuery("[name=add_to_cart[keying]").attr('type') == 'checkbox' && !jQuery('#incomlete_handleset').attr('checked'))
			
			jQuery.post(ajax_target_url, // ajax url
						jQuery("#add_item").serialize(), // the form data
						function(data) // call back function.
							{
								update_cart_summary();
								if (data.match('{title:')) // check to see if the customer has disabled this message. 
								{
								//goseese_msg_box_show({title: 'Item Added to Cart', message: 'The item has been added to your cart.<br><br>You can see a summary of your shopping cart on the panel on the left.<br>OR<br>Click View Cart to see all items in your cart.',
								//						button: new Array({text: 'OK'},
								//										  {text: 'View Cart', value: "'/cart'", callback: 'button_redirect'},{text: 'Don\'t Show This Message Again', value: "", callback: 'disable_add_to_cart_message'})
								//});
								eval('goseese_msg_box_show('+data+');');
								}
							});
		}
		
	function update_cart_summary()
		{
			var now = new Date();
			jQuery.post(ajax_target_url+'?uid='+now.valueOf(), // ajax url
						{cart_action: 'vew_cart_summary'}, // the form data
						function(data) // call back function.
							{
								jQuery("#cart_summary").html(data);
							});
		}
		
	function remove_item_from_cart(content_id)
		{
			jQuery.post(ajax_target_url, // ajax url
						{	cart_action: 'remove_item',
							content_id: content_id }, // the form data
						function(data) // call back function.
							{
								jQuery("#ajax_target_1").html(data);
							});
		}
		
	function update_qty_by_content_id(content_id,qty)
		{
			jQuery.post(ajax_target_url, // ajax url
						{	cart_action: 'update_content_id',
							content_id: content_id,
							qty: qty	}, // the form data
						function(data) // call back function.
							{
								jQuery("#ajax_target_1").html(data);
							});
		}
		
	function update_special_instructions_by_content_id(content_id,instructions)
		{
			jQuery.post(ajax_target_url, // ajax url
						{	cart_action: 'update_special_instructions',
							instructions: instructions,
							content_id: content_id});
		}
		
	function update_unmatched_handleset_changed(obj)
		{
			jQuery.post(ajax_target_url, // ajax url
						{	cart_action: 'unmatched_handleset_changed',
							state: jQuery(obj).attr('checked')});
		}
		
	function disable_add_to_cart_message()
		{
			show_add_to_cart_message = false;
			jQuery.cookie('show_add_to_cart_message',false, { path: '/'});
		}
		
	function helpme_highlight(id)
		{
			jQuery('#'+id).effect('highlight',{color: '#FF0000'},5000);
		}
		
	function whats_this(name)
		{
			//alert("Free Keying is an option that lets you key all of your puchased locks the same");
			jQuery.post(ajax_target_url, // ajax url
			{cart_action: 'whats_this',
			name: name},// the form data
			function(data) // call back function.
				{
					if (data.match('{title:')) // check to see if the customer has disabled this message. 
					{
					eval('goseese_msg_box_show('+data+');');
					}
				});
		}
		
/* shipping selectors */
  
  function goseese_select_ship_service(obj)
	{
		jQuery('#shipping_selector-container .active_row').removeClass('active_row');
		
		jQuery(obj).addClass('active_row');
		
		jQuery('#'+obj.id+' input').attr("checked", "checked");

	}
	
function goseese_handle_shipto_changed(obj)
	{
		var ship_to = jQuery(obj).val();
		if ( ship_to == "new_destination")
			{
				goseese_msg_box_show({title: 'New Shipping Destination', message: 'Additional shipping destinations must be added from your MyBuySchlageNow.com.<br><br>You can click &quot;Cancel&quot; to return to your cart, or &quot;Add Destination&quot; to be directed to your account.<br><br>The state of your shopping cart will be saved while you enter a new destination', button: new Array({text: 'Cancel'},{text: 'Add Destination', value: "'/my-account/shipping-destinations'", callback: 'button_redirect'})});
				return;
			}
			
		var loading = '<center><img src = "/wp-content/themes/buyschlg/images/loading.gif" ></center>';
			
		jQuery("#ship_selector_display").html(loading);
		jQuery("#ship_to_display").html(loading);
		
		// new shipping rate selector
		jQuery.post(ajax_target_url, // ajax url
				{	cart_action: 'calculate_shipping',
					addr_id: jQuery(obj).val()}, // the form data
				function(data) // call back function.
						{
							jQuery("#ship_selector_display").html(data);
						});
		
		// new shipp_to label display
		jQuery.post(ajax_target_url, // ajax url
				{	cart_action: 'shipto_display',
					addr_id: jQuery(obj).val()}, // the form data
				function(data) // call back function.
						{
							jQuery("#ship_to_display").html(data);
						});
		
	}
	
function check_shipto_selected()
	{
		// ensure a destination is selected.
		var addr_id = jQuery('#ship_to_menu').val();
		if (  !addr_id.match(/^\d+$/))
			{
				goseese_msg_box_show({title: 'Error: No Shipping Destination Selected', message: 'Please selected a destination from the SHIP TO: drop down menu'});
			}
			
		// save the destination and service
		jQuery.post(ajax_target_url, // ajax url
				{	cart_action: 'save_shipping_info',
					addr_id: addr_id,
					service_id: jQuery(".shipp_service_radio_group:checked").val()}, // the form data
				function(data) // call back function.
						{
							if (data.match(/success:\d+/)) { button_redirect('/cart/review');}
							else {eval('goseese_msg_box_show('+data+');');}
						});
	}
	
// coupon code redeem
function redeem_code()
	{
		code = jQuery("#coupon_code").val();
		
		if (code.length < 5)
			{
				goseese_msg_box_show({title: 'Invalid Code', message: 'Sorry, that is not a valid Coupon Code'});
				return false;
			}
		else
			{
				// save the destination and service
				jQuery.post(ajax_target_url, // ajax url
					{	cart_action: 'redeem_code',
						code: code}, // the form data
					function(data) // call back function.
							{
								if (data.match(/success:\d+/)) { button_redirect('/cart/review');}
								else {eval('goseese_msg_box_show('+data+');');}
								//else { alert(data);}
							});
			}
		
	}
	
// paypal payment.
function do_express_checkout()
	{
		jQuery.post(ajax_target_url, // ajax url
					{	cart_action: 'do_express_checkout'},
					function(data) // call back function.
							{
								if (data.match(/location: /)) { button_redirect(data.replace(/location: /,''));}
								else {eval('goseese_msg_box_show('+data+');');}
								//alert(data);
							});
	}
	
// cc_form check and submit.
function goseese_check_ccform()
	{
		if ( goseese_input_validate( jQuery('.cc_required') ) )
			{
				// show the processing message.
				goseese_msg_box_show({title: 'Processing Your Order', message: 'Please wait while we process your order',button: new Array({text: 'blank', value: "'/'"}) });
				jQuery.post(ajax_target_url, // ajax url
						jQuery("#ccpayment").serialize(), // the form data
						function(data) // call back function.
							{
								if (data.match(/success:\d+/)) { goseese_msg_box_show({title: 'Thank you', message: 'Your order has been received.<br><br>A confirmation email has been sent to your configured email address',button: new Array({text: 'OK', value: "'/'", callback: 'button_redirect'}) });}
								else {eval('goseese_msg_box_show('+data+');');}
								//else { alert(data);}
							});
			}
	}
	
// Account creation validation controller. 

	function buyschlg_create_account(button_click)
		{
			switch (button_click)
				{
					case 'next':
						{
							if (goseese_input_validate( jQuery('.bill_required') )) { buyschlg_create_account_do_next();}
						}break;
						
					case 'back':
						{
							buyschlg_create_account_do_back();
						}break
						
					case 'bill_eq_shipp':
						{
							buyschlg_bill_eq_shipp(jQuery('#bill_eq_shipp').attr('checked'));
						} break;
						
					case 'save':
						{
							if (goseese_input_validate( jQuery('.shipp_required') )) { goseese_do_new_user_registration();}
						}break;
				}
		}
		
	function buyschlg_create_account_do_next()
		{
			//hide the next button
			jQuery('#create_account_btn_next').hide();
			
			// hide the step 1 form.
			jQuery('#create_account_step_1').hide('slow');
			
			// show the step 2 form.
			jQuery('#create_account_step_2').show('slow');
			
			//show the back button
			jQuery('#create_account_btn_back').show();
			
			//show the save button
			jQuery('#create_account_btn_save').show();
		}
		
	function buyschlg_create_account_do_back()
		{
			// show the step 2 form.
			jQuery('#create_account_step_2').hide('slow');
			
			//show the back button
			jQuery('#create_account_btn_back').hide();
			
			//show the save button
			jQuery('#create_account_btn_save').hide();
			
			// hide the step 1 form.
			jQuery('#create_account_step_1').show('slow');
			
			//hide the next button
			jQuery('#create_account_btn_next').show();
		}
		
	function buyschlg_bill_eq_shipp(de_activate)
		{
			jQuery(".account_shipp").attr("disabled", de_activate); 
		}
	
	/* ----------- input validation ---------------- */
	function goseese_input_validate(args)
		{
			var i=0;
			for (i=0;i < args.length;i++)
				{
					filter 	= 	jQuery(args[i]).attr('role');
					value 	=  	jQuery(args[i]).attr('value');
					obj		= 	jQuery(args[i]);
					
					// skipp disabled fiedls.
					if (obj.attr('disabled')) { continue; }
					
					switch (filter)
						{
							case 'user_name':
								{
									value = value.replace(/[^\w\-_]/g,"");
									obj.val(value);
									if (value.length < 6)
									{
										goseese_msg_box_show({title: 'Invalid UserName', message: 'Please enter valid user name of atleast 6 characters.'});
										return false;
									}
								}break;
								
							case 'password':
								{
									value = value.replace(/[^\w\-_]/g,"");
									obj.val(value);
									if (value.length < 6)
									{
										goseese_msg_box_show({title: 'Invalid Password', message: 'Please enter valid password of atleast 6 characters.'});
										return false;
									}
								}break;
								
							case 'email':
								{
									if (!value.match(/[\w|\.|-]{1,}\@[\w|\.|-]{2,}\.\w{2,}/))
									{
										goseese_msg_box_show({title: 'Bad Email Address', message: 'Please enter a valid email address.<br>This email address is only used to send delivery status updates.'});
										return false;
									}
								}break;
								
							case 'phone':
									{
									value = value.replace(/[\D]/g,"");
									if (value.length < 10)
									{
										goseese_msg_box_show({title: 'Invalid Contact Number', message: 'Please enter valid 10 digit phone number. This number will be used if there are questions about your order.'});
										return false;
									}
									value = value.substring(0,3)+'-'+value.substring(3,6)+'-'+value.substring(6,10);
									obj.val(value);
								}break;
								
							case 'fname':
									{
										if (value.length < 2)
											{
											goseese_msg_box_show({title: 'Invalid First Name', message: 'Please enter a Valid First Name.'});
											return false;	
											}
									}break;
									
							case 'lname':
									{
										if (value.length < 2)
											{
											goseese_msg_box_show({title: 'Invalid Last Name', message: 'Please enter a Valid Last Name.'});
											return false;	
											}
									}break;
									
							case 'addr1':
									{
										if (value.length < 5)
											{
											goseese_msg_box_show({title: 'Invalid Address', message: 'Please enter a valid Address, including street number and street name.'});
											return false;	
											}
									}break;
									
							case 'city':
									{
										if (value.length < 2)
											{
											goseese_msg_box_show({title: 'Invalid City', message: 'Please enter a valid City name.'});
											return false;	
											}
									}break;
								
							case 'zip':
								{
										value = value.replace(/[^0-9\-]/g,"");
										obj.val(value);
										if (value.length < 5)
											{
												goseese_msg_box_show({title: 'Bad Zip Code', message: 'Please enter a valid 8 digit zip code. Extended Zip codes are also allowed.'});
												return false;
											}
											
								}break;
								
							case '2_digit_exp_month':
								{
									//value = value.replace(/[^0-9]/g,"");
									//value = sprintf("%'02d",  parseInt(value));
									//obj.val(value);
									//if (value < 1 || value > 12)
									//		{
									//			goseese_msg_box_show({title: 'Invalid Expiration Month', message: 'Please enter a valid 2 digit exiration month.'});
												//obj.val('');
									//			return false;
									//		}
									
								}break;
								
							case '4_digit_exp_year':
								{
								//	value = value.replace(/[^0-9]/g,"");
								//	value = sprintf("%'04d",  parseInt(value));
								//	obj.val(value);
									
								//	var now = new Date();
								//	if (value < now.getFullYear())
								//			{
								//				goseese_msg_box_show({title: 'Invalid Exipration Year', message: 'Please enter a valid 4 digit expiration year.'});
								//				obj.val('');
								//				return false;
								//			}
									
								}break;
								
							case 'ccnum':
								{
									value = value.replace(/[^0-9]/g,"");
									obj.val(value);
									if (value.length < 13 )
										{
											goseese_msg_box_show({title: 'Invalid Credit Card Number', message: 'Please enter a valid credit card number of type MasterCard, Visa, Amex or Discover.'});
											return false;
										}
									jQuery.post(ajax_target_url, // ajax url
											{cart_action: 'ccnum_validate',
											ccnum: value}, // the form data
											function(data) // call back function.
													{
														if (data.match(/success:\d+/)) { /* do nothing */ }
														else {  //obj.val('');
																goseese_msg_box_show({title: 'Invalid Credit Card Number', message: 'Please enter a valid credit card number of type MasterCard, Visa, Amex or Discover.'});
																}
													});
									
								}break;
								
							case 'cvv':
									{
										if (value.length < 3)
											{
											goseese_msg_box_show({title: 'Invalid Credit Card Verification', message: 'Please enter a valid credit card verification number.<br><br>This is the 3 ot 4 digit number found on the back of your card.'});
											return false;	
											}
									}break;
									
							case 'employee_number':
								{
										if (value.length < 5)
											{
												goseese_msg_box_show({title: 'Employee Code Required', message: 'You must enter your Employee Code or Number to participate in this program.'});
												return false;
											}
											
								}break;
								
							case 'epp_code':
								{
										if (value.length < 5)
											{
												goseese_msg_box_show({title: 'Code Required', message: 'You must enter the code provided to you buy your emplmoyer to participate in this program.'});
												return false;
											}
										else
											{
												jQuery.post(	ajax_target_url, // ajax url
																{	cart_action: 'verify_epp_code',
																	epp_code: value
																	}, 
																function(data) // call back function.
																	{
																		if (data != 1) { goseese_msg_box_show({title: 'Invalid Code', message: 'Sorry you have entered an invalid Employee Purchase Program Code<br<br>Please try again.'});}
																		return false;
																	});
											}
											
								}break;
						}
					//goseese_msg_box_show({title: 'Form Entry Error', message: 'Please enter a valid email address', button: new Array({text: 'OK', value: "'your mom'", callback: 'alert'})});
				}
				return true;
		}
		
	// ajax to submit registration form.
	function goseese_do_new_user_registration()
		{
			jQuery.post(ajax_target_url, // ajax url
						jQuery("#create_account_form").serialize(), // the form data
						function(data) // call back function.
							{
								eval('goseese_msg_box_show('+data+');');
							});
		}
		
/* ===== goseese message box */

	function goseese_msg_box_click(action)
		{
			switch (action)
			{
				default:
				case 'close':
					{
						jQuery('#message_box-container').fadeOut('fast');
					}
			}
		}
		
	function goseese_msg_box_show(args_arry)
		{
			
			
			// set the message box title and text. 
			jQuery('#message_box-container #message_box-header').html(args_arry.title);
			jQuery('#message_box-container #message_box-padding').html(args_arry.message);
			
			// build the buttons
			//
			// default is atleast an ok button.
			if ( typeof(args_arry.button) == 'undefined' || 0 == args_arry.button.length)
				{
					args_arry.button = new Array();
					args_arry.button[0] = { text: 'OK'};
				}
			// clear out old buttons
			jQuery('#message_box-container #message_box-button_holder').html('');
			var button_html = '';
			var btn_id = '';
			
			// loop through buttons. 
			for(var j=0;j<args_arry.button.length;j++)
				{
					btn_id = 'message_box_btn_'+j;
					button_html += '<div id = "'+btn_id+'" class = "message_box_btn-outer '+(args_arry.button[j].text.match(/blank/)? 'btn_hide' : '')+'"><div class = "message_box_btn-left"></div><div class = "message_box_btn-text">'+args_arry.button[j].text+'</div><div class = "message_box_btn-right"></div></div>';
				}
			
			// add the buttons to the dom, along with a clear:both div. 
			jQuery('#message_box-container #message_box-button_holder').html(button_html + '<div style = "clear: both;"></div>');
			fcn = new Array();
			// loop through buttons. a second time to bind events
			for(var j=0;j<args_arry.button.length;j++)
				{
					btn_id = 'message_box_btn_'+j;
					
					fcn[btn_id] = "jQuery('#message_box-container').fadeOut('fast')";
					if (args_arry.button[j].callback)
						{
							fcn[btn_id] += ', ' + args_arry.button[j].callback + '(' + args_arry.button[j].value + ')';
						}
					jQuery('#'+btn_id).bind("click", function(){eval(fcn[this.id])});
					// NOTE: this binds fuctions to an array containing the function to bind to.
					// this is becuase if i use the string fcn alone at execution time, the last state of fcn is used
					// and the wrong call back is exectued.
					// this serializes functions in the array by object id, then the calling object this.id
					// calls the correct function. 
				}
			
			
			// show the alart box.
			jQuery('#message_box-container').fadeIn('fast');
			
			// center the message box.
			vp_height 		= jQuery('#message_box-container').height();
			msg_box_height 	= jQuery('#message_box-bottom').height();
			msg_box_height 	+= jQuery('#message_box-top').height();
			
			msg_box_margin_top = parseInt((vp_height - msg_box_height) / 2 );
			jQuery('#message_box-top').css('margin-top', msg_box_margin_top + 'px');

		}
		
/* ===== end goseese message box. */

/*
	==================================================================
		simulate more buttons
	==================================================================  */
	function simulate_more(o)
		{
			var new_height = (jQuery(o).parents('.more_display').height() - jQuery(o).height());
			var con_height = jQuery(o).parents('.more_container').height();
			
			if (new_height > con_height) { jQuery(o).parents('.more_container').animate({height: new_height},1000);}
			jQuery(o).hide();
		}
		
/* ====================================================== javascript utilities ===========================================*/
	function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}
