// Detect Browser Settings
var Browser = {
	appName: navigator.appName,
	appVersion: parseInt(navigator.appVersion),
	userAgent: navigator.userAgent, 
	IE:     !!(window.attachEvent && !window.opera),
	IE6:	(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && 
				navigator.userAgent.toLowerCase().indexOf('opera') == -1 && 
				parseInt(navigator.appVersion) == 4 && 
				navigator.userAgent.toLowerCase().indexOf('msie 6.') != -1
			),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/),
	Height: function() {
		if(Browser.Gecko||Browser.WebKit)
			return window.innerHeight + window.scrollMaxY;
		else if(Browser.IE)
			return document.body.clientHeight-0;
		else if(Browser.Opera)
			return window.innerHeight + window.pageYOffset;
	},
	Width: function() {
		if(Browser.Gecko||Browser.WebKit)
			return window.innerWidth;
		else if(Browser.IE)
			return document.body.clientWidth;
		else if(Browser.Opera)
			return window.innerWidth;
	},
	ScrollY: function() {
		if(Browser.Gecko||Browser.WebKit)
			return window.pageYOffset;
		else if(Browser.IE)
			return screen.height;
		else if(Browser.Opera)
			return window.pageYOffset;
	}	
}

var URL = {
	specialChars: 
		Array(	'$',
			  	'&',
				'+',
				',',
				'/',
				':',
				';',
				'=',
				'?',
				'@',
				' ',
				'"',
				'<',
				'>',
				'#',
				'%',
				'{',
				'}',
				'|',
				'\\',
				'^',
				'~',
				'[',
				']',
				'`',
				'*',
				'.',
				'-',
				'\'',
				'!',
				'(',
				')',
				'™',
				'©',
				'®'),
	specialReplace:
		Array(	'%24',
				'%26',
				'%2B',
				'%2C',
				'%2F',
				'%3A',
				'%3B',
				'%3D',
				'%3F',
				'%40',
				'%20',
				'%22',
				'%3C',
				'%3E',
				'%23',
				'%25',
				'%7B',
				'%7D',
				'%7C',
				'%5C',
				'%5E',
				'%7E',
				'%5B',
				'%5D',
				'%60',
				'%2A',
				'%2E',
				'%2D',
				'%27',
				'%21',
				'%28',
				'%29',
				'%99',
				'%A9',
				'%AE')
};

String.prototype.ucWords = function() {
	var re = /\s/;
	var words = this.split(re);
	re = /(\S)(\S+)/;
	for (i = words.length - 1; i >= 0; i--) {
		re.exec(words[i]);
		words[i] = RegExp.$1.toUpperCase()
		+ RegExp.$2.toLowerCase();
	}
	return words.join(' ');
}

Object.prototype.isArray = function() {
	return (this.constructor.toString().indexOf('Array') != -1);
}

function addCharacter(target, char)
{
	//char = replaceChars(URL.specialChars, char, URL.specialReplace);
	$(target).value += char+' ';
}

/*
function replaceChars([array] needle (search term/s), [array] haystack (search stack), [array] replace (search replace))
*/
function replaceChars(needle, haystack, replace)
{
	// if replace and needle is array, used when encoding multiple characters for URL
	if(replace.isArray() && needle.isArray())
	{
		if(replace.length != needle.length)
			return '';
	}
	
	// Iterate through arrays
	if(haystack.isArray())
	{
		for(i=0;i<haystack.length;i++)
		{
			var str = '';
			for(k=0;k<haystack[i].length;k++)
			{
				var indicator = false;
				
				if(needle.isArray())
				{
					for(j=0;j<needle.length;j++)
					{
						if(haystack[i].charAt(k) == needle[j])
						{
							if(replace.isArray())
								str += replace[j];
							else
								str += replace;
							indicator = true;
						}
					}
				}
				else if(needle.length == 0) 
					return '';
				else
				{
					if(haystack[i].charAt(k) == needle)
					{
						str += replace;
						indicator = true;
					}
				}
				if(!indicator && haystack[i].charAt(k) != '')
					str += haystack[i].charAt(k);
			}
			haystack[i] = str;
		}
		
		return haystack;
	}
	else if(haystack.length == 0) 
		return '';
	else
	{
		var str = '';
		//alert(haystack +' - '+ typeof haystack);
		for(i=0;i<haystack.length;i++)
		{
			var indicator = false;
			if(needle.isArray())
			{
				for(k=0;k<needle.length;k++)
				{
					;
					if(haystack.charAt(i) == needle[k])
					{
						if(replace.isArray())
							str += replace[k];
						else
							str += replace;
						indicator = true;
					}
				}
			}
			else if(needle.length == 0)
				return '';
			else
			{
				if(haystack.charAt(i) == needle)
				{
					str+=replace;
					indicator = true;
				}
			}
			
			if(!indicator && haystack.charAt(i) != '')
				str += haystack.charAt(i);
		}
		return str;
	}	
}

