/* Focusing HTML inputs on Internet Explorer */
var i = 0;
var j;
var k;
var pattern;
var text;
var subtotal;
var focusOnIE;
var total;
var shipment_fee;
var previous_fee;

focusOnIE = function() {
	var tags = ['INPUT','TEXTAREA','SELECT'];
	for (j=0; j<tags.length; j++) {
		var sfEls = document.getElementsByTagName(tags[j]);
		for (var i=0; i<sfEls.length; i++) {
			if (sfEls[i].getAttribute('TYPE') != "button") {
				sfEls[i].onfocus=function() {
					this.className+=" focusIE";
				}
				sfEls[i].onblur=function() {
					this.className=this.className.replace(new RegExp(" focusIE\\b"), "");
				}
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", focusOnIE);

// Prompt an error message and highlighted the related field
function errorMsg(text, input_id) {
	alert(text);
	document.getElementById(input_id).focus();
}

// Test whether a date is anterior to today's date or not
function isFuture(month_id,year_id) {
	var today = new Date();
	var thisDate = new Date();
	thisMonth = document.getElementById('creditcard_month').options[document.getElementById('creditcard_month').selectedIndex].value;
	thisYear = document.getElementById('creditcard_year').options[document.getElementById('creditcard_year').selectedIndex].value;	
	thisDate.setFullYear(thisYear,thisMonth,01);
	if (thisDate>today)
		return true;
	else
		errorMsg('Please check your expiration date.', 'creditcard_month');
		return false;
}

// Test on any required field
function checkRequiredField(input_id) {
	var value = document.getElementById(input_id).value;
	if (value==null||value=="") {
        errorMsg('Please fill up the highlighted field', input_id);
		return false;
	}
	else 
		return true;
}

// Regular expression-based test on the entered email address
function isMailAddress(email_id){
	var email = document.getElementById(email_id).value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email))
		return true;
	else
		errorMsg ('Please make sure your email address is correct.', email_id);
		return false;
}

function checkCustomerInfo() {
	if (checkRequiredField('customer_name') && isMailAddress('email_address'))
		document.getElementById('form_shipment').submit();
}

function checkCreditCardNumber(creditCardNumber_id) {
	var string = document.getElementById(creditCardNumber_id).value;
	var pattern = new RegExp("^[0-9]+$");
	if ((document.getElementById(creditCardNumber_id).value.length != 16) || (! pattern.test(string))) {
		errorMsg ('Please enter the 16 digits of your credit card number.', creditCardNumber_id);
		return false;
	}
	else { 
		return true;
	}
}

function checkCreditCard() {
	if (checkCreditCardNumber('creditcard_number') && isFuture('creditcard_month','creditcard_year') && checkRequiredField('creditcard_name')) {
		document.getElementById('creditcard_button').style.display = 'none';
		document.getElementById('li_main_4').style.display = 'block';
		document.getElementById('customer_name').focus();
		window.scrollTo(0,2000);
	}
}

function checkForm(id) {
	var nothingSelected = true;
	switch(id) {
		
		// Select your photos
		case 'wedding_photogallery':
			// Grab the right form Element			
			var form = document.getElementById(id);
			for (i=0; i<form.elements.length; i++) {
				if (form.elements[i].checked) {
					nothingSelected = false;
					form.submit();
				}
			}
			if (nothingSelected) {
				//alert ('Oops, no photo has been selected.');
				form.submit();

			}
			break;
			
		// Select printing formats	
		case 'form_printing_format':
			// Grab the right form Element			
			var form = document.getElementById(id);
			var order = '';
			
			for (i=0; i < form.elements.length; i++) {
				if (form.elements[i].selectedIndex != 0) {
					nothingSelected = false;
					// Store all purchase inside hidden input
					order += ';'+form.elements[i].id+'|'+form.elements[i].options[[form.elements[i].selectedIndex]].value
					// Submit form
					//form.submit();
				}
			}
			if (nothingSelected)
				alert('Please apply formatting to at least one image.');
			else {
				// Create the hidden input
				var hiddenInput = document.createElement('input');
				hiddenInput.setAttribute('type', 'hidden');
				hiddenInput.setAttribute('id', 'order');
				hiddenInput.setAttribute('name', 'order');				
				hiddenInput.setAttribute('value', order);
				form.appendChild(hiddenInput);
				form.submit();
			}
			break;
			
		// Checkout > Shipment address
		case 'form_shipment':
			// Grab the right form Element			
			var form = document.getElementById(id);
			for (i=0; i<form.elements.length; i++) {
				if (form.elements[i].tagName == 'TEXTAREA' && form.elements[i].value != '') {
					nothingSelected = false;
					form.submit();
				}
			}
			if (nothingSelected) {
				alert ('Please write down your shipping address.')	
			}
			break;

		default:
			alert('Pb with your JS coding: This form id doesn\'t exist.');
			
	}
}

// Select all photos from 'Select your photos'
function selectAll(id) {
	var form = document.getElementById(id);
	for (i=0; i<form.elements.length; i++) {
		if (form.elements[i].id == 'filename[]') {
			form.elements[i].checked = true;
		}
	}
}
// Deselect all photos from 'Select your photos'
function deselectAll(id) {
	var form = document.getElementById(id);
	for (i=0; i<form.elements.length; i++) {
		if (form.elements[i].id == 'filename[]') {
			form.elements[i].checked = false;
		}
	}
}

function setQuantity(select_id, select_value) {
	var form = document.getElementById('form_printing_format');
	var pattern = new RegExp("^("+select_id+"_)");
	for (i=0; i < form.elements.length; i++) {
		if (pattern.test(form.elements[i].id)) {
			for (j=0; j<form.elements[i].options.length; j++) {
				form.elements[i].options[j].selected = (form.elements[i].options[j].value==select_value)? true : false;
			}
		}
	}
	showSubtotal();
}

function showSubtotal() {
	var total = [];
	var count = 0;
	var form = document.getElementById('form_printing_format');
	var div_price = document.getElementById('div_price');
	for (i=0; i<div_price.childNodes.length; i++) {
		if (div_price.childNodes[i].tagName == 'UL') {
			for (j=0; j<div_price.childNodes[i].childNodes.length; j++) {
				if (div_price.childNodes[i].childNodes[j].tagName == 'LI') {
					subtotal = 0;
					pattern = new RegExp("^("+div_price.childNodes[i].childNodes[j].id+"_)");
					for (k=0; k < form.elements.length; k++) {
						if (pattern.test(form.elements[k].id)) {
							subtotal += form.elements[k].selectedIndex;
						}
					}
					text = '<span>'+subtotal+'</span> photo';
					text += (subtotal<2)? ' ' : 's ';
					text +=  'in '+div_price.childNodes[i].childNodes[j].id;
					div_price.childNodes[i].childNodes[j].innerHTML = text;
					total[count] = subtotal;
					count++;
				}
			}
		}
	}
	for (i=0; i<div_price.childNodes.length; i++) {
		if (div_price.childNodes[i].tagName == 'P') {
			for (j=0; j<div_price.childNodes[i].childNodes.length; j++) {
				if (div_price.childNodes[i].childNodes[j].tagName == 'SPAN') {
					total = formatPrice(total);
					div_price.childNodes[i].childNodes[j].innerHTML = total;
				}
			}
		}
	}
}


function showShipment(value) {

	var form = document.getElementById('form_shipment');

	// Check which input as been clicked on
	switch (value) {

		case 'shipment_required':
			
			// Hide any 'credit card' panel previously displayed
			document.getElementById('li_main_3').style.display = 'none';
			// If the related division isn't yet displayed, well let it be seen.
			if (document.getElementById(value).style.display == 'none' || document.getElementById(value).style.display == '') {
				for (i=0; i<form.elements.length; i++) {
					if (form.elements[i].type == 'radio') {
						div = document.getElementById(form.elements[i].value)
						div.style.display = (form.elements[i].checked)? 'block' : 'none';
						document.getElementById('shipment_address').focus();
					}
				}
				window.scrollTo(0,2000);
			}
			// If the division is already displayed, that means the address has been entered.
			// The purchase summary table will be modified according to the user indications.
			else {
				if (document.getElementById('shipment_address').value == '') {
					// Set the value of 'shipment_country' to default
					document.getElementById('shipment_country').selectedIndex = 0;					
					document.getElementById('shipment_address').focus();
					alert('Please indicate your shipping address.');
				}
				else {
					var shipment_country = document.getElementById('shipment_country');
					if (shipment_country[shipment_country.selectedIndex].value == 'default')
						alert('Please indicate your location.');
					else {
						shipment_fee = (shipment_country[shipment_country.selectedIndex].value == 't&t')? 50.00 : 150.00;						
						var tfoot = document.getElementById('tr_tfoot').parentNode;
						// Store the previous price in a variable
						total = document.getElementById('span_total').innerHTML;
						// Clone the 'Total' row
						var tr_total = tfoot.lastChild.cloneNode(true);
						previous_fee = 0;
						if (tr_shipment = document.getElementById('tr_shipment')) {
							previous_fee = +tr_shipment.childNodes[1].innerHTML.replace(' TT$','');
						}
						// Remove all foot rows except subtotal and VAT
						for (i=(tfoot.childNodes.length-1); i>1; i--) {
							tfoot.removeChild(tfoot.childNodes[i]);
						}
						// Create <tr id="shipment">
						var tr_shipment = document.createElement('tr');
						tr_shipment.id = 'tr_shipment';
						// Create <th colspan="3">Shipment :</th>
						var th1 = document.createElement('th');
						th1.setAttribute('colSpan','3');
						th1.appendChild(document.createTextNode('Shipment :'));
						tr_shipment.appendChild(th1);
						// Create <th class="last_td"><span>price</span> TT$</th>
						var th2 = document.createElement('th');
						th2.setAttribute('class', 'last_td');
						th2.appendChild(document.createTextNode(shipment_fee.toFixed(2)+' TT$'));
						tr_shipment.appendChild(th2);
						tfoot.appendChild(tr_shipment);
						// Add cloned previous total row
						tfoot.appendChild(tr_total);
						// Get previous shipment fee
						// Update total price
						var span = document.getElementById('span_total');
						span.innerHTML = (+(span.innerHTML.replace(' ',''))-previous_fee+shipment_fee).toFixed(2);
						document.getElementById('li_main_3').style.display = 'block';
						document.getElementById('creditcard_number').focus();
						window.scrollTo(0,2000);
					}
				}
			}
			break;
		
		case 'shipment_no':
			if (tr_shipment = document.getElementById('tr_shipment')) {
				var tfoot = document.getElementById('tr_tfoot').parentNode;
				// Clone the 'Total' row
				var tr_total = tfoot.lastChild.cloneNode(true);
				// Remove all foot rows except subtotal and VAT
				for (i=2; i<tfoot.childNodes.length; i++) {
					tfoot.removeChild(tfoot.childNodes[i]);
				}
				// Delete shipment fee from previous total price
				var span = document.getElementById('span_total');
				span.innerHTML = (+(span.innerHTML.replace(' ',''))-(+tr_shipment.childNodes[1].innerHTML.replace(' TT$',''))).toFixed(2);
				alert('Your total has been updated.');	
			}
			// Set the value of 'shipment_country' to default
			document.getElementById('shipment_country').selectedIndex = 0;
			// Display/hide the shipment divisions according to the value selected
			for (i=0; i<form.elements.length; i++) {
				if (form.elements[i].type == 'radio') {
					var div = document.getElementById(form.elements[i].value);
					div.style.display = (form.elements[i].checked)? 'block' : 'none';
				}
			}
			// Display and focus on the next checkout step
			document.getElementById('li_main_3').style.display = 'block';
			document.getElementById('creditcard_number').focus();
			window.scrollTo(0,2000);
			break;

		default:
			alert('Boy, there\'s something wrong with your script.');
	}
	
}

/*********************/
/* Zoom in/out photo */
/*********************/
var img_loading = new Image(32,32);
img_loading.src = "img/gif/loading.gif";
var img = new Image();

function photoZoomIn(photo_path) {

	// 1. Get the scrolling offset
	var scrollTop = getScrollTop();

	// 2. Set the absolute top position of the main division to fit the scrollTop value
	var div_main = document.getElementById('zoom_in_main');
	// Internet Explorer command
	div_main.style.top = scrollTop;
	// Other browsers command
	div_main.setAttribute('style','top:'+scrollTop+'px;');

	// 3. Replace image according to the file path sent as variable
	var td = document.getElementById('zoom_photo').parentNode;
	for (i=(td.childNodes.length -1); i>=0; i--) {
		td.removeChild(td.childNodes[i]);
	}
	var tag_img_loading = document.createElement('IMG');
	tag_img_loading.setAttribute('src', img_loading.src)
	td.appendChild(tag_img_loading);
	
	var new_photo = document.createElement('IMG');
	new_photo.setAttribute('id', 'zoom_photo');	
	img.src = photo_path;
	img.onload = function() {
		for (i=(td.childNodes.length -1); i>=0; i--) {
			td.removeChild(td.childNodes[i]);
		}
		//style="background-image: url(images/yourpic.jpg)"
		new_photo.style.cssText = 'background-position:center; background-repeat:no-repeat; border:none; background-image: url(\''+img.src+'\')';
		new_photo.setAttribute('src', 'img/gif/copyright.gif');
		new_photo.setAttribute('height', '550');
		new_photo.setAttribute('width', '550');
		
		var a = document.createElement('A');
		a.setAttribute('href', 'javascript:photoZoomOut();');
		a.innerHTML = 'close';
		td.appendChild(new_photo);
		td.innerHTML += '<br />';
		td.appendChild(a);
	}
	
	// 4. Set HTML overflow to hidden
	var html = document.getElementsByTagName('HTML');
	browser = getBrowserName();
	if (browser == 'MSIE') { // all IE
		html[0].style.overflow = 'hidden';
	}
	else if (browser == 'Opera') { // Opera
	}
	else if (browser == 'Firefox'){ // Firefox
		html[0].setAttribute('style', 'overflow:hidden');
		window.scrollBy(0,scrollTop);
	}
	else if (browser == 'Safari'){ // Safari
		html[0].style.overflow = 'hidden';
	}

	// 5. Display the whole 'zoom in' main division
	div_main.style.display = 'block';
	//window.setTimeout('Effect.Appear(\'zoom_in_main\', {duration:.9})',2500);	

}
function photoZoomOut() {
	
	// 1. Browser & scrollTop detect
	var browser = getBrowserName();
	var scrollTop = getScrollTop();	

	// 2. Set HTML overflow back to normal for each browser
	var html = document.getElementsByTagName('HTML');
	if (browser == 'MSIE') { // all IE
		html[0].style.overflow = 'auto';
	}
	else if (browser == 'Safari') { // Safari
		html[0].setAttribute('style','overflow:auto');
		window.scrollTo(0,scrollTop);
	}
	else { // All except IE
		html[0].setAttribute('style','overflow:auto');
	}

	// Hide the whole 'zoom in' main division	
	document.getElementById('zoom_in_main').style.display = 'none';
	//Effect.Fade('zoom_in_main');
}
/* Zoom in/out photo */

function getBrowserName() {
	var browser = navigator.userAgent;
	var browserNames = new Array (/(MSIE)+/,/(Firefox)+/,/(Opera)+/,/(Safari)+/)	
	for (i=0;i<browserNames.length;i++) {
		if (browserNames[i].test(browser))
			browser = ""+browserNames[i];
	}
	return browser.replace('/(', '').replace(')+/', '');
}

function getScrollTop() {
	var scrollTop = 0;
	if (self.pageYOffset) { // all except IE
		//alert('all except IE');
		scrollTop = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) { // IE 6 Strict
		//alert('IE 6 Strict');	
		scrollTop = document.documentElement.scrollTop;
	}
	else if (document.body) { // all other IE
		//alert('all other IE');		
		scrollTop = document.body.scrollTop;
	}
	return scrollTop;
}