function checkQty(aField,aStock)
{
	var aQty = aField.value;
	if (aQty > aStock)
	{
		alert("Please modify your order quantity for this item.\n We have " + aStock + " in stock and you have ordered " + aQty + ".");
		aField.value=0;
	}
}
	
function docart(){
	if(addtocart()){
		updateBagTotals();
		scroll(0,0);
		$cp=$("#cartpop");
		$cp.css({display:"none",visibility:"visible"}).slideUp(0,function(){$cp.slideDown("slow")});
		$(".qtyfld").each(function(index) {
			$(this).val("");
		});
	}
}

function addtocart(){
	var prod, stk, newX, errmsg="";
	var bshow=false;
	$.each($(".qtyfld"),function(i,e){
		if ((!isNaN(e.value))&&(e.value>0)){
			prod = e.name.split("|");
			desc = prod[3];
			stk = prod[7];
			if(parseInt(e.value) > parseInt(stk)){
				newX = "Item|"+prod[1]+"|"+prod[2]+"|"+htmlEncode(desc)+"|"+prod[4]+"|"+htmlEncode(prod[5])+"|"+prod[6]+"|"+prod[7]+"|"+prod[7];
				errmsg = errmsg + 'Item #' + prod[2] +': '+ e.value +' ordered with '+ stk +' available.<br>';
				SetCookie("shopcart", prod[1], newX, 7, "/", ".esutures.com", "")
				bshow=true;
				if($('#bagTB').length){
					$('#bagTB tr:first').before('<tr><td colspan=4>'+errmsg+'</td></tr>');
					$('#bagTB tr:last').after('<tr><td>'+stk+'</td><td><b>'+prod[2]+'</b><br>'+desc.replace("/amp;","&")+'</td><td>'+prod[5]+'</td><td>'+formatCurrency(prod[4])+'</td></tr>');
				}else if($('#cartTB').length){
					$('#txtErrMsg').val(errmsg);
				}
			}else
			if (GetCookieLen("shopcart","")>2700){
				bshow=true;
				errmsg += "Item #" + prod[2] +": "+ e.value +" was not added to your order due to your cart being full.<br>"
				if($('#bagTB').length){
					$(".bag-err").css({display:"block"}).html(errmsg);
				}else if($('#cartTB').length){
					$('#txtCartErrMsg').val(errmsg);
				}
			}else {
				SetCookie("shopcart", prod[1], e.name+"|"+e.value, 7, "/", ".esutures.com", "");
				bshow=true;
				if($('#bagTB').length){
					$('#bagTB tr:last').after('<tr><td>'+e.value+'</td><td><b>'+prod[2]+'</b><br>'+desc.replace("/amp;","&")+'</td><td>'+prod[5]+'</td><td>'+formatCurrency(prod[4])+'</td></tr>');
				}
			}
		}
	});
	return bshow;
}

function updatecart(){
	emptycart();
	addtocart();
	document.shopcart.submit();
}

function removefromcart(){
	emptycart();
	addtocart();
	window.location = "/cart/";
}

function emptycart(){
	SetCookie("shopcart", "", "", -7, "/", ".esutures.com", "");
}

function dopriceadjust(){
	var prod, newX;
	$.each($(".qtyfld"),function(i,e){
		if ((!isNaN(e.value))&&(e.value>0)){
			prod = e.name.split("|");
			newX = "Item|"+prod[1]+"|"+prod[2]+"|"+htmlEncode(prod[3])+"|"+e.value+"|"+htmlEncode(prod[5])+"|"+prod[6]+"|"+prod[7]+"|"+prod[8];
			//alert(newX);
			SetCookie("shopcart", prod[1], newX, 7, "/", ".esutures.com", "")
		}
	});
	window.location = "/cart/";
}

function addBagTBRow(qty,desc,expdt,price){
	//var $table = $("#bagTB");
	//var n = $('tr:last td', $table).length;
	//var tds = '<tr><td>'+qty+'</td><td>'+desc.replace("/amp;","&")+'</td><td>'+expdt+'</td><td>'+price+'</td></tr>';
	//$table.append(tds);
	$('#bagTB tr:last').after('<tr><td>'+qty+'</td><td>'+desc.replace("/amp;","&")+'</td><td>'+expdt+'</td><td>'+price+'</td></tr>');
}

function closeBagTB(){
	$("#bagTB tr:gt(0)").remove();
	$(".bag-err").css({display:"none"}).html("");
	hideElement('cartpop');
}