function changeCategoriesList(object,target,url){
	var selected = object.options[object.selectedIndex].value;
	new ajax (url+selected, {update: $(target), onComplete: populateMenu});
	
	function populateMenu(request) {
		for(x=target.length;x>=0;x--){
			target[x] = null;
		}
		
		var re = new RegExp("(\<select(.*?)\>)(.*?)(\<\/select\>)","i");

		$(target).innerHTML = request.responseText;
		
		if($(target).outerHTML)
			$(target).outerHTML = $(target).outerHTML.replace(re, "$1"+request.responseText+"$4");
	}
}

function checkLimit(object, limit, target){
	if(limit==null)
		limit = 255;
	var str = ''+object.value.length;
	if(object.value.length > limit)
		object.value = object.value.substring(0,limit);
		
	str = object.value.length+' of '+limit+' characters';
	$(target).innerHTML = str;
}

function updateProduct(pid){
	var url = './_admin.product.php?a=update&pid='+pid+'&';
	var error = '';
	
	var cid = $('catList'); 				//SELECT
	var title = $('title');					//STRING
	var code = $('code');					//STRING
	var barcode = $('barcode');				//STRING
	var sdescription = $('sdescription');	//STRING
	var ldescription = $('ldescription');	//STRING
	var cost_au = $('cost_au');				//FLOAT
	var cost_nz = $('cost_nz');				//FLOAT
	var special_au = $('special_au');		//FLOAT
	var special_nz = $('special_nz');		//FLOAT
	var special = $('special');				//SELECT
	var whatsnew = $('whatsnew');			//SELECT
	var pack = $('pack');					//INT
	var item_au = $('item_au');				//FLOAT
	var item_nz = $('item_nz');				//FLOAT
	var stock = $('notinstock').checked==true?1:0;
	var keywords = $('searchkeywords');
	var clearance = $('clearance_fix');
	var clearance_au = $('clearance_au');
	var clearance_nz = $('clearance_nz');
	
	cid = cid.options[cid.selectedIndex].value;
	title = replaceChars(URL.specialChars, title.value, URL.specialReplace);
	code = replaceChars(URL.specialChars, code.value, URL.specialReplace);
	barcode = replaceChars(URL.specialChars, barcode.value, URL.specialReplace);
	sdescription = replaceChars(URL.specialChars, sdescription.value, URL.specialReplace);
	ldescription = replaceChars(URL.specialChars, ldescription.value, URL.specialReplace);
	cost_au = parseFloat(cost_au.value);
	cost_nz = parseFloat(cost_nz.value);
	item_au = parseFloat(item_au.value);
	item_nz = parseFloat(item_nz.value);
	special_au = parseFloat(special_au.value);
	special_nz = parseFloat(special_nz.value);
	special = parseInt(special.value);
	whatsnew = parseInt(whatsnew.value);
	pack = parseInt(pack.value);
	keywords = replaceChars(URL.specialChars, keywords.value, URL.specialReplace);
	clearance = parseInt(clearance.value);
	clearance_au = parseFloat(clearance_au.value);
	clearance_nz = parseFloat(clearance_nz.value);
	
	if(isNaN(cost_au)){cost_au = 0;error+='Cost AU must be a number ie. 23.75<br/>';}
	if(isNaN(cost_nz)){cost_nz = 0;error+='Cost NZ must be a number ie. 23.75<br/>';}
	if(isNaN(item_au)){item_au = 0;error+='Item AU must be a number ie. 23.75<br/>';}
	if(isNaN(item_nz)){item_nz = 0;error+='Item NZ must be a number ie. 23.75<br/>';}
	if(isNaN(special_au)){special_au = 0;error+='Special AU must be a number ie. 23.75<br/>';}
	if(isNaN(special_nz)){special_nz = 0;error+='Special NZ must be a number ie. 23.75<br/>';}
	if(isNaN(special)){special = 0;error+='Special must be a number ie. 1 = yes, 0 = no<br/>';}
	if(isNaN(whatsnew)){whatsnew = 0;error+='Whats New must be a number ie. 1 = yes, 0 = no<br/>';}
	if(isNaN(pack)){pack = 0;error+='Pack must be a whole number ie. 7<br/>';}
	if(error.length>0){
		var e = $('error');
		e.innerHTML = error;
	}else{
		url+= 'catid='+cid+'&title='+title+'&code='+code+'&barcode='+barcode+'&sdescription='+sdescription;
		url+= '&ldescription='+ldescription+'&cost_au='+cost_au+'&cost_nz='+cost_nz+'&item_au='+item_au;
		url+= '&item_nz='+item_nz+'&special_au='+special_au+'&special_nz='+special_nz+'&special='+special;
		url+= '&whatsnew='+whatsnew+'&pack='+pack+'&notinstock='+stock+'&keywords='+keywords+'&clearance='+clearance;
		url+= '&clearance_au='+clearance_au+'&clearance_nz='+clearance_nz;
		
		new ajax (url, {onComplete: updateFields});
	}
	
	function updateFields(request) {
		if(request.responseText.length>0)
		alert('Product Updated');
		
		var e = $('error');
		e.innerHTML = '<br/>';
		
		var p = $('prod_title');
		p.innerHTML = '<b>'+title.ucWords()+'</b>';
	}
}
function updateIdea(id){
	var url = './_admin.idea.php?a=update&id='+id+'&';
	var error = '';
	
	var code = $('code');					//STRING
	var title = $('title');					//STRING
	var description = $('description');		//STRING
	var ingredients = $('ingredients');		//STRING

	code = replaceChars(URL.specialChars, code.value, URL.specialReplace);
	title = replaceChars(URL.specialChars, title.value, URL.specialReplace);
	description = replaceChars(URL.specialChars, description.value, URL.specialReplace);
	ingredients = replaceChars(URL.specialChars, ingredients.value, URL.specialReplace);
	
	if(error.length>0){
		var e = $('error');
		e.innerHTML = error;
	}else{
		url+= 'code='+code+'&title='+title+'&description='+description+'&ingredients='+ingredients;
		
		new ajax (url, {onComplete: updateFields});
	}
	
	function updateFields(request) {
		if(request.responseText.length>0)
		alert('Idea Updated');
		
		var e = $('error');
		e.innerHTML = '<br/>';
		
		var p = $('idea_title');
		p.innerHTML = '<b>'+title.ucWords()+'</b>';
	}
}
	
