/* globals */
var win = null;
var filter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,5}|\d+)$/;

function NewWindow(mypage,myname,w,h,s,r){
	LeftPos = (screen.width) ? (screen.width-w)/2 : 0;
	TopPos = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPos+',left='+LeftPos+',scrollbars='+s+',resizable='+r+',status=yes';
	win = window.open(mypage,myname,settings);
}
/* init valid popup and external windows */
function windowLinks() {
    if(!document.getElementsByTagName) {
         return;
    }
    var anchors = document.getElementsByTagName('a');
    for (var i = 0; i < anchors.length; i++) {
         var anchor = anchors[i];
         var relIndex = anchor.rel;
		 if (relIndex){
		 var relSplit = relIndex.split('|');
		 /* XHTML compliant target attribute */
		 if (relSplit[0] == 'external') {
            anchor.target = '_blank';
			anchor.className = 'external';
			anchor.title = 'Load in new window: '+ anchor.href;
			/* XHTML compliant popup attribute */
   		} else if (relSplit[0] == 'popup') {
			if (anchor.className == '' && anchor.title == '') {
			  anchor.className = 'popup';
			  anchor.title = 'Link loads in Popup Window';
			}
			anchor.popupWidth = relSplit[1];
			anchor.popupHeight = relSplit[2];
			/* added the ablitity to have resize or scroll */
			anchor.popupScroll = relSplit[3];
			anchor.popupResize = relSplit[4];
	        anchor.onclick = function() {
				NewWindow(this.href,'',this.popupWidth,this.popupHeight,this.popupScroll,this.popupResize);return false;
			   };
			}
		}
	}
}

/* allows a user to bookmark a page */
function bookmarkpage(title, url){
	if (document.all) {
		window.external.AddFavorite(url, title);
	} else if (window.sidebar) {
		window.sidebar.addPanel(title, url, '');
	}
}

/* toggles visibility */
function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
		var element = document.getElementById(expandCollapse.arguments[i]);
		element.style.display = (element.style.display == 'none' || element.style.display == '') ? 'block' : 'none';
	}
}
/* check that a user wants to log out */
function logOut() {
	ht = document.getElementsByTagName('html')[0];
	ht.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
	if (confirm('Are you sure you want to log out?')) {
		return true;
	} else {
		ht.style.filter = '';
		return false;
	}
}

/* validates the newsletter subscription */
function validateSubscription() {
	if(!gebi('newsletterform')) {return;}
	/* get the newsletter form wait for it to submit */
	var nf = gebi('newsletterform');
	nf.onsubmit = function() {
		/* if either the name of email are not correct halt the submission */
		if(nf.elements['NewsletterName'].value == 'YOUR NAME') {
			alert('Please enter your name');
			nf.elements['NewsletterName'].focus();
			return false;			
		}
		if(!filter.test(nf.elements['NewsletterEmail'].value)) {
			alert('Please enter a valid email address');
			nf.elements['NewsletterEmail'].focus();
			return false;
		}
		return true;
	};
}

/* init the function for copying the billing address data to the delivery address fields */
function initSetSameAddress() {
	if(!gebi('setsame')) {return;}
	addEvent(gebi('setsame'), 'click', setSameAddress, false);
	return true;
}
/* wait for the button to be clicked */
function setSameAddress(e) {
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	/* these are all the billing fields that should be copied */
	var fields = new Array('con_address','con_suburb','con_postcode','con_state','con_country');
	if (target.value.indexOf('Copy') != -1) {
		for (var i=0; i<fields.length; i++) {
			/* loop the fields and get the equivilent delivery fields as well as the delivery error spans 
			that have been created for validation. We also need the field itself to copy the data from */
			var delField = gebi('con_del_'+fields[i].split('_')[1]);
			var errorField = gebi('error_con_'+fields[i].split('_')[1]);
			var field = gebi(fields[i]);
			/* the field is a dropdown */
			if(field.type == 'select-one') {	
				field.selectedIndex = delField.selectedIndex;	
				/* copy the current selcted and if it is '' then show the error */
				if (field.options[field.selectedIndex].value == ''){
					errorField.innerHTML = validationSet[field.name]['error'];
					field.className = 'fielderror';
				} else {
					errorField.innerHTML = '';
					field.className = 'textfield';		
				}	
			/* for fields that are input and texteareas */
			} else if (field.type == 'text' || field.type == 'textarea') {
				field.value = delField.value;
				/* copy in the value and make sure that the regex matches otherwise show the error */
				if (!field.value.match(validationSet[field.name]['regexp'])) {
					errorField.innerHTML = validationSet[field.name]['error'];
					field.className = 'fielderror';
				} else {
					errorField.innerHTML = '';
					field.className = 'textfield';
				}					
			}
		}
	}
	return false;
}

