function updateURL(textbox, url_field_id, category_id_field, force)
{
    var url_field = document.getElementById(url_field_id);

    if(url_field.value == "index")
    {
    	return;
    }

    //remove all non-alphanumeric (plus dash and underscore) characters
    //then replace all double-dashes with a single dash
    //then remove any leading or trailing dashes
    var url_field_text = textbox.value.replace(/[^A-Za-z0-9\-_]/g, "-").replace(/-{2,10}/g, "-").replace(/(^-|-$)/g, "").toLowerCase();

    if(category_id_field)
    {
    	cat_url = jQuery("#" + category_id_field + " option:selected").text().replace(/[^A-Za-z0-9\-_]/g, "-").replace(/-{2,10}/g, "-").replace(/(^-|-$)/g, "").toLowerCase();

    	if(cat_url && cat_url != "none")
    	{
    		url_field_text = cat_url + "/" + url_field_text;
    	}
    }

    if(!force && url_field.value != "" && url_field.value != url_field_text)
    {
    	nerivon_confirm("Update URL?", "<p>The change you've made changes the suggested URL for this page.</p><br><br><p><b>Current URL:</b> " + url_field.value + "<br><b>Suggested URL:</b> " + url_field_text + "</p><br><br><p>Would you like to use the suggested URL for this page?</p>", "info", true, function(isConfirm)
        {
        	if(isConfirm)
        	{
        		url_field.value = url_field_text;
    			try
    			{
    				url_field.onkeyup();
    			}
    			catch(e){}
        	}
        });
    }
    else
    {
		url_field.value = url_field_text;
		try
		{
			url_field.onkeyup();
		}
		catch(e){}
    }
}

function update_metadata_url(count)
{
	if(jQuery("#page_id_" + count + " option:selected").val() > 0)
	{
		try
		{
			jQuery.post(
				"/admin/get_page_data",
				{
	            	page_id: document.getElementById("page_id_" + count).value
				},
				function(data)
				{
					if(data == "FAILED")
					{
						error("Error", "Error getting this page's URL. If you modify the URL field, this page's URL will be updated. You probably don't want to save the form this way!", true, null);
					}
					else
					{
						jQuery("#url_" + count).val(data["url"]);

						if(data["title"] != "")
						{
							jQuery("#title_" + count).val(data["title"]);
						}
						if(data["description"] != undefined && data["description"] != "")
						{
							jQuery("#description_" + count).val(data["description"]);
						}
					}
				}
			);
		}
		catch(e)
		{
			error("Error", "Error getting this page's URL. If you modify the URL field, this page's URL will be updated. You probably don't want to save the form this way! " + e, true, null);
		}
	}
	else
	{
	}
}

function set_metadata_dirty(count)
{
	jQuery("#submit_" + count).removeClass("btn-success");
	jQuery("#submit_" + count).addClass("btn-danger");
}

function set_metadata_clean(count)
{
	jQuery("#submit_" + count).addClass("btn-success");
	jQuery("#submit_" + count).removeClass("btn-danger");
}

function save_metadata_pages(count)
{
	try
	{
		jQuery.post(
			"/admin/metadata_pages_save",
			{
				metadata_id: jQuery("#metadata_id_" + count).val(),
				site_id: jQuery("#site_id_" + count).val(),
				page_id: jQuery("#page_id_" + count).val(),
				url: jQuery("#url_" + count).val(),
				title: jQuery("#title_" + count).val(),
				description: jQuery("#description_" + count).val()
			},
			function(data)
			{
				if(data == "FAILED")
				{
					set_metadata_dirty(count);
					error("Error", "Error saving your meta data. You may have already used this URL.", true, null);
				}
				else
				{
					//data will contain our ID
					set_metadata_clean(count);
					var new_record = (jQuery("#metadata_id_" + count).val() == "");
					jQuery("#metadata_id_" + count).val(data);

					if(new_record)
					{
						jQuery("#delete_" + count).unbind().attr("onclick", "");
						jQuery("#delete_" + count).click(function()
						{
							nerivon_confirm('Are you sure?', 'This item will be deleted.', 'warning', true, function(confirmed)
							{
								if(confirmed)
								{
									window.location = '/admin/metadata_pages_delete/' + data;
								}
							});

							return false;
						});
					}
				}
			}
		);
	}
	catch(e)
	{
		error("Error", "Error saving your meta data: " + e, true, null);
	}
}