function newProduct(bool) {
	bool = bool==true?true:false;
	var conf = confirm('Create a new product?'+(bool?' You will lose unsaved changes!':''));
	if(conf){
		var url = './_admin.product.php?a=new';
		new ajax (url, {onComplete: result});
	}
	
	function result(response) {
		if(parseInt(response.responseText)>0)
			window.location = './_admin.catalogue.php?pid='+response.responseText;
		else
			alert('Failure creating new product!');
	}
}

function newIdea(bool) {
	bool = bool==true?true:false;
	var conf = confirm('Create a new idea?'+(bool?' You will lose unsaved changes!':''));
	if(conf){
		var url = './_admin.idea.php?a=new';
		new ajax (url, {onComplete: result});
	}
	
	function result(response) {
		if(parseInt(response.responseText)>0)
			window.location = './_admin.ideas.php?id='+response.responseText;
		else
			alert('Failure creating new idea!');
	}
}

function deleteProduct(pid) {
	if(parseInt(pid)>0){
		var conf = confirm('Delete this product? This cannot be reversed!');
		if(conf){
			var url = './_admin.product.php?a=remove&p='+pid;
			new ajax (url, {onComplete: result});
		}
	}
	
	function result(response) {
		var txt = response.responseText;
		if(txt=='true'||txt=='false'){
			if(txt=='true'){
				alert('Product successfully removed!');
				window.location = './_admin.catalogue.php';
			}else{
				alert('Product could not be deleted!');
			}
		}
	}
}

