/****************************************************************
Copyright (c) <2009> <PieCart.co.uk> 

This software is copyright and can not be used, copied or redistributed 
in any way without both prior permission and a valid licence.
Licences are available from: www.piecart.co.uk

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Copying portions of this script will infringe International Copyright Laws 
and is strictly prohibited. Where possible, acknowledgments of authors and 
of source scripts have been made and web addresses provided. 
Please locate the original scripts if you wish to develop them.

Thanks go to to the authors, both paid and unpaid.
******************************************************************/

/*************************************************************************************************
	Thanks to Atul for the initialiser script and
	to Blue for the the Set Parameters list, associated mods and form validation.
**************************************************************************************************/

var PieCart;

	function loadCart()
	{
 	if(PieCart == null)
	{
	PieCart = new cart("sales@blingblong.co.uk");
	PieCart.initialize();
	}
	}

	function cart( business ) {
	this.ds	= 1;
	this.totalItems = 0;
	this.totalPrice	= 0.00;
	this.cancel =  'http://www.blingblong.co.uk/index.html';
	this.success =  'http://www.piecart.co.uk/success.html';
	this.minOrder	= 30.00;
	this.postage	= 0.00;
	this.postageA	= 0.00;
	this.threshA	= 0.00;
	this.postageB	= 3.00;
	this.threshB	= 60.00;
	this.postageC	= 5.00;
	this.items 		= new Array();
	this.userBusiness = business;
	
/****************************************************************
This notice applies to significant portions of the following section 
of the script, but not the whole script. Please locate the original 
scripts if you wish to utilise them. 
Thanks to Brett Wejrowski from (www.thewojogroup.com) for his generous 
and ingenious gift. 

Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person
obtaining a copy of simpleCart.js and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
******************************************************************/

	this.ItemColumns = ['ID','Name','Price','Options','Quantity','Total','Delete'];

	this.initialize = function () {
		if( !readCookie("PieCart") ) {
			this.totalItems  = 0;
			this.totalPrice = 0.00;
		} else {
			data = readCookie("PieCart").split("&");
			this.totalItems = data[0]*1;
			this.totalPrice = data[1]*1;
			for(x=2;x < (data.length);x++) {
				newItem = new item();
				itemData = data[x].split(",");
				i=0;
				for(i=0;i<itemData.length;i++) {
					pair = itemData[i].split('=');
					newItem.addValue(pair[0],pair[1]);
				}
				if(!newItem.getValue('name') || !newItem.getValue('price') || !newItem.getValue('quantity')) {
					alert("item must have price, name, and quantity!");
					return false;
				}
				this.items[x-2] = newItem;
			}
			
		}
		this.setUpEvents();
		this.updateCookie();
		this.updatePageElements();
		return;
	};

	this.checkOutEvent = function() {
		PieCart.checkOut();
		return false;
	};
	
	this.emptyEvent = function() {
		PieCart.empty();
		return false;
	};

	this.setUpEvents = function() {
			var x=0,element,elements = getElementsByClassName('PieCart_total');

			x=0;
			elements = getElementsByClassName('PieCart_checkout');
			for( x=0;x<elements.length;x++) {
				element = elements[x];
				if( element.addEventListener ) {
					element.addEventListener("click", this.checkOutEvent, false );
				} else if( element.attachEvent ) {
				  	element.attachEvent( "onclick", this.checkOutEvent );
				}
			}
			x=0;
			elements = getElementsByClassName('PieCart_empty');
			for( x=0;x<elements.length;x++) {
				element = elements[x];
				if( element.addEventListener ) {
					element.addEventListener("click", this.emptyEvent, false );
				} else if( element.attachEvent ) {
				  	element.attachEvent( "onclick", this.emptyEvent );
				}
			}
			return;
	};
	
	this.add = function() {
		newItem = new item();
		var x=0;
		for(x=0;x<arguments.length;x++){
			temp = arguments[x];
			data = temp.split('=');
			newItem.addValue(data[0],data[1]);
		}
		if(!newItem.getValue('')) {
			alert('Please provide an option for this item!');
			return false;
		}
		if(!newItem.getValue('price')) {
			alert('Oops! Destination Supplement is not a valid selection!');
			return false;
		}
		isnew = true;
		if(!newItem.getValue('quantity')) {
			newItem.addValue('quantity',1);
		}
		this.totalItems = this.totalItems + newItem.getValue('quantity');
		x=0;
		for( x=0;x < this.items.length;x++ ) {
			tempItem = this.items[x];
		if(tempItem.getValue('idno') == 'DS' && newItem.getValue('idno') == 'DS') {
				this.totalItems = this.totalItems - 1;
		alert('Oops! Remove old Destination Supplement before adding a new one!');
			return false;
				}
		if( tempItem.equalTo(newItem) ) {
				tempItem.addValue( 'quantity' , (parseInt(tempItem.getValue('quantity')) + parseInt(newItem.getValue('quantity')) ) );
				this.totalPrice = this.totalPrice + parseFloat( tempItem.getValue('price') );
				isnew = false;
			}
		}
		if( isnew ) {
			this.items[this.items.length] = newItem;
			this.totalPrice = this.totalPrice + parseFloat(newItem.getValue('price'));
		}
		this.updateCookie();
		this.updatePageElements();
		return;
	};
	
	this.addItem = function(newItem) {
		var x=0;
		for(x=0;x<this.items.length;x++) {
			var tempItem = this.items[x];
			if( tempItem.equalTo(newItem) ){
				tempItem.addValue('quantity', parseInt(newItem.getValue('quantity')) + parseInt(tempItem.getValue('quantity')) );
				this.totalItems = this.totalItems + parseInt(newItem.getValue('quantity'));
				this.totalPrice = this.totalPrice + parseInt(newItem.getValue('quantity'))*parseFloat(newItem.getValue('price'));
				return;
			}
		}
		this.items[this.items.length] = newItem;
		this.totalItems = this.totalItems + parseInt(newItem.getValue('quantity'));
		this.totalPrice = this.totalPrice + parseInt(newItem.getValue('quantity'))*parseFloat(newItem.getValue('price'));
		return;
	};

	this.updateCookie = function () {
		cookieString = String(this.totalItems) + "&" + String(this.totalPrice);
		x=0;
		for(x=0;x<this.items.length;x++ ) {
			tempItem = this.items[x];
			cookieString = cookieString + "&" + tempItem.cookieString();
		}
		createCookie("PieCart", cookieString, 30 );
	}

	this.empty = function () {
		this.items = new Array();
		this.totalItems = 0;
		this.totalPrice = 0.00;
		this.updateCookie();
		this.updatePageElements();
		return false;
	};

	this.deleteItem = function( item ) {  
		found = false;
		var temp = new Array();
		for(x=0; x < this.items.length;x++ ) {
			tempItem = this.items[x];		
			if( tempItem.equalTo(item) ) {
				found = true;
				this.totalItems = this.totalItems - parseFloat(tempItem.getValue('quantity'));
			}
			if( found ) {
				if( x < ( this.items.length - 1 ) ) {
					temp[x] = this.items[x+1];
				} 
			} else {
				temp[x] = this.items[x];
			}
		}
		this.items = temp;
		this.updateCookie();
		this.updatePageElements();
		return false;
	};

	this.options = function() {
		var x=0;
		for(x=0;x<this.items.length;x++) {
			var temp = this.items[x];
			if( temp.optionList() ) {
				return true;
			}
		}
		return false;
	};

	this.updatePageElements = function() {
		var x=0,element,elements = getElementsByClassName('PieCart_total');
		for( x=0;x<elements.length;x++) {
			element = elements[x];
			element.innerHTML = this.returnTotalPrice();
		}
		x=0;
		elements = getElementsByClassName('PieCart_quantity');
		for( x=0;x<elements.length;x++) {
			element = elements[x];
			element.innerHTML = String(this.totalItems);
		}
		elements = getElementsByClassName('PieCart_items');
		for( x=0;x<elements.length;x++) {
			cartTable = elements[x];
			newRow = document.createElement('tr');
			var x=0,i=0;

			while (cartTable.childNodes[0]) {
				cartTable.removeChild(cartTable.childNodes[0]);
			}

			for( x=0;x<this.ItemColumns.length;x++) {
				if( this.ItemColumns[x] ) {
					tempCell = document.createElement('td');
					tempCell.innerHTML = '&nbsp; ' + this.ItemColumns[x] + ' &nbsp;';
					newRow.appendChild(tempCell);
				}
			}
			newRow.className = "cartHeaders";
			cartTable.appendChild(newRow);

			x=0;
			for( x=0;x<this.items.length;x++ ) {
				tempItem = this.items[x];
				newRow = document.createElement('tr');
				i=0;
				for(i=0;i<this.ItemColumns.length;i++) {
					tempCell = document.createElement('td');
					if( this.ItemColumns[i] == 'ID' ) {
						if( tempItem.getValue('idno') ) {
							tempCell.innerHTML =  tempItem.getValue('idno');
						}
					}
					if( this.ItemColumns[i] == 'Name' ) {
						tempCell.innerHTML = tempItem.getValue('name');
					} else if (	this.ItemColumns[i] == 'Price' ) {
						tempCell.innerHTML = this.returnFormattedPrice( tempItem.getValue('price'));
					} else if ( this.ItemColumns[i] == 'Options' && this.options() ) {
						tempCell.innerHTML =  tempItem.optionList ();
					} else if (	this.ItemColumns[i] == 'Quantity' ) {
						tempCell.innerHTML = '<input type="text" size="6" onblur="PieCart.updateQuantity(' + tempItem.functionString() +',\'new_quantity=\' + this.value);return false;"value="' + tempItem.getValue('quantity') + '" />';
					} else if (	this.ItemColumns[i] == 'Total' ) {
						tempCell.innerHTML = this.returnFormattedPrice( tempItem.getValue('quantity')* tempItem.getValue('price'));
					} else if (	this.ItemColumns[i] == 'Delete' ) {
						tempCell.innerHTML = '<input type="image" src="images/delbut.gif" alt="Delete" onClick="PieCart.updateQuantity(' + tempItem.functionString() +',\'new_quantity=\' + 0);return false;" />';
					}
					newRow.appendChild(tempCell);
				}
				cartTable.appendChild(newRow);
			}

			newRow = document.createElement('tr');
			tempCell = document.createElement('td');
			tempCell.innerHTML = '<b>Totals<b/>';			
			newRow.appendChild(tempCell);
			tempCell = document.createElement('td');			
			newRow.appendChild(tempCell);			
			tempCell = document.createElement('td');
			newRow.appendChild(tempCell);
			tempCell = document.createElement('td');
			newRow.appendChild(tempCell);			
			tempCell = document.createElement('td');			
			tempCell.innerHTML = String(this.totalItems);
			newRow.appendChild(tempCell);
			tempCell = document.createElement('td');
			tempCell.innerHTML = this.returnTotalPrice();
			newRow.appendChild(tempCell);
			tempCell = document.createElement('td');
			tempCell.innerHTML = '<img border="0" src="images/upbut.gif" alt="Update">';			
			newRow.appendChild(tempCell);
			cartTable.appendChild(newRow);
		}
		return false;	
	};
 
	this.returnTotalPrice = function() {
		return this.returnFormattedPrice( this.totalPrice );
	};

	this.returnFormattedPrice = function( price ) {
		temp = Math.round(price*100);
		change = String(temp%100);
		if( change.length == 0) {
			change = "00";
		} else if( change.length == 1) {
			change = "0" + change;
		}
		temp = String(Math.floor(temp/100));
		return temp + "." + change;
	};
	
	this.updateQuantity = function() {
		newItem = new item();
		x=0;
		for(x=0;x<arguments.length;x++){
			temp = arguments[x];
			data = temp.split('=');
			if( data[0] == 'new_quantity') {
				var new_quantity = data[1];
			} else {
				newItem.addValue(data[0],data[1]);
			}
		}
		newQuan = new_quantity - newItem.getValue('quantity');
		newItem.addValue('quantity', newQuan );
		this.addItem(newItem);
		if( new_quantity < 1 ) {
			this.deleteItem( newItem );
			return;
		}
		this.updateCookie();
		this.updatePageElements();
		return false;
	}

	this.checkOut = function() { 
		if( this.totalItems == 0 ){
			alert("Your cart is empty!");
			return false;
		}
		if( this.totalPrice < this.minOrder ){
			alert("Sorry! Your Cart Total is less than the minimum order value.");
			return false;
		}
		if(this.ds == 1 && tempItem.getValue('idno') != 'DS') {
			alert('Please select your Destination Supplement before visiting the Checkout!');
			return false;
		}
		if( this.totalPrice <= this.threshA ){
			this.postage = 0 + this.postageA;
		}
		if( this.totalPrice > this.threshA && this.totalPrice <= this.threshB ){
			this.postage = 0 + this.postageB;
		}
		if( this.totalPrice > this.threshB ){
			this.postage = 0 + this.postageC;
		}
		var winpar = "scrollbars,location,resizable,status";
		var i,j=0,des,counter;
		var strn  = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart" +
		        	"&upload=1" +
					"&business=" + this.userBusiness +
		  			"&shipping=" + this.postage +
					"&cancel_return=" + this.cancel +
					"&return=" + this.success +
					"&currency_code=GBP" +
					"&lc=GB";		
		counter = 0;
		for (counter = 0; counter < this.items.length; counter++) { 
			tempItem = this.items[counter];
			j = counter + 1; 
			strn = strn + 	"&item_name_"    + j + "=" + tempItem.getValue('name') +
							"&item_number_"  + j + "=" + j +
		                	"&quantity_"     + j + "=" + tempItem.getValue('quantity') +
		                	"&amount_"       + j + "=" + this.returnFormattedPrice(tempItem.getValue('price') ) +
		      				"&no_shipping_"  + j + "=" + "0" +
							"&no_note_"   	 + j + "=" + "1";
			if( tempItem.optionList() ) {
				strn = strn + "&on0_"		+ j + "=" + "Options" +
				 			  "&os0_"		+ j + "=" + tempItem.optionList();
			}			
				
		}
		window.open (strn, "paypal", winpar);
		return false;
	};
}

function trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

function checkEmail(email)
{	
	
  var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
  
  if(pattern.test(email)) {         
	return true;
  } else {   
	return false; 
  }

}

function submitform()
{

  var name_element = document.getElementById('txt_name');
  var email_element = document.getElementById('txt_email');  
  var address1_element = document.getElementById('txt_address1');
  var address2_element = document.getElementById('txt_address2');
  var address3_element = document.getElementById('txt_address3');
  var zip_element = document.getElementById('txt_zip');
  var country_element = document.getElementById('txt_country');
  var telephone_element = document.getElementById('txt_tel');
  var mobile_element = document.getElementById('txt_mob');
  var q1_element = document.getElementById('txt_q1');
  var q2_element = document.getElementById('txt_q2');
  var droplist_element = document.getElementById('slt_droplist');
  var message_element = document.getElementById('tbox_question');
  
  var name = trim(name_element.value); 
  var email = trim(email_element.value);
  var address1 = trim(address1_element.value);  
  var address2 = trim(address2_element.value);
  var address3 = trim(address3_element.value);
  var zip = trim(zip_element.value);
  var country = trim(country_element.value);
  var telephone = trim(telephone_element.value);
  var mobile = trim(mobile_element.value);
  var q1 = trim(q1_element.value);
  var q2 = trim(q2_element.value);
  var droplist = trim(droplist_element.value);
  var message = trim(message_element.value);
  
  var error_message = 'The following fields must be completed: \n\n';
  
  var error_flag = false;  

  if(name == '') {
	  error_message += 'Name: Please enter a valid name\n';
	  error_flag = true;
  } 

  if(!checkEmail(email)) {
	  error_message += 'Email: Please enter a valid address\n';
	  error_flag = true;
  }  

  if(address1 == '') {
	  error_message += 'Address Line 1: Please enter your details\n';
	  error_flag = true;
  }
  
  if(address2 == '') {
	  error_message += 'Address Line 2: Please enter your details\n';
	  error_flag = true;
  }
  
  if(address3 == '') {
	  error_message += 'Address Line 3: Please enter your details\n';
	  error_flag = true;
  }
  
  if(zip == '') {
	  error_message += 'Please enter your ZIP Code\n';
	  error_flag = true;
  }
  
  if(country == '') {
	  error_message += 'Please enter your Country\n';
	  error_flag = true;
  }

  if(telephone == '') {
	  error_message += 'Telephone: Please enter your details\n';
	  error_flag = true;
  }

  if(mobile == '') {
	  error_message += 'Mobile: Please enter your details\n';
	  error_flag = true;
  }

  if(q1 == '') {
	  error_message += 'Q1: Please enter your details\n';
	  error_flag = true;
  }

  if(q2 == '') {
	  error_message += 'Q2: Please enter your details\n';
	  error_flag = true;
  }

  if(droplist == '') {
	  error_message += 'Drop List: Please make a selection\n';
	  error_flag = true;
  }

  if(message == '') {
	  error_message += 'Message Box: Please make an entry\n';
	  error_flag = true;
  }
  
  if(error_flag) {
	  alert(error_message);
  } else {
	  document.PieCartForm.submit();
  }

}