function updateBagTotals(){
	var tot=0;
	var cnt=0;
	var cookie;
	cookie=hGetCookie("shopcart");
	if(cookie.indexOf("%7C")){
		cookie = unescape(cookie);
	}
	var subKeys=cookie.split("&");
    if(subKeys.length>0){
		for(var i=0; i<subKeys.length; i++) {
			var nameval = subKeys[i].split("=");
			//alert("product: " + nameval[1]);
			var prod = nameval[1].split("|");
			//alert('price: '+prod[4]+' q: '+prod[8]);
			if(prod[8]>0){
				tot += (parseFloat(prod[4].replace(/[^\d.]/g, '')) * parseInt(prod[8]));
				cnt += 1;
			}
		}
	}
	
	$("#cartCnt").text(cnt);
	if(tot){$("#cartTotal").text(formatCurrency(tot));}
}

function clearShopCart(){
	if(confirm('Are you sure you want to clear all cart items?')){
		emptycart();
		window.location = "/cart/";
	}
}
	
function hideElement(elementId){
	$("#"+elementId).slideUp()
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function htmlEncode(value){ 
  return $('<div/>').text(value).html(); 
} 

/* Begin functions dealing with Cookies */
function hSetCookie(name, value, expires, path, domain, secure){
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) expires = expires * 1000 * 60 * 60 * 24;
	var expires_date = new Date(today.getTime() + (expires));
	document.cookie = name+"="+escape(value) +
	//document.cookie = name+"="+value +
		((expires) ? ";expires="+expires_date.toGMTString() : "") +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
} 
function hGetCookie(cookie_name){
	var regexp=new RegExp(cookie_name +"=(.*?)(;|$)","i");
	var results=regexp.exec(document.cookie);
	if(results){
		return(unescape(results[1]));
		//return(results[1]);
	}else{
		return null;
	}
} 

function hasSubKeys(cookieName){
    var ret=false;
    var cookie=unescape(hGetCookie(cookieName));
	//var cookie=hGetCookie(cookieName);
    var subKeys=cookie.split("&");
    if(subKeys.length>=2){
        ret=true;
    }else{
        var subKeys=cookie.split("=");
        if(subKeys.length>=1){
            ret=true;
        }
    }
    return ret;
}


function GetCookie(cookieName,keyName){
	var ret;
	var cookie=unescape(hGetCookie(cookieName));
	//var cookie=hGetCookie(cookieName);
	//alert(cookie);
	if(keyName && hasSubKeys(cookieName)==true){
		var cookieData=getCookieData(cookie);
		ret=cookieData[keyName];
	}else{
		ret=cookie;
	}
	return ret
}

function SetCookie(cookieName,keyName,value,expires, path, domain, secure){
	var thisCookie=unescape(hGetCookie(cookieName));
	//var thisCookie=hGetCookie(cookieName);
	if((thisCookie) && (thisCookie != "null")){
		if(keyName){
			//alert("(SetCookie) keyName: "+keyName);
			var cookieData=getCookieData(thisCookie);
			cookieData[keyName]=value;
			value="";
			for (var cookie in cookieData){
				//alert("(SetCookie) cookie in cookieData: "+cookie+"="+cookieData[cookie]);
				value +=cookie+"="+cookieData[cookie]+"&";
			}
			if(value.charAt(value.length-1)=="&"){value=value.substring(0,value.length-1)}
		}
	}else{
		value = keyName+"="+value;
	}
	//alert("(SetCookie) "+cookieName+"\n"+value);
	hSetCookie(cookieName, value, expires, path, domain, secure)
}

function getCookieData(cookie){
	var ret=[];
	var subKeys=cookie.split("&");
	for (var i=0;i<subKeys.length;i++){
		//alert(subKeys[i]);
		var pos=subKeys[i].indexOf("=");
		if(pos!=0){
			//alert("cookieData["+subKeys[i].substring(0,pos)+']='+subKeys[i].substring(pos+1));
			ret[subKeys[i].substring(0,pos)]=subKeys[i].substring(pos+1);
		}
	}
	return ret;
}

function GetCookieLen(cookieName,keyName){
	var ret;
	var cookie=unescape(hGetCookie(cookieName));
	//var cookie=hGetCookie(cookieName);
	//alert("(GetCookieLen) cookie: \n" + cookie);
	if(keyName && hasSubKeys(cookieName)==true){
		var cookieData=getCookieData(cookie);
		ret=cookieData[keyName];
	}else{
		ret=cookie;
	}
	if(ret){
		return ret.length;
	}else{
		return 0;
	}
	
}
/* End functions dealing with Cookies */


