/**
 * @author Mike
 * 
 * This script also contains customized snippets 
 * of code taken from:
 * 
 * Roshan Bhattarai's "check username availability in 
 * ajax and php using jquery’s fading effect" script.
 * Find this @ http://roshanbh.com.np/2008/04/check-username-available-ajax-php-jquery.html
 * 
 * w3 Schools "PHP and AJAX MySQL Database Example"
 * Find this @ http://www.w3schools.com/PHP/php_ajax_database.asp
 */

var xmlHttp;

/**
 * Return if a username is available.
 * @param {Object} str
 */
function showUser(str) { 
	xmlHttp = GetXmlHttpObjec();
	if(xmlHttp == null) {
		alert("Browser does not support HTTP Request");
		return;
	}
	
	var url="scripts/getuser.php";
	url=url+"?q="+str;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=regStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

/**
 * Update a users address.
 */
function updateAddress() {
	var cid = document.getElementById('cid').innerHTML;
	var fname = document.deliveryadd.firstname.value;
	var lname = document.deliveryadd.lastname.value;
	var add1 = document.deliveryadd.address1.value;
	var add2 = document.deliveryadd.address2.value;
	var city = document.deliveryadd.city.value;
	var county = document.deliveryadd.county.value;
	var zip = document.deliveryadd.postcode.value;
	
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 }
 var url="scripts/updateaddress.php";
 url=url+"?f="+fname;
 url=url+"&l="+lname; 
 url=url+"&a1="+add1;
 url=url+"&a2="+add2; 
 url=url+"&city="+city;  
 url=url+"&county="+county; 
 url=url+"&zip="+zip;  
 url=url+"&cid="+cid;
 url=url+"&sid="+Math.random()
 xmlHttp.onreadystatechange=addressChanged;
 xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

/**
 * Save a gallery selection.
 * @param {Object} num
 */
function saveGallery(num) {
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 }
 var url="scripts/updategalleryselection.php";
 url=url+"?n="+num;
 url=url+"&sid="+Math.random();
 xmlHttp.onreadystatechange=galleryChanged;
 xmlHttp.open("GET",url,true);
xmlHttp.send(null);	
}

/**
 * Load a users details.
 * @param {Object} cid
 */
function loadResult(cid) {
	document.editform.cid.value = document.getElementById(cid).innerHTML;
	document.editform.username.value = document.getElementById('user' + cid).innerHTML;
	document.editform.firstname.value = document.getElementById('fname' + cid).innerHTML;
	document.editform.lastname.value = document.getElementById('lname' + cid).innerHTML;
	document.editform.address1.value = document.getElementById('a1' + cid).innerHTML;
	document.editform.address2.value = document.getElementById('a2' + cid).innerHTML;
	document.editform.city.value = document.getElementById('city' + cid).innerHTML;
	document.editform.county.value = document.getElementById('county' + cid).innerHTML;
	document.editform.zip.value = document.getElementById('zip' + cid).innerHTML;
	document.editform.telephone.value = document.getElementById('tel' + cid).innerHTML;	
	document.editform.email.value = document.getElementById('email' + cid).innerHTML;		

	if(document.getElementById('admin' + cid).innerHTML == 1) {
		document.editform.admin.checked = true;
	}
}

/**
 * Register that the state has changed when checking a username request.
 */
function regStateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 		 $("#ua").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
		 
		 if(xmlHttp.responseText == "Username Taken!") {
		 	$("#ua").fadeTo(200,0.1,function() //start fading the messagebox
				{ 
				  //add message and change the class of the box and start fading
				  $(this).html('This User name Already exists.').addClass('messageboxerror').fadeTo(900,1);
			});
		 } else {
		 	$("#ua").fadeTo(200,0.1,function()  //start fading the messagebox
				{ 
				  //add message and change the class of the box and start fading
				  $(this).html('Username available to register.').addClass('messageboxok').fadeTo(900,1);	
			});
		 }
 } 
}

/**
 * Show that a gallery selection preference has been saved.
 */
function galleryChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 	$("#messageboxgal").removeClass().addClass('messagebox').text('Saving...').fadeIn("slow");
		 
	$("#messageboxgal").fadeTo(200,0.1,function() //start fading the messagebox
	{ 
		//add message and change the class of the box and start fading
		$(this).html('Your gallery selection has been saved. Thank you. Your change will be shown when you return to the gallery page.').addClass('messageboxok').fadeTo(900,1);
	});
 } 
}

/**
 * Confirm that an address change has been saved.
 */
function addressChanged() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		document.deliveryadd.edit.checked = false;
		openForm();
		
		document.getElementById('address_saved').style.display = 'block';
		$("#address_saved").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");

	 	$("#address_saved").fadeTo(200,0.1,function()  //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Your details have been saved!').addClass('messageboxok').fadeTo(900,1);	
		});		
	}
}

/**
 * XML request function for AJAX.
 */
function GetXmlHttpObject()
 { 
 var objXMLHttp=null;
 if (window.XMLHttpRequest)
  {
  objXMLHttp=new XMLHttpRequest();
  }
 else if (window.ActiveXObject)
  {
  objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 return objXMLHttp;
 }

/**
 * Check that two password entries match.
 * 
 * @param {Object} repass
 * @param {Object} pass
 */
function checkPass(repass, pass) {
	$("#pa").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
	
	if(repass == pass) {
		$("#pa").fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Your passwords are accepted.').addClass('messageboxok').fadeTo(900,1);
		});	
	} else {
	 	$("#pa").fadeTo(200,0.1,function()  //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Your passwords are not the same.').addClass('messageboxerror').fadeTo(900,1);	
		});		
	}
}

/**
 * Validate the register form.
 */
function checkForm() {
	$("#msg").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
	
	if(document.getElementById("pa").innerHTML == "Your passwords are accepted." && 
		document.getElementById("ua").innerHTML == "Username available to register." &&
		document.forms[0].name.value != "" && document.forms[0].address1.value != "" &&
		document.forms[0].county.value != "" && document.forms[0].zip.value != "" && 
		document.forms[0].email.value != "" && document.forms[0].telephone.value != "") {
		
		return true;
	} else {
		$("#msg").fadeTo(200,0.1,function() { 
			  $(this).html('You have not completed the form correctly.').addClass('messageboxerror').fadeTo(900,1);	
		});	
		
		return false;
	}
}

/**
 * Reset the register form.
 */
function resetForm(){
	document.forms[0].username.value = "";
	document.forms[0].password.value = "";
	document.forms[0].repassword.value = "";	
	document.forms[0].name.value = "";
	document.forms[0].address1.value = "";
	document.forms[0].address2.value = "";
	document.forms[0].county.value = "";
	document.forms[0].zip.value = "";
	document.forms[0].email.value = "";
	document.forms[0].telephone.value = "";

	$("#pa").fadeTo(200,0.1,function()  { 
		  $(this).html('Password Check.').addClass('messageboxout').fadeTo(900,1);	
	});

	$("#ua").fadeTo(200,0.1,function()  { 
		  $(this).html('Username Check.').addClass('messageboxout').fadeTo(900,1);	
	});
}

/**
 * Registration complete redirect.
 */
function regCompReDir() {
	setTimeout("location.href='index.php'", 5000);
}

/**
 * Admin Registration complete redirect.
 */
function regCompAdminReDir() {
	setTimeout("location.href='admin.php'", 5000);
}

/**
 * User details saved complete redirect.
 */
function saveCompAdminReDir() {
	setTimeout("location.href='admin.php'", 5000);
}

/**
 * Payment confirmed complete redirect.
 */
function paymentConfirmed() {
	setTimeout("location.href='index.php'", 5000);
}

/**
 * Set the height of a page if the site does not fill the window.
 */
function setHeight() {
	if($(document).height() > $('leftContent').height()-300) {
		$('#leftContent').height($(document).height()-300);
		$('#rightContent').height($(document).height()-300);
	}
}

