// JavaScript Document
function change_link( price, product_code, begin, end ){
	//first we need to get the number of items that is to be added to the shoping cart
	//note qty_*** is the text box that contains the desired number of items to be added
	var amount = parseInt(document.getElementById('qty_' +product_code).value, 10);
	
	//if it is not a number or not a positive integer we need to exit
	if( isNaN(amount) || amount < 1 ){	
		//do nothing
	}else{
		//we need to convert the sc_num to a string 
		var sc = readCookie('sc');

		var found = false;
			
		//we check to see if there is a any previous products bought that are identical to the new one
		for( var i = 0; i < sc.length/6 && !found ; i++ ){
			if( product_code.toString() == sc.substring( (i*6), (i*6)+3 ) ){
				//we have found the string for alteration
				//first we need the existing amount 
				pq = parseInt(sc.substring( (i*6)+3, (i*6)+6 ), 10 );
				pq_desired = pq + amount;
				var newString = "";
				if( pq_desired < 10 ){
					newString = "00" + pq_desired;
				}else if( pq_desired < 100 ){
					newString = "0" + pq_desired;
				}else if( pq_desired < 1000 ){
					newString = pq_desired;
				}else{
					//if we get here then the amount needs to be modified to ensure that no more than 999
					//of each item is included in the shopping cart basket
					amount = 999 - pq;
					newString = "999";
				}
					
				//now to change the sc
				sc = sc.replace( sc.substring( (i*6)+3, (i*6)+6 ), newString );
				found = true;
			}
		}
			
		if(!found){
			//we have a new product
			var newString=""
			if( amount < 10 ){
				newString = "00" + amount;
			}else if( amount < 100 ){
				newString = "0" + amount;
			}else if( amount < 1000 ){
				newString = amount;
			}else{
				newString = "999";
				amount = 999;
			}
				
			if( sc == "0" || sc == "" ){
				//this is the customer first item
				sc = product_code.toString() +newString;
			}else{
				//the customer has already got some items so we slap it to the end of the sc
				sc = sc +product_code.toString() +newString;
			}
					
		}
	
		//now we update the price of the product in the shopping cart basket
		var cost = (amount * parseFloat(price) ) + parseFloat(document.getElementById('st_subtotal').value);
		document.getElementById('st_subtotal').setAttribute( 'value', cost.toFixed(2) );
					
		//now we update the amount of items in the shopping cart basket
		var items = amount + parseInt(document.getElementById('st_items').value, 10);
		document.getElementById('st_items').setAttribute( 'value', items );
			
		//finaly the cookie needs updating
		createCookie( 'sc', sc, 1 );
						
		href = begin +amount + end;
			
		//alter the shopping cart link
		document.getElementById("sc_link_" +product_code).setAttribute( 'href', href );
	}
		
}
	
	