// 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 sdescription = $('sdescription');	//STRING
	var ldescription = $('ldescription');	//STRING
	var totalcost = $('totalcost');		//FLOAT
	
	cid = cid.options[cid.selectedIndex].value;
	title = replaceChars(URL.specialChars, title.value, URL.specialReplace);
	sdescription = replaceChars(URL.specialChars, sdescription.value, URL.specialReplace);
	ldescription = replaceChars(URL.specialChars, ldescription.value, URL.specialReplace);
	totalcost = parseFloat(totalcost.value);
	
	if(isNaN(totalcost)){totalcost = 0;error+='Cost must be a number ie. 23.75<br/>';}
	if(error.length>0){
		var e = $('error');
		e.innerHTML = error;
	}else{
		url+= 'catid='+cid+'&title='+title+'&sdescription='+sdescription+'&ldescription='+ldescription;
		url+= '&totalcost='+totalcost;
		
		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 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 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 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 onLoadCheckSize(){
	var short = $('sdescription');
	
	var targetShort = $('sdesc');
	
	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.categories.php?a=move&cid='+catid+'&target='+target;
			new ajax(url, {onComplete: result});
		}
	}
	
	function result(response){
		window.location = './admin.categories.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.categories.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.categories.php';
		}
	}
}

function newCategory(){
	var conf = confirm('Create a new category?');
	if(conf){
		var url = './admin.categories.php?a=new&parent=0';
		new ajax (url, {onComplete: result});
	}
	
	function result(response) {
		if(parseInt(response.responseText)>0){
			window.location = './admin.categories.php?a=edit&cid='+parseInt(response.responseText);
		}
	}
}

function editCategory(catid){
	if(parseInt(catid)>0){
		var conf = confirm('Edit category?');
		if(conf){
			var url = './admin.categories.php?a=edit&cid='+parseInt(catid);
			window.location = url;
		}
	}
}

function updateAdminOrder(orderid)
{
	if(parseInt(orderid) > 0 )
	{
		var status = $('statusList').options[$('statusList').selectedIndex].value;
		var url = './admin.order.php?a=update&orderid='+orderid+'&status='+status;
		new ajax(url, {onComplete: result});
	}
	
	function result(response)
	{
		if(response.responseText == 'true')
			alert('Order status updated');
		else
			alert('Could not update order status');
	}
}

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 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 cartCheckout() {
	var url = './cart.php?a=confirmcheckout&';
	var error = '';
	
	var conf = confirm('Are you sure you wish to proceed?\n');
	var first_name = $('first_name').value;
	var last_name = $('last_name').value;
	var address = $('address').value;
	var suburb = $('suburb').value;
	var state = $('state').value;
	var postcode = $('postcode').value;
	var country = $('country').value;
	var phone = $('phone').value;
	var email = $('email').value;
	var card = $('card').value;
	var card_name = $('card_name').value;
	var card_expiry = $('card_expiry').value;
	var card_type = $('card_type').value;
	var instructions = $('instructions').value;
	
	url+= 'first_name='+first_name+'&last_name='+last_name+'&address='+address+'&suburb='+suburb;
	url+= '&state='+state+'&postcode='+postcode+'&country='+country+'&phone='+phone;
	url+= '&email='+email+'&card='+card+'&card_name='+card_name+'&card_type='+card_type;
	url+= '&card_expiry='+card_expiry+'&instructions='+instructions;

	if(conf){
		new ajax (url, {onComplete: result});
	}
	
	function result(response) {
		/*var txt = response.responseText;
		if(txt=='true'||txt=='false'){
			if(txt=='true'){*/
				window.location = 'index.php';
			/*}else{
				alert('Order could not be completed!');
			}
		}*/
	}
}

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 firstname = replaceChars(URL.specialChars, $('firstname').value, URL.specialReplace);	//STRING
		var lastname = replaceChars(URL.specialChars, $('lastname').value, URL.specialReplace);		//STRING
		var password = $('password').value;
		var password2 = $('password2').value;
		
		url += '&username='+username;
		url += '&firstname='+firstname;
		url += '&lastname='+lastname;
		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 = 'admin.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 = 'admin.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 changeNotInStock(obj, pid)
{
	var imgYes = 'images/list_tick.gif';
	var imgNo = 'images/list_cross.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!');
	}
}