/**
 * Dandomain Navigation class
 * 
 * Developed by Joachim Loevgaard (www.loevgaard.dk)
 */
function DandomainNavigation() {
	this.steps = new Array();
	this.COOKIE_NAME = "dandomainNavigation"
}

DandomainNavigation.prototype.init = function() {
	var navigationStr = $.cookie(this.COOKIE_NAME) ? $.cookie(this.COOKIE_NAME) : "";
	navigationSteps = navigationStr.split("|");
	
	for(var i in navigationSteps) {
		if(!navigationSteps[i]) continue;
		
		this.steps.push(navigationSteps[i]);
	}
	this.steps.push(encodeURI(location.pathname));
	
	$.cookie(this.COOKIE_NAME, this.steps.join("|"), { path: '/', domain: "." + document.location.hostname });
}

/**
 * This method only works if its used on a product page
 * 
 * It will return or navigate to the URL of the most sensible last page of the actual product
 */
DandomainNavigation.prototype.backToCategory = function(redirect) {
	 var url = $('.BreadCrumbLink_Active:first').attr('href');
	 var productUri = this.productUri();
	 
	 if(this.steps.length > 1) {
		 var i = this.steps.length-1;
		 while(i >= 0 && productUri == this.productUri(this.steps[i])) {
			 i--;
		 }
		 if(i >= 0) url = this.steps[i];
	 }
	 if(redirect) {
		 location.href = url;
	 } else {
		 return url;
	 }
	 /*
	 var url = $('.BreadCrumbLink_Active:first').attr('href');
	 var productUri = this.productUri();
	 
	 if(this.steps.length > 1) {
		 for(var i = (this.steps.length - 1); i >= 0; i--) {
			 if(this.steps[i].match(/c[0-9]+\.html/gi)) {
				 if(this.steps[i+1].indexOf(productUri) >= 0) {
					 alert(productUri);
					 url = this.steps[i];
					 break;
				 }
			 }
		 }
	 }
	 if(redirect) {
		 location.href = url;
	 } else {
		 return url;
	 }
	 */
}
 
DandomainNavigation.prototype.productUri = function(str) {
	if(!str) str = location.pathname;
	var pathPieces = str.split("/");
	var acc = pathPieces[pathPieces.length-1].match(/[a-z0-9\-]+[a-z0-9]+/i);
	acc = acc[0].replace(/(\-)?[0-9]+p/i, "");
	return acc;
}

var nav;
$(document).ready(function() {
	nav = new DandomainNavigation();
	nav.init();
});