var query = null;
var url = "/shop/adserveContent.aspx";
var catalog = null;
var category = null;

jQuery.query = function(s) {
     var r = {};
     var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
     q = q.replace(/\&$/, ''); // remove the trailing &
     jQuery.each(q.split('&'), function() {
         var splitted = this.split('=');
         if (splitted.length > 1) {
			 var key = splitted[0];
			 var val = splitted[1];
			 // convert floats
			 if (/^[0-9.]+$/.test(val)) { val = parseFloat(val); }
			 // ignore empty values
			 if ( typeof(val) == 'number' || val.length > 0) { r[key.toLowerCase()] = val; } // PC 27/03/09 - always lowercase the key for consistent naming
         }
     });
     return r;
};

$j(document).ready(function() {
	query = $j.query(location.search);

	catalog = query.catalog == undefined ? "" : query.catalog;
	category = query.category == undefined ? "" : query.category;
	
	$j(".adservingCookie:first").each(function() {
		var el = $j(this);
		var locCatalog = catalog;
		var locCategory = category;
		
		if (el.attr("catalog")) {
			locCatalog = el.attr("catalog");
		}
		if (el.attr("category")) {
			locCategory = el.attr("category");
		}
		
		$j.ajax({
			type: "GET",
			url: "/shop/adserveCookies.aspx",
			data: {
				catalog: locCatalog,
				category: locCategory,
				originLocation: location.pathname + location.search
			},
			// Ajax error handler
			error: function(xhr, status, error) {

			},
			 // Ajax success handler
			success: function(responseText, textStatus) {
				// Retrieve the time we last updated the cookies
				var lastUpdate = new Date($j.cookie("lastUpdate"));
				var now = new Date();
				var delta = (Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()) - 
								Date.UTC(lastUpdate.getUTCFullYear(), lastUpdate.getUTCMonth(), lastUpdate.getUTCDate(), lastUpdate.getUTCHours(), lastUpdate.getUTCMinutes(), lastUpdate.getUTCSeconds())) 
									/ 1000;
									
				debug.log("delta:" + delta);
				debug.log("now:"+now.toString());
				debug.log("lastUpdate:" + lastUpdate.toString());
				
				var data = JSON.parse(responseText);
				for(var i = 0; i < data.length; i++) {
					for(cookieName in data[i]) {
						// Save the old value so we can use it as the user browses around the site now
						var oldVal = $j.cookie(cookieName);
						if (oldVal != null) {
							// Need to check if we've already set an old cookie
							if ($j.cookie("old" + cookieName) == null || delta > 1200) {
							debug.log("old cookie was null or delta > 1200:" + cookieName);
								$j.cookie("old" + cookieName, oldVal); // Set this as a session cookie, so will expire when user leaves site
								
								// Set the time we last updated the *old* cookies
								$j.cookie("lastUpdate", new Date(), { expires: new Date(2099,11,31,12,00,00), path: '/' });
							}
						}
						
						// Now set the new cookie
						$j.cookie(cookieName, data[i][cookieName], { expires: new Date(2099,11,31,12,00,00), path: '/' });
					}
				}
				
				// Once we've processed the cookies, load the adserve content
				processAdserveContent();
			}
		});
	});
});

function processAdserveContent() {
debug.log(">>> processAdserveContent");
	var mostRecent = getCookie("mostRecent", "");
	var mostRecentSub = getCookie("mostRecentSub", "");
	var repeatVisit = getCookie("repeatVisit", "");

	// Find all adservingContent elements and replace them with content loaded via Ajax
	$j(".adservingContent").each(function() {
		var el = $j(this);
		var locCatalog = catalog;
		var locCategory = category;
		
		if (el.attr("catalog")) {
			locCatalog = el.attr("catalog");
		}
		if (el.attr("category")) {
			locCategory = el.attr("category");
		}
		
		var data = {
				catalog: locCatalog,
				category: locCategory,
				originLocation: location.pathname + location.search,
				mostRecent: mostRecent,
				mostRecentSub: mostRecentSub,
				repeatVisit: repeatVisit
			  };
debug.log("processing children");
		var node = processChildren(el, 1);
		if (node != null && node != -1) {
		debug.log("a matching child node has been found");
			node = findContent(node);
			if (node != null) {
			debug.log("a node with a href or content has been found");
				var href = node.attr("href");
				if (href) {
					loadAdserveContent(el, href, null);
				}
				else if (node.html() != "") {
					var content = node.html();
					el.empty();
					el.append(content);
					el.fadeIn("slow");
				}
			}
		}
		else {
		debug.log("loading default adserve content");
			loadAdserveContent(el, url, data);
		}		
    });
}

// Iterate over the child DOM nodes of the supplied element and match up the specified cookie attributes with the actual cookie values
function processChildren(el) {
debug.log(">>> processChildren");
	var children = el.children("div");
	if (children.length > 0) {
		var result = null;
		
		children.each(function() {
			if (result === null) {
				var child = $j(this);
				var cookie = child.attr("cookie");
				var value = child.attr("value");
	debug.log("child:" + cookie + "=" + value);
				if (cookie) {
					// If this matches the cookie value, process any child nodes
					if (value == getCookie(cookie)) {
					debug.log("cookie match");
						var childResult = processChildren(child);
						// If this node has no children, we've reached the end of the chain and all cookies match, so return this object
						if (childResult === -1) {
						debug.log("childResult is -1");
							result = child;
						}
						else if (childResult != null) {
						debug.log("childResult is a node");
							result = childResult;
						}
					}
				}
			}
		});
		
		return result;
	}
	
	return -1;
}

// From the passed in DOM element, iterate up the chain and return the first element that has a href specified or some content
function findContent(node) {
	if (node == null || node.length === 0) {
		return null;
	}
	if (node.attr("href") || node.html() != "") {
		return node;
	}
	
	return findContent(node.parent("div:first"));
}

// Make an ajax request to the specified URL and load the returned content in the supplied element
function loadAdserveContent(el, url, data) {
	$j.ajax({
		type: "GET",
		url: url,
		data: data,
		// Ajax error handler
		error: function(xhr, status, error) {

		},
		// Ajax success handler
		success: function(responseText, textStatus) {
			el.empty();
			el.append(responseText);
			el.fadeIn("slow");
		}
	});
}

function getCookie(cookieName, defaultValue) {
	var cookie = $j.cookie("old" + cookieName);
	if (cookie == null) {
		return defaultValue;
	}
	
	return cookie;
}