function selectAllModules(value)
{
	jQuery(".module-checkbox-" + (value == 1 ? "yes" : "no")).click();
}

//user is "finished typing," do something
function doneTyping()
{
    //do something
	if(jQuery("#search_q").val() == "")
	{
		jQuery("#menu-search-result").html("");

		return false;
	}

	jQuery("#menu-search-result").html('<fieldset><legend>Search Results</legend><div class="text-center"><em class="fas fa-sync fa-spin" aria-hidden="true"></em> Searching...</div></fieldset>').slideDown(500, function()
	{
		// Animation complete
		try
		{
			jQuery.post(
				"/ajax/search/" + jQuery("#search_q").val(),
				{
	            },
				function(data)
				{
					var result = "";

					for (var key in data)
					{
						if (data.hasOwnProperty(key))
						{
							var count = 0;
							var this_result = "";

							for (var key2 in key)
							{
								if (data[key].hasOwnProperty(key2))
								{
									count++;
							    	this_result += "<li class='list-group-item'><a href='" + data[key][key2]["url"] + "' onclick='" + data[key][key2]["onclick"] + "'>" + data[key][key2]["text"] + "</a></li>";
							    }
							}

							if(count > 0)
							{
								this_result = "<ul class='list-group'><li class='list-group-item'>" + key + "</li>" + this_result + "</ul>";
					    	}

							result += this_result;
					  	}
					}

					if(result == "")
					{
						result = "<ul class='list-group'><li class='list-group-item'>Nothing Was Found</li></ul>";
					}

					jQuery("#menu-search-result").html('<fieldset><legend>Search Results</legend>' + result + '</fieldset>');
				}
			);
		}
		catch(e)
		{
			error("Error", "Error fetching search results: " + e, true, null);
		}
	});
}

function table_hover(table_selector, edit_link)
{
	jQuery(table_selector + ' tbody tr td').off('click').on('click',function(e)
	{
		// Prevent going to a link if there are any anchors or buttons in this cell.
		if(jQuery(this).find("a:not(a.click), button:not(button.click), input:not(input.click)").length > 0)
		{
			return;
		}

		// Find the primary key ID from our hidden field (older code, but has occasional purpose).
		id = jQuery(this).parent().find('input.pk').first().val();

		if(id == "" || typeof id == "undefined")
		{
			// Find the primary key ID which is automatically added as the ID for the TR.
			var id = jQuery(this).parent().attr("id");
		}

		// If we have an ID, redirect to it.
		if(id != "")
		{
			edit_link = edit_link.replace("{id}", id);
			window.location = edit_link;
		}
	});
}

function get_popular_image_size(e)
{
	// e.preventDefault();

	category_id = jQuery("#category_id").val();

	jQuery.post(
		'/ajax/get_popular_image_size/' + category_id,
		{
	    },
		function(data)
		{
			if(typeof data == "object")
			{
				if(data.width && data.height)
				{
					jQuery(".image-size-recommendation").removeClass("hidden").html("Most of your pages " + (category_id > 0 ? "in this category " : "") + "are using " + data.wh);
				}
				else
				{
					jQuery(".image-size-recommendation").removeClass("hidden").html("");
				}
			}
		}
	);
}

function setModulePagesDisplay()
{
	setTimeout(function()
	{
		var position = jQuery("#position").val();
		var always_on = (Number(jQuery(".toggle_value_always_on").val()) >= 1);

		if(position.length > 0)
		{
			jQuery(".always_on_container").show();
            jQuery(".always_on_container :input").prop("required", true);
		}
		else
		{
			jQuery(".always_on_container").hide();
            jQuery(".always_on_container :input").removeAttr("required");
		}

		if(position.length > 0 && !always_on)
		{
			jQuery("#modules_pages_container").show();
            jQuery("#modules_pages_container :input").prop("required", true);
		}
		else
		{
			jQuery("#modules_pages_container").hide();
            jQuery("#modules_pages_container :input").removeAttr("required");
		}
	},250);
}

