/*
 * Continue shopping which uses the referrer to redirect to
 *  
 * Version 1.0
 * 
 */
/**
 * 
 */
function continueShopping() {
	var referrer = null;
	var referrerPage = null;
	var defaultPage = '/';
	var currentPage = window.location.pathname;
	var currentHost = window.location.host;
	var productURL = null;
	
	//Make sure the property exists
	if(document.referrer) {
		referrer = document.referrer;
	}

	//Get the product URL, if any
	try {
		productURL = getProductHistoryURL();				
	} catch(e) {
		productURL = null;
	}
	defaultPage = (productURL == null ? defaultPage : productURL);
				
	//Make sure we have something first
	if(referrer == null || referrer == '') {
		window.location.href = defaultPage;
		return;
	}
	
	try {
		hostPosition = referrer.indexOf(currentHost)
		
		//Check for not found
		if(hostPosition == -1) {
			//Incorrect host
			window.location.href = defaultPage;
			return;	
		}
		
		//Extract the path
		referrerPage = referrer.substring( (hostPosition + currentHost.length));

		//Check to see if we are on the same page
		if(referrerPage.toLowerCase() == currentPage.toLowerCase()) {
			window.location.href = defaultPage;
			return;			
		}
		
		window.location.href = referrerPage;
		return;
	}
	catch(e) {
		//Error, just redirect to default
		window.location.href = defaultPage;
		return;				
	}
}

/**
 * 
 */
function getProductHistoryURL() {
	//%2FHistory
	// /History
	var cookieName = '%2FHistory';
	var cookies = null;
	var cookiePackage = null;
	var productCode = null;
	var productCodes = null;
	
	if(!document.cookie || document.cookie == null) {
		return null;
	}
	
	//Divide up the cookies
	cookies = document.cookie.split(';');

	for(index = 0; index < cookies.length; index++) {
		cookiePackage = cookies[index];
		while(cookiePackage.charAt(0) == ' ') {
			cookiePackage = cookiePackage.substring(1, cookiePackage.length);
		} 
				
		if(cookiePackage.indexOf(cookieName + '=') == 0) {
			productCode = cookiePackage.substring(cookieName.length + 1);
			
			//Check for empty
			if(productCode == null || productCode == '') {
				return null;
			}
			
			//Split up the codes
			productCodes = productCode.split('%2C');
			
			//Return the URL
			return '/ProductDetails.asp?ProductCode=' + productCodes[0];
		}
	}
	
	return null;
}
