/*
 * AJAX functions
 * ==============
 */

function ajaxAddToBag(ref, size, name) {
	if (checkCookiesEnabled()) {

		if (!size) {
			alert("You did not select a size - please choose one from the options provided and try again!");
		} else {
			var ajaxObject = new sack();
			ajaxObject.requestFile = '/shop/addToBag.php?itemRef=' + ref + '_' + size;
			ajaxObject.runAJAX();

			alert(name + " has been added to your shopping bag!\nTo adjust quantities or purchase your selection, please click on 'check out' at the top of the page.\nOtherwise, please continue browsing for additional products!");
		}
	} else {
		alert("It looks like 'cookies' are disabled in your web browser. We need you to allow cookies from this site in order to use the basket functionality.");
	}
}

function ajaxUpdateBagCount() {
	var ajaxObject = new sack();
	ajaxObject.requestFile = '/shop/getBagItemCount.php';
	ajaxObject.onCompletion = function() { document.getElementById('bagItemCount').innerHTML = ajaxObject.response; };
	ajaxObject.runAJAX();
}


/*
 * Cookie Functions
 * ================
 *
 * Based on http://techpatterns.com/downloads/javascript_cookies.php
 */

function cookieDelete(name, path, domain) {
	if ( cookieGet( name ) ) {
		document.cookie = name + "=" +
			( ( path ) ? "; path=" + path : "" ) +
			( ( domain ) ? "; domain=" + domain : "" ) +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function cookieGet(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while ( i < clen ) {
		var j = i + alen;
		if ( document.cookie.substring(i, j) == arg ) return cookieGetVal(j);
		i = document.cookie.indexOf( " ", i ) + 1;
		if ( i == 0 ) break;
	}
	return null;
}

function cookieGetVal(offset) {
	var endstr = document.cookie.indexOf ( ";", offset );
	if ( endstr == -1 ) endstr = document.cookie.length;
	return unescape( document.cookie.substring( offset, endstr ) );
}

function cookieSet(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape (value) +
		( ( expires ) ? "; expires=" + expires.toGMTString() : "" ) +
		( ( path ) ? "; path=" + path : "" ) +
		( ( domain ) ? "; domain=" + domain : "" ) +
		( ( secure ) ? "; secure" : "" );
}

function checkCookiesEnabled() {
	cookieSet("foo", "bar");
	if (cookieGet("foo")) {
		cookieDelete("foo");
		return true;
	} else {
		return false;
	}
}	