function deleteIdea(id) {
	if(parseInt(id)>0){
		var conf = confirm('Delete this idea? This cannot be reversed!');
		if(conf){
			var url = './_admin.idea.php?a=remove&p='+id;
			new ajax (url, {onComplete: result});
		}
	}
	
	function result(response) {
		var txt = response.responseText;
		if(txt=='true'||txt=='false'){
			if(txt=='true'){
				alert('Idea successfully removed!');
				window.location = './_admin.ideas.php';
			}else{
				alert('Idea could not be deleted!');
			}
		}
	}
}

function doProductSearch() {
	var data = $('searchData');
	var type = $('searchType');
	
	if(data.value.length>0){
		var url = './catalogue.php?a=search&data='+data.value+'&type='+type.options[type.selectedIndex].value;
		window.location = url;
	}else{
		alert('You need to enter a search string!');
	}
}

function doAdminSearch() {
	var data = $('searchData');
	var type = $('searchType');
	
	if(data.value.length>0){
		var url = './_admin.catalogue.php?a=search&data='+data.value+'&type='+type.options[type.selectedIndex].value;
		window.location = url;
	}else{
		alert('You need to enter a search string!');
	}
}

function doAdminUserSearch() {
	var data = $('searchData');
	var type = $('searchType');
	
	if(data.value.length>0){
		var url = './_admin.users.php?a=search&data='+data.value+'&type='+type.options[type.selectedIndex].value;
		window.location = url;
	}else{
		alert('You need to enter a search string!');
	}
}

function removeImage(pid,bool,object){
	if(parseInt(pid)>0){
		var conf = confirm('Do you really want to remove the product '+(bool==true?'thumbnail ':'')+'image?');
		if(conf){
			var url = './_admin.product.php?a=deleteimage&thumb='+bool+'&pid='+pid;
			new ajax (url, {onComplete: result});
			object.disabled=true;
		}
	}
	
	function result(response){
		window.location = window.location;
	}
}

function removeIdeaImage(id,bool,object){
	if(parseInt(id)>0){
		var conf = confirm('Do you really want to remove the idea '+(bool==true?'thumbnail ':'')+'image?');
		if(conf){
			var url = './_admin.idea.php?a=deleteimage&thumb='+bool+'&id='+id;
			new ajax (url, {onComplete: result});
			object.disabled=true;
		}
	}
	
	function result(response){
		window.location = window.location;
	}
}

function onLoadCheckSize(){
	var short = $('sdescription');
	var long = $('ldescription');
	
	var targetShort = $('sdesc');
	var targetLong = $('ldesc');
	
	targetShort.innerHTML = short.value.length + ' of 30 characters';
	targetLong.innerHTML = long.value.length + ' of 255 characters';
}

function moveCategory(object,catid){
	if(parseInt(catid)>0){
		var conf = confirm('Move this category?');
		if(conf){
			var target = object.options[object.selectedIndex].value;
			var url = './_admin.ranges.php?a=move&cid='+catid+'&target='+target;
			new ajax(url, {onComplete: result});
		}
	}
	
	function result(response){
		window.location = './_admin.ranges.php';
	}
}

function deleteCategory(catid){
	if(parseInt(catid)>0){
		var conf = confirm('Do you really wish to delete this category? This cannot be reversed!');
		if(conf){
			var url = './_admin.ranges.php?a=deletecat&cid='+catid;
			new ajax(url, {onComplete: result});
		}
	}
	
	function result(response){
		var text = parseInt(response.responseText);
		if(text==1){
			alert('Category could not be removed because there are still products within this category!\nMake sure you assign these products to another category before continuing!');
		}else if(text==2){
			alert('Category could bot be removed because there are child categories attached to this category!\nMake sure you remove or assign these categories to another range or category before continuing!');
		}else if(text==3){
			alert('Could not delete from database!');
		}else if(text==4){
			alert('Category successfully removed!');
			window.location = './_admin.ranges.php';
		}
	}
}

function newCategory(){
	var conf = confirm('Create a new category?');
	if(conf){
		var url = './_admin.ranges.php?a=new&parent=0';
		new ajax (url, {onComplete: result});
	}
	
	function result(response) {
		if(parseInt(response.responseText)>0){
			window.location = './_admin.ranges.php?a=edit&cid='+parseInt(response.responseText);
		}
	}
}

function editCategory(catid){
	if(parseInt(catid)>0){
		var conf = confirm('Edit category?');
		if(conf){
			var url = './_admin.ranges.php?a=edit&cid='+parseInt(catid);
			window.location = url;
		}
	}
}

