(function(_) {
_.log("Executing managed setup script");
let pages = [];
_.pages.setData(pages);
for (let i=0; i<pages.length; i++) {
	const page = pages[i];
	if (!_.pages.isVisible(page)) {
		continue;
	}
	let container = document.getElementById("helloretail-category-page-" + page.key);
	if (container) {
		// Try to find existing filters in the storage
		let products = {};
		const stored_string = _.search.util.get_query_var('hr-page');
		if (stored_string && stored_string.length > 1 && stored_string[0] == '{') {
			// query string var called hr-page
			try {
				products = JSON.parse(stored_string);
			} catch (e) {
				_.log("Could not parse preset filters or sorting for page " + page.key);
			}
		} else if (window.location.hash.length > 1 && window.location.hash[1] == '{') {
			// fragment part of url
			try {
				const store = JSON.parse(decodeURIComponent(window.location.hash.substr(1)));
				if (store[page.key]) {
					products = store[page.key];
				}
			} catch (e) {
				_.log("Could not parse preset filters or sorting for page " + page.key);
			}
		}
		
		const options = {
			id: page.id,
			url: document.location.href,
			products: products,
			params: container.dataset,
			firstLoad: true
		}
		_.api.pages.load(page.key, options, function(data){
			// Removes stylesheets with same key as the current page
			let loaded_styles = document.head.querySelectorAll(`style[data-hello_retail_page_key='${page.key}']`);
			loaded_styles.forEach(style => {
				style.remove();
			});
			
			// Insert stylesheet
			const style = document.createElement('style');
			style.dataset.hello_retail_page_key = page.key;
			style.innerHTML = data.products.style;
			document.head.appendChild(style);
			new Function('_', 'container', 'data', 'page', data.products.javascript).bind(null)(_, container, data, page);
		});
	}
}
})(ADDWISH_PARTNER_NS);