/**
 * Update the item totals on the add to cart page.
 * @param {Object} str
 * @param {Object} type
 */
function updateItemTotals(str, type){
	if(type == "frame") {
		document.getElementById("frame_total").innerHTML = currencyFormatted(str);
	}
	
	if(type == "finish") {
		document.getElementById("finish_total").innerHTML = currencyFormatted(str);
	}
	
	var quantity = parseFloat(document.getElementById("quantity").value);
	var finish = parseFloat(document.getElementById("finish_total").innerHTML);
	var frame = parseFloat(document.getElementById("frame_total").innerHTML);
	var photo = parseFloat(document.getElementById("photo_total").innerHTML);
	var total = frame + finish + photo;
	
	document.getElementById("grand_total").innerHTML = (total*quantity).toFixed(2);
}

/**
 * Update the checkouts totals.
 * @param {Object} str
 */
function updateCheckoutTotal(str){
	var cost = parseFloat(str);
	var ordertotal = parseFloat(document.getElementById("order_total").innerHTML);
	var total = cost + ordertotal;
	var dis = total - ((total / 100) * 20);
	
	var str = document.getElementById('discount').innerHTML;
	
	if(str.match("20%")) {
		document.getElementById("grand_total").innerHTML = total.toFixed(2) + 
			' <span style="color:red; font-weight:bold;">(' + dis.toFixed(2) + ')</span>';	
	} else {
		document.getElementById("grand_total").innerHTML = total.toFixed(2);	
	}
}

/**
 * Turn on the user delivery address form on the checkout page.
 */
function openForm() {	
	if(document.deliveryadd.edit.checked) {
		document.deliveryadd.firstname.disabled = false;
		document.deliveryadd.lastname.disabled = false;
		document.deliveryadd.address1.disabled = false;
		document.deliveryadd.address2.disabled = false;
		document.deliveryadd.city.disabled = false;
		document.deliveryadd.county.disabled = false;
		document.deliveryadd.postcode.disabled = false;		
		document.getElementById('address_saved').style.display = 'none';		
		document.getElementById('address_save').style.display = 'block';
		document.getElementById('address_save_info').style.display = 'block';										
	} else {
		document.deliveryadd.firstname.disabled = true;
		document.deliveryadd.lastname.disabled = true;
		document.deliveryadd.address1.disabled = true;
		document.deliveryadd.address2.disabled = true;
		document.deliveryadd.city.disabled = true;
		document.deliveryadd.county.disabled = true;
		document.deliveryadd.postcode.disabled = true;
		document.getElementById('address_save').style.display = 'none';		
		document.getElementById('address_save_info').style.display = 'none';		
	}
}

/**
 * Update the user upload result.
 */
function updateResult() {

	var str = document.getElementById('result').innerHTML;
	var f = document.getElementById('file').innerHTML;
	
	switch(str) {
			case "big":
				$("#upload_result").fadeTo(200, 0.1, function() //start fading the messagebox
				{
					//add message and change the class of the box and start fading
					$(this).html('Your selected photo\'s filesize is too big. Please select a photo which is 1.5MB or less and try again.').addClass('messageboxerror').fadeTo(900, 1);
				});		
				break;
			case "not":
				$("#upload_result").fadeTo(200, 0.1, function() //start fading the messagebox
				{
					//add message and change the class of the box and start fading
					$(this).html('There has been a problem uploading your photo. Please make sure all the fields are completed try again.').addClass('messageboxerror').fadeTo(900, 1);
				});
				break;
			case "type":
				$("#upload_result").fadeTo(200, 0.1, function() //start fading the messagebox
				{
					//add message and change the class of the box and start fading
					$(this).html('You have tried to upload a file which is not a photo. Please select a photo and try again.').addClass('messageboxerror').fadeTo(900, 1);
				});		
				break;		
			case "ok":
				$("#upload_result").fadeTo(200, 0.1, function() //start fading the messagebox
				{
					//add message and change the class of the box and start fading
					$(this).html('Your photo ' + f + ' has been uploaded successfully!').addClass('messageboxok').fadeTo(900, 1);
				});		
				break;	
			case "":
				$("#upload_result").fadeTo(200, 0.1, function() //start fading the messagebox
				{
					//add message and change the class of the box and start fading
					$(this).html('Click \'Upload\' when you have completed the form.' +
						'Make sure all the fields are complete.').addClass('messagebox').fadeTo(900, 1);
				});		
				break;														
		}	
}