function updateAdminOrder(orderid){
	if(parseInt(orderid)>0){
		var status = $('statusList').options[$('statusList').selectedIndex].value;
		var cost = $('freightCost').value;
		var url = './_admin.order.php?a=update&orderid='+parseInt(orderid)+'&cost='+cost+'&status='+status;
		
		new ajax(url, {onComplete: result});
	}
	
	function result(response){
		txt = response.responseText;
		if(txt=='true'){
			alert('Order details updated!');
			window.location = window.location;
		}else{
			alert('Order details could not be updated!');
		}
	}
}

function deleteAdminOrder(orderid){
	if(parseInt(orderid)>0){
		var conf = confirm('Are you sure you want to delete this order?\nThis cannot be reversed!');
		if(conf){
			var url = './_admin.order.php?a=delete&orderid='+orderid;
			
			new ajax(url, {onComplete: result});
		}
	}
	
	function result(response){
		if(response.responseText=='true'){
			alert('Order successfully removed!');
			var url = './_admin.orders.php';
			window.location = url;
		}else{
			alert('Order could not be removed!');
		}
	}
}

function printOrder(orderid,bool){
	if(parseInt(orderid)>0){
		bool = bool=='true'?true:false;
		var conf = confirm('Do you want to '+(bool==true?'display':'print')+' this order?');
		if(conf){
			var url = './print.order.php?orderid='+orderid;
			r = window.open(url,'_blank','height=700,width=740,menubar=no,scrollbars=yes,status=no,toolbar=no,titlebar=no,resizable=no');
			r.focus();
		}
	}
}

function addCartItem(title,productid,qty) {
	if(parseInt(productid)>0){
		var url = './catalogue.php?a=addtocart&p='+productid+'&qty='+$(qty).value;
		new ajax(url, {onComplete: result});
	}
	
	function result(response){
		if(response.responseText=='fail'){
			alert('Could not add '+title+' to shopping cart.\nPlease make sure you have entered a quantity above zero.');
		}else{
			alert(title+' added!');
			window.location = window.location;
		}
	}
}

function deleteCartItem(productid,object){
	if(parseInt(productid)>0){
		var conf = confirm('Do you really wish to remove this product from your shopping cart?');
		if(conf){
			var url = './cart.php?a=remove&productid='+productid;
			
			new ajax(url, {onComplete: result});
			remRow(object);
		}
	}
	
	function result(response){
		var txt = response.responseText;
		if(txt=='true'){
			alert('Product successfully removed from cart!');
			window.location = window.location;
		}else{
			alert('Product was not removed from cart!');
		}
	}
	
	function remRow(object){
		if(!object)
			return;
		
		object.parentNode.removeChild(object);
	}
}

function doQtyBox(object,productid,qty,bool){
	bool = bool==true?true:false;
	
	if(parseInt(productid)>0&&parseInt(qty)>0){
		if(bool){
			object.innerHTML = qty;
			new ajax('./cart.php?a=edit&productid='+productid+'&qty='+qty, {onComplete: null});
			new ajax('./cart.php?a=getIP&productid='+productid+'&qty='+qty, {onComplete: updateItemPrice});
		}else{
			if(parseInt(object.innerHTML)==parseInt(qty)){
				var input = "<input type='text' id='"+parseInt(productid)+"qty' value='"+parseInt(qty)+"' ";
				input += "style='width:20px;border:1px solid #000;font:10px verdana,sans,helvetica;color:#000;' onfocus='this.select()' ";
				input += "onKeyDown='if (event.keyCode ==13) { doQtyBox(this.parentNode,"+productid+",this.value,true); } ' ";
				input += "alt=\"Press enter once you are finished modifying this field\" title=\"Press enter once you are finished modifying this field\" />";
				object.innerHTML = input;
			}
		}
	}
	
	function updateItemPrice(response){
		window.location = './cart.php';
	}
}

function saveCart() {
	var conf = confirm('Do you wish to save your cart?\n\nNo personal information will be saved.');
	if(conf){
		new ajax('./cart.php?a=save', {onComplete: result});
	}
	
	function result(response){
		if(response.responseText=='true')
			alert('Cart information successfully saved!\n\nYour cart information can be loaded the next time you login.');
		else
			alert('Could not save cart information.');
	}
}