function item () {
	this.names	= new Array();
	this.values	= new Array();

	this.addValue = function(name,value) {
		if( this.names.length != this.values.length ) {
			alert("name and value array lengths do not match for this item!");
			return false;
		}
		found = false;
		var a=0;
		for(a=0;a<this.names.length;a++) {
			if( this.names[a] == name ) {
				this.values[a] = value;
				return;
			}
		}
		if( !found ) {
			this.names[this.names.length]	= name;
			this.values[this.values.length]	= value;
		}
		return;
	};

	this.getValue = function(name) {
		var g=0;
		for(g=0;g<this.names.length;g++) {
			if(name==this.names[g]) {
				return this.values[g];
			}
		}
		return null;
	};

	this.equalTo = function(item) {
		if(this.getSize() != item.getSize() ) {
			return false;
		} 
		var q=0;
		for(q=0;q<this.names.length;q++) {
			if( this.names[q] != 'quantity' && (item.getValue(this.names[q]) != this.values[q]) ) {
				return false;
			}
		}
		return true;
	};

	this.getSize = function() {
		return this.names.length;
	};
	
	this.cookieString = function() {
		returnString = '';
		var i=0;
		returnString = this.names[i] + "=" + this.values[i];
		i=1;
		for(i=1;i<this.names.length;i++) {
			returnString = returnString + "," + this.names[i] + "=" + this.values[i];
		}
		return returnString;
	};
	
	this.functionString = function() {
		returnString = '\'';
		var f=0;
		returnString = '\'' + this.names[f] + "=" + this.values[f];
		f=1;
		for(f=1;f<this.names.length;f++) {
			returnString = returnString + "','" + this.names[f] + "=" + this.values[f];
		}
		returnString = returnString + '\'';
		return returnString;
	}
	
	this.optionList = function() {
		returnString = '';
		if( this.getSize() < 4 ) {
			return null;
		}
		var o=0;
		for(o=0;o<this.names.length;o++) {
			if(this.names[o] != 'quantity' && this.names[o] != 'price' && this.names[o] != 'name' && this.names[o] != 'idno') {
				returnString = returnString + this.names[o] + ':' + this.values[o] + ', ';
			}
		}
		while(returnString.charAt(returnString.length-1)==',' || returnString.charAt(returnString.length-1)==' ' || returnString.charAt(returnString.length)==':'){
			returnString = returnString.substring(0,returnString.length-1);
		}
		return returnString;
	};
}

//*************************************************************************************************
// Thanks to Peter-Paul Koch for these cookie functions! (http://www.quirksmode.org/js/cookies.html)
//*************************************************************************************************
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//*************************************************************************************************
/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};
//*************************************************************************************************

function createCart(){
	PieCart.initialize();
	return;
}

window.onload = createCart;