function disableCardFields() {
	if (!gebi('existingcustomer')){return false;}
	/* these are all the card fields that should be disabled */
	var fields = new Array('con_card_name','con_card_number','con_card_type','con_card_expiry_month','con_card_expiry_year','save_card');
	var existingCustomer = gebi('existingcustomer');
	existingCustomer.onclick = function() {
		for (var i=0; i<fields.length; i++) {
			var field = gebi(fields[i]);
			field.disabled = field.disabled == false ? true : false;
		}
	};
	return true;
}

function initChangeFreight() {
	if (!gebi('total_cost')){return false;}
	/* add event handlers to the two freight radion buttons */
	addEvent(gebi('freight_option1'), 'click', changeFreight, false);
	addEvent(gebi('freight_option2'), 'click', changeFreight, false);
	return true;
}

function changeFreight(e) {
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	var total = gebi('total_cost');
	var costs = gebi('freight_values').value.split(';');
	var totalFreight = gebi('total_freight_display');
	var totalGST = gebi('total_gst_display');
	var payment = gebi('payment');
	/* depending on the radio checked modify the page to show the correct freight */
	switch (target.value) {
		case 'normal':
		total.innerHTML = costs[0];
		totalFreight.innerHTML = costs[1];
		totalGST.innerHTML = costs[2];
		break;
		case 'toBeAdvised':
		total.innerHTML = costs[0];
		totalFreight.innerHTML = costs[1];
		totalGST.innerHTML = costs[2];
		payment.style.display = 'none';
		break;
		case 'customerArrange':		
		total.innerHTML = costs[3];
		totalFreight.innerHTML = '$0.00';
		totalGST.innerHTML = costs[4];
		payment.style.display = 'block';
		break;	
	}
	return true;
}

function initCheckEmailExists() {
	if(!gebi('checkexists')) {return;}
	var checkExistsButton = gebi('checkexists');
	checkExistsButton.onclick = function() {
		var ajax = new Ajax();
		var email = gebi('con_email').value;
		if (!email.match(filter)) {
			alert('Please enter a valid email address');
		} else {
			ajax.doGet('modules/ajax_response.cfm?action=checkemail&email='+email, function(str){alert(str);});
		}
		return false;
	};
	return true;
}

function cancelButton() {
	var cancelButton,url;
	if(gebi('accountcancel')) {
		cancelButton = gebi('accountcancel');
		url = 'my_account.cfm?status=cancelled';
	} else if (gebi('checkoutcancel')) {
		cancelButton = gebi('checkoutcancel');	
		url = 'shopping_cart.cfm?status=cancelled';
	} else if (gebi('newslettercancel')) {
		cancelButton = gebi('newslettercancel');	
		url = 'newsletter.cfm?status=cancelled';
	} else {
		return;
	}
	cancelButton.onclick = function() {
		window.location.href = url;
		return false;
	};
	return true;
}

function idJumpmenu() {
	if(!document.getElementsByTagName) {return;}
	var selects = document.getElementsByTagName('select');
	/* if the select's id has _id in it */
	for (var i=0; i<selects.length; i++) {
		if (selects[i].id.indexOf('_id') != -1) {
			addEvent(selects[i], 'change', 
				function(e) {
					var t = window.event ? window.event.srcElement : e ? e.target : null;
					if (!t) {return false;}
					/* wait till the value is changed and is not '' or null */
					if (t.options[t.selectedIndex].value != null && t.options[t.selectedIndex].value != '') {
						/* grab the id to search the url for */
						var s = searchCGI(t.id.substr(0,t.id.indexOf('_id')+3));
						/* once you have it's value use that to replace it's value
						in the url with the current selected id */
						setCGI(s[0],s[1],s[0],t.options[t.selectedIndex].value);
					} else {
						return false;
					}
					return true;			
			}, false);
		}
	}
	return true;
}

addLoadListener(windowLinks);
addLoadListener(validateSubscription);
addLoadListener(initSetSameAddress);
addLoadListener(initCheckEmailExists);
addLoadListener(cancelButton);
addLoadListener(disableCardFields);
addLoadListener(initChangeFreight);
addLoadListener(idJumpmenu);