function cancelCart() {
	var conf = confirm('Do you wish to discard all items?\n\nYou cannot reverse this action.');
	if(conf){
		new ajax('./cart.php?a=cancelcart', {onComplete: result});
	}
	
	function result(response){
		if(response.responseText=='true'){
			alert('Your items have been discarded');
			window.location = './catalogue.php?rid=2';
		}else{
			alert('Your cart could not be cancelled.');
		}
	}
}

function cartCheckout() {
	var conf = confirm('Do you wish to proceed?\nYour order information will be sent to you via email.');
	var inst = $('instructions').value;
	if(conf){
		window.location = './cart.php?a=confirmcheckout&instructions='+inst;
	}
}

function cartPrint() {
	var url = './cart.php?a=print';
	var r = window.open(url,'_blank','height=700,width=700,menubar=no,status=no,toolbar=no,titlebar=no,resizable=no');
	r.focus();
}

function newUser() {
	var url = './_admin.user.php?a=new';
	new ajax(url, {onComplete: result});
	
	function result(request){
		var txt = request.responseText.toString();
		if(txt=='false'){
			alert('Could not create a new user!\nThere is already a user account with the same login (email) details!');
		}else if(txt.indexOf(':') == -1){
			alert('User could not be created!');
		}else{
			var r = txt.split(':',2);
			alert('User successfully created!\nYou can create a password for the user once you begin editing their details.');
			window.location = './_admin.users.php?uid='+parseInt(r[0]);
		}
	}
}

function deleteUser(uid,back) {
	back = back==true||back=='true'?true:false;
	if(parseInt(uid)>0){
		var url = './_admin.user.php?a=delete&uid='+uid;
		new ajax(url, {onComplete: result});
	}
	
	function result(request){
		if(request.responseText=='true'){
			alert('User deleted!');
			if(back)
				window.location = './_admin.users.php';
		}else{
			alert('User could not be deleted!');
		}
	}
}

function updateUser(uid){
	if(parseInt(uid)>0){
		var url = './_admin.user.php?a=update&uid='+uid;
		
		var username = replaceChars(URL.specialChars, $('username').value, URL.specialReplace);		//STRING
		var client = replaceChars(URL.specialChars, $('client').value, URL.specialReplace);			//STRING
		var accno = replaceChars(URL.specialChars, $('accno').value, URL.specialReplace);			//INTEGER
		var country = $('country');																	//SELECT
		var firstname = replaceChars(URL.specialChars, $('firstname').value, URL.specialReplace);	//STRING
		var lastname = replaceChars(URL.specialChars, $('lastname').value, URL.specialReplace);		//STRING
		var email = replaceChars(URL.specialChars, $('email').value, URL.specialReplace);			//STRING
		var web = replaceChars(URL.specialChars, $('web').value, URL.specialReplace);				//STRING
		var desc = replaceChars(URL.specialChars, $('desc').value, URL.specialReplace);				//STRING
		var tele = replaceChars(URL.specialChars, $('tele').value, URL.specialReplace);				//STRING
		var fax = replaceChars(URL.specialChars, $('fax').value, URL.specialReplace);				//STRING
		var mobile = replaceChars(URL.specialChars, $('mobile').value, URL.specialReplace);			//STRING
		var admin = $('admin');					//1 or 0
		var discount = parseFloat($('discount').value);
		var street = replaceChars(URL.specialChars, $('street').value, URL.specialReplace);
		var suburb = replaceChars(URL.specialChars, $('suburb').value, URL.specialReplace);
		var pcode = parseInt($('pcode').value);
		var state = $('state');
		var password = $('password').value;
		var password2 = $('password2').value;
		var crystal = $('crystal').options[$('crystal').selectedIndex].value;
		var sandylion = $('sandylion').options[$('sandylion').selectedIndex].value;
		
		discount = discount>1?1:discount;
		discount = discount<0?0:discount;
		
		country = country.options[country.selectedIndex].value;
		admin = admin.options[admin.selectedIndex].value;
		state = state.options[state.selectedIndex].value;
		
		url += '&username='+username;
		url += '&client='+client;
		url += '&accno='+accno;
		url += '&country='+country;
		url += '&firstname='+firstname;
		url += '&lastname='+lastname;
		url += '&email='+email;
		url += '&website='+web;
		url += '&description='+desc;
		url += '&tele='+tele;
		url += '&fax='+fax;
		url += '&mobile='+mobile;
		url += '&admin='+admin;
		if(!isNaN(discount)){url += '&discount='+discount;}
		if(!isNaN(pcode)){url += '&pcode='+pcode;}
		url += '&street='+street;
		url += '&suburb='+suburb;
		url += '&state='+state;
		url += '&crystal='+crystal;
		url += '&sandylion='+sandylion;
		if(password.length>5&&password2.length>5&&password==password2){
			url += '&password='+password;
			url += '&password2='+password2;
		}
		new ajax(url, {onComplete: result});
	}
	
	function result(request){
		if(request.responseText == 'true'){
			alert('User updated!');
		}else if(request.responseText == '1'){
			alert('User updated!\nYou need to log in again because of your email or password change');
			window.location = './_login.php';
		}else{
			alert('User was not updated!\nCheck that you have entered correct data into the input fields,'
				  +'\nand entered email addresses correctly eg. user@some.net');
		}
	}
}