function getFileTitle(e)
{
	filename = e.target.value.replace(/\.([a-z0-9]+?)$/ig, "").replace("_", " ").trim();
	filename = filename.replace('C:\\fakepath\\', '');

	if(jQuery("#title").val() == "")
	{
		jQuery("#filename").val("0");
		jQuery("#url").val("");
		jQuery("#title").val(filename).focus().blur();
	}
}

function closeSidebar()
{
	jQuery('#st-container').removeClass('st-menu-open');
}

function shopSelectAllProducts(obj)
{
	jQuery(".shop_product_checkbox").prop("checked", obj.checked ? true : false);
}

function shopSelectAllOrders(obj)
{
	jQuery(".shop_order_checkbox").prop("checked", obj.checked ? true : false);
}

function shopCategoryDialog()
{
	jQuery( "#shop-category-dialog" ).dialog(
	{
		title: "Batch Update Main Product Category",
		width: 500,
		maxHeight: 480,
		modal: true
	});
}

function shopPriceDialog()
{
	jQuery( "#shop-price-dialog" ).dialog(
	{
		title: "Batch Update Product Price",
		width: 500,
		maxHeight: 480,
		modal: true
	});
}

function shopSizeDialog()
{
	jQuery( "#shop-size-dialog" ).dialog(
	{
		title: "Batch Update Product Dimensions",
		width: 500,
		maxHeight: 480,
		modal: true
	});
}

function shopOrderStatusDialog()
{
	jQuery("#new_status_id").val(1);
	jQuery("#paid_yes").prop("checked", false);
	jQuery("#paid_no").prop("checked", false);
	jQuery("#tracking_number1").val("");
	jQuery("#tracking_number2").val("");
	jQuery("#tracking_number3").val("");

	jQuery( "#shop-order-status-dialog" ).dialog(
	{
		title: "Batch Update Order Status",
		width: 550,
		maxHeight: 480,
		modal: true
	});
}

function shop_get_selected_products()
{
	var checked = "";

	jQuery(".shop_product_checkbox:checked").each(function()
	{
		checked += "'" + jQuery(this).attr('id').replace("shop_product_", "") + "',";
	});

	if(checked.length > 0)
	{
		return checked.substring(0, checked.length-1);
	}
	else
	{
		return false;
	}
}

function shop_get_selected_orders()
{
	var checked = "";

	jQuery(".shop_order_checkbox:checked").each(function()
	{
		checked += "'" + jQuery(this).attr('id').replace("shop_order_", "") + "',";
	});

	if(checked.length > 0)
	{
		return checked.substring(0, checked.length-1);
	}
	else
	{
		return false;
	}
}

function remove_product_image(link, image_id)
{
	nerivon_confirm('Are you sure?', 'This image will be deleted.', 'warning', true, function(confirmed)
	{
		if(confirmed)
		{
			jQuery.post
		    (
		        "/admin/delete_product_image",
		        {
		            image_id: image_id
		        },
		        function(data)
		        {
		        	if(data == "SUCCESS")
		        	{
		        		// Hide the parent <li>
		        	    jQuery(link).parent().hide(1000);
		        	}
		        	else
		        	{
		        		error("Error", "There was an error removing this image.", true, null);
		        	}
		        }
		    );
		}
	});
}