/**
 * Validate the add to cart form.
 */
function checkAddForm() {
	var s = parseInt(document.getElementById('stock').innerHTML);
	if(document.getElementById('quantity').value > s) {
		addToCart("stock", s);
		return false;	
	}
	
	if(document.addtocart.frames.selectedIndex == 0) {
		addToCart("frame", s);
		return false;
	}
	
	if(document.addtocart.quantity.value == 0) {
		addToCart("quan", s);
		return false;
	}
	
	if(document.addtocart.finishes.selectedIndex == 0) {
		addToCart("finish", s);
		return false;
	}
	
	return true;
}

/**
 * Add to cart feedback.
 * @param {Object} str
 * @param {Object} i
 */
function addToCart(str, i) {
	switch(str) {
		case "stock":
			$("#addmsgbox").fadeTo(200, 0.1, function() //start fading the messagebox
			{
				//add message and change the class of the box and start fading
				$(this).html('You have tried to purchase more items than we have stock for. Please select less than ' + i + '.').addClass('messageboxerror').fadeTo(900, 1);
			});			
		break;
		case "finish":
			$("#addmsgbox").fadeTo(200, 0.1, function() //start fading the messagebox
			{
				//add message and change the class of the box and start fading
				$(this).html('You need to select a finish for your photo.').addClass('messageboxerror').fadeTo(900, 1);
			});			
		break;
		case "frame":
			$("#addmsgbox").fadeTo(200, 0.1, function() //start fading the messagebox
			{
				//add message and change the class of the box and start fading
				$(this).html('You need to select a frame for your photo.').addClass('messageboxerror').fadeTo(900, 1);
			});			
		break;
		case "quan":
			$("#addmsgbox").fadeTo(200, 0.1, function() //start fading the messagebox
			{
				//add message and change the class of the box and start fading
				$(this).html('Please select more than 0 photos.').addClass('messageboxerror').fadeTo(900, 1);
			});			
		break;						
	}	
}

/**
 * Confirm a users purchase.
 */
function confirmPurchase() {
	var i = 0;
	
	if(confirm("Are you sure you want to confirm this purchase?")) {
		var card = document.getElementById('cardnumber').value;
		var cv2 = document.getElementById('cv2').value;
		var type = document.ordersummary.card_type.selectedIndex;
		var vm = document.ordersummary.valid_month.selectedIndex;
		var vy = document.ordersummary.valid_year.selectedIndex;
		var em = document.ordersummary.expiry_month.selectedIndex;
		var ey = document.ordersummary.expiry_year.selectedIndex;

		if(card.length != 16 || cv2.length != 3 || vm == 0 || vy == 0 || em == 0 || ey == 0) {
			alert("Your card details are wrong!");
			i = 1;
		} 
		
		if(document.ordersummary.postage.selectedIndex == 0) {
			alert("Please select a postage!");
			i = 1;
		}
		
		if(i == 1) {
			return false;			
		} else {
			document.ordersummary.submit();
		}
	}
}

// http://www.web-source.net/web_development/currency_formatting.htm
function currencyFormatted(amount)
{
	var i = parseFloat(amount);
	
	if(isNaN(i)) { 
		i = 0.00; 
	}
	
	var minus = '';
	
	if(i < 0) { 
		minus = '-'; 
	}
	
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);

	if(s.indexOf('.') < 0) { 
		s += '.00'; 
	}
	
	if(s.indexOf('.') == (s.length - 2)) {
		s += '0'; 
	}
	
	s = minus + s;
	
	return s;
}