function updatePassword(){
	var url = './_profile.php?a=update';
	
	var oldpass = $('oldpass').value;
	var password = $('password').value;
	var password2 = $('password2').value;
	
	url += '&oldpass='+oldpass;
	if(password.length>5&&password2.length>5&&password==password2){
		url += '&password='+password;
		url += '&password2='+password2;
	}
	new ajax(url, {onComplete: result});
	
	function result(request){
		if(request.responseText == '1'){
			alert('Password updated!\nYou will now be redirected to the login page');
			window.location = './_login.php';
		}else{
			alert('Could not update your password!\nMake sure the password you entered matches your current password');
		}
	}
}

function generatePass(uid,url){
	if(parseInt(uid)>0){
		url += uid;
		var conf = confirm('Are you sure you want to generate a new password?');
		if(conf)
			new ajax(url, {onComplete: result})
	}
	
	function result(request){
		var txt = request.responseText.toString();
		
		if(txt=='1'){
			alert('Password successfully generated.'
				  +'\nThe new password has been emailed to the users email address.');
		}else if(txt=='2'){
			alert('Your password has been successfully changed.'
				  +'\nYour new password has been emailed to you.\nYou will now be logged out.');
			window.location = './_login.php';
		}else if(txt=='false'){
			alert('A new password could not be generated!');
		}
			
	}
}

function addToDescription(insert, obj, limit, target) {
	$(obj).value += insert;
	checkLimit($(obj), limit, target);
}

function changeInStock(obj, pid)
{
	var imgYes = 'images/list_cross.gif';
	var imgNo = 'images/list_tick.gif';
	
	if(parseInt(pid)>0)
	{
		var url = '_admin.catalogue.php?a=changeStock&pid='+pid;
		new ajax(url, {onComplete: result});
	}
	
	function result(response)
	{
		var txt = response.responseText;
		
		if(txt == 'true') 
		{
			$(obj).src = imgYes;
			alert('Product has been successfully updated! Product is now marked as unavailable!');
		}
		else if(txt == 'false')
		{
			$(obj).src = imgNo;
			alert('Product has been successfully updated! Product is now marked as available!');
		}
		else
			alert('Product could not be updated!');
	}
}

function changeWhatsNew(obj, pid)
{
	var imgYes = 'images/list_tick.gif';
	var imgNo = 'images/list_cross.gif';
	
	if(parseInt(pid)>0)
	{
		var url = '_admin.catalogue.php?a=changeNew&pid='+pid;
		new ajax(url, {onComplete: result});
	}
	
	function result(response)
	{
		var txt = response.responseText;
		
		if(txt == 'true') 
		{
			$(obj).src = imgYes;
			alert('Product has been successfully updated! Product is now marked as Whats New!');
		}
		else if(txt == 'false')
		{
			$(obj).src = imgNo;
			alert('Product has been successfully updated! Product is now marked as not new!');
		}
		else
			alert('Product could not be updated!');
	}
}

function exeBroadcast(broadcast,mode){
	if(parseInt(broadcast)>0){
		var url = './_admin.broadcast.run.php';
		var broadcast = broadcast;
		var mode = mode;
		
		url += '?broadcast='+broadcast;
		url += '&mode='+mode;
		alert('Sending Broadcast, you will recieve an email confirmation when complete.');
		new ajax(url, {onComplete: result});
	}
	
	function result(request){
		alert('Broadcast Complete');
	}
}