function get_layout_options(layout_id, product_id, result_id)
{
    var results = document.getElementById(result_id);

    jQuery.post
    (
        "/ajax/get_shop_layout_options",
        {
            layout_id: layout_id,
            product_id: product_id
        },
        function(data)
        {
            results.innerHTML = "<i class='fas fa-spin fa-spinner'></i> Loading Layout Specific Values...";

            if(typeof data === 'string')
            {
                new_html = data;
            }
            else if(typeof data === 'object')
            {
                var new_html = "";
                var run_after = "";
                var total_fields = 0;

                jQuery.each( data, function( key, obj )
                {
                    if(obj.datatype != "video")
                    {
                    	total_fields ++;
                    }
                });

                var per_column = Math.ceil(total_fields/2);
                var count = 0;

                new_html += '<div class="row"><div class="col-12 col-md-6">';

                jQuery.each( data, function( key, obj )
                {
                    if(obj.datatype == "video")
                    {
                    	if(obj.data_value != "")
                    	{
                    		new_html += '<input type="hidden" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" value="' + htmlEntities(obj.data_value) + '" />';
                    	}
                    }
                    else
                    {
                    	count++;

	                    if(count == per_column+1)
	                    {
	                      	new_html += '</div><div class="col-12 col-md-6">';
	                    }
	                    new_html += '<input type="hidden" name="product_option_' + obj.key + '_old_value" id="product_option_' + obj.key + '_old_value" value="' + htmlEntities(obj.data_value) + '" />';
                    	new_html += '<div class="<?php echo(FORM_ROW); ?>">';
	                    new_html += '<label for="' + obj.key + '" class="col-12 col-md-5 col-lg-4">' + obj.data_name + '</label>';
	                    new_html += '<div class="col-12 col-md-7 col-lg-8">'

	                    switch(obj.datatype)
	                    {
	                        case "checkbox":
	                        {
	                        	var checked = (obj.data_value == 1);

	                            new_html += '<input type="checkbox" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" ' + (checked ? 'checked' : '') + ' value="1" />';

	                            break;
	                        }
	                        case "text":
	                        {
	                            new_html += '<input class="form-control" type="text" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" value="' + htmlEntities(obj.data_value) + '" />';

	                            break;
	                        }
	                        case "textarea":
	                        {
	                            new_html += '<textarea class="form-control" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" >' + htmlEntities(obj.data_value) + '</textarea>';

	                            break;
	                        }
	                        case "number":
	                        {
	                            new_html += '<input class="form-control" type="number" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" value="' + htmlEntities(obj.data_value) + '" />';

	                            break;
	                        }
	                        case "email":
	                        {
	                            new_html += '<input class="form-control" type="email" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" value="' + htmlEntities(obj.data_value) + '" />';

	                            break;
	                        }
	                        case "number":
	                        {
	                            new_html += '<input class="form-control" type="tel" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" value="' + htmlEntities(obj.data_value) + '" />';

	                            break;
	                        }
	                        case "url":
	                        {
	                        	//type = "url" doesn't seem to accept relative URLs so we're going to just use text
	                            new_html += '<input class="form-control" type="text" name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" value="' + htmlEntities(obj.data_value) + '" />';

	                            break;
	                        }
	                        case "file":
	                        {
	                            new_html += '<select name="product_option_' + obj.key + '" id="product_option_' + obj.key + '" class="form-control custom-select">';
	                            new_html += '<option value="0">Select Existing File</option>';
	                            new_html += existing_files_select_options;
	                            new_html += '</select><label>&nbsp;</label>';
	                            new_html += '<input type="file" name="product_option_' + obj.key + '_file" id="product_option_' + obj.key + '_file" />';

	                            if(obj.data_value)
	                            {
	                            	run_after += "jQuery('#product_option_" + obj.key + " option').filter(function() { return jQuery(this).text() == '" + obj.data_value + "'; }).prop('selected', true);\n";
	                            }

	                            break;
	                        }
	                    }

	                    new_html += '</div></div>';
	                }
                });

                new_html += '</div></div>';
            }

            results.innerHTML = new_html;

            if(run_after)
            {
            	eval(run_after);
            }
        }
    );
}

function select_shop_categories(category_id)
{
    var feral_checkbox = document.getElementById("category_id_" + category_id + "_checkbox")
    var feral_hidden = document.getElementById("category_id_" + category_id);

    //reset checkbox's click event for all checkboxes so we can assign it to just the clicked one afterwards
    jQuery(".category_id_checkbox").unbind("click");

    //set this checkbox to checked (using Feral, we set the hidden field as well)
    try
    {
    	feral_checkbox.checked = '1';
    	feral_hidden.value = '1';
    }
    catch(e)
    {
    	//ignore
    }

    //disable unchecking the default category
    jQuery(feral_checkbox).click(function(){return false;});
}

jQuery(window).on("load", function()
{
	jQuery(".list-filter").each(function()
	{
		jQuery(this).change(function()
		{
			setCookie("filter." + jQuery(this).attr("data-filter-name"), jQuery(this).val(), 1);
		});

		value = getCookie("filter." + jQuery(this).attr("data-filter-name"));

		if(value)
		{
			jQuery(this).val(value);
		}
	});

	jQuery("#shop-category-dialog-form").submit(function()
	{
		try
		{
			jQuery.post(
				"/admin/product_update_category",
				{
					product_ids: shop_get_selected_products(),
					category_id: document.getElementById("new_category_id").value
				},
				function(data)
				{
					jQuery("#shop-category-dialog").dialog( "close" );
					jQuery('#list').DataTable().ajax.reload();
				    jQuery("#shop_select_all_products").prop("checked", false);
				    success("Category Updated", "", true, null);
				}
			);
		}
		catch(e)
		{
			error("Error", "Error updating your product(s): " + e, true, null);
		}

		return false;
	});

	jQuery("#shop-price-dialog-form").submit(function()
	{
		try
		{
			jQuery.post(
				"/admin/product_update_price",
				{
					product_ids: shop_get_selected_products(),
					price: document.getElementById("price").value,
					price_lock: (document.getElementById("price_lock").checked ? "1" : "0"),
					update_price_lock: (document.getElementById("update_price_lock").checked ? "1" : "0")
				},
				function(data)
				{
					jQuery("#shop-price-dialog").dialog( "close" );
					jQuery('#list').DataTable().ajax.reload();
				    jQuery("#shop_select_all_products").prop("checked", false);
				    success("Price Updated", "", true, null);
				}
			);
		}
		catch(e)
		{
			error("Error", "Error updating your product(s): " + e, true, null);
		}

		return false;
	});

	jQuery("#shop-size-dialog-form").submit(function()
	{
		try
		{
			jQuery.post(
				"/admin/product_update_size",
				{
					product_ids: shop_get_selected_products(),
					shipping_length: document.getElementById("shipping_length").value,
					shipping_width: document.getElementById("shipping_width").value,
					shipping_height: document.getElementById("shipping_height").value,
					shipping_weight: document.getElementById("shipping_weight").value,
					update_shipping_length: (document.getElementById("update_shipping_length").checked ? "1" : "0"),
					update_shipping_width: (document.getElementById("update_shipping_width").checked ? "1" : "0"),
					update_shipping_height: (document.getElementById("update_shipping_height").checked ? "1" : "0"),
					update_shipping_weight: (document.getElementById("update_shipping_weight").checked ? "1" : "0")
				},
				function(data)
				{
					jQuery("#shop-size-dialog").dialog( "close" );
					jQuery('#list').DataTable().ajax.reload();
				    jQuery("#shop_select_all_products").prop("checked", false);
				    success("Size Updated", "", true, null);
				}
			);
		}
		catch(e)
		{
			error("Error", "Error updating your product(s): " + e, true, null);
		}

		return false;
	});

	jQuery("#shop-order-status-dialog-form").submit(function()
	{
		try
		{
			jQuery.post(
				"/admin/order_update_status",
				{
					order_ids: shop_get_selected_orders(),
					status_id: document.getElementById("new_status_id").value,
					paid: (document.getElementById("paid").value == 1 ? 1 : 0),
					tracking_number1: document.getElementById("tracking_number1").value,
					tracking_number2: document.getElementById("tracking_number2").value,
					tracking_number3: document.getElementById("tracking_number3").value
				},
				function(data)
				{
					jQuery("#shop-order-status-dialog").dialog( "close" );
					jQuery('#list').DataTable().ajax.reload();
				    jQuery("#shop_select_all_products").prop("checked", false);
				    success("Order Status Updated", "", true, null);
				}
			);
		}
		catch(e)
		{
			error("Error", "Error updating your order(s): " + e, true, null);
		}

		return false;
	});

	jQuery(window).resize();
});

/**
 * Some versions of jQuery break this function and JS Webshim requires it.
 */
jQuery.swap = function( elem, options, callback, args ) {
    var ret, name, old = {};
    // Remember the old values, and insert the new ones
    for ( name in options ) {
            old[ name ] = elem.style[ name ];
            elem.style[ name ] = options[ name ];
    }

    ret = callback.apply( elem, args || [] );

    // Revert the old values
    for ( name in options ) {
            elem.style[ name ] = old[ name ];
    }
    return ret;
};

jQuery(window).on("resize", function()
{
	var h = jQuery(".nv-sidebar").eq(0).height();
	jQuery(".content").css({"margin-top": h + "px"});
	jQuery(".nv-sidebar-content, .nv-sidebar-content-open").css({"top": (h - 2) + "px"});
});
