// JavaScript Document
addLoadListener(loadHeader);
addLoadListener(detectJS);
addLoadListener(externalLinks);
addLoadListener(loadMenuImgs);
addLoadListener(imgReplace);
addLoadListener(changeImg);
addLoadListener(changeNavColour);
addLoadListener(submitOrder);
addLoadListener(changeCountry);
addLoadListener(loadPlayer);
addLoadListener(detailsFormSubmit);
addLoadListener(changeQty);
var orderTotal;
var lineId;
var itemQty;

function addLoadListener(fn){
	if (typeof window.addEventListener != 'undefined'){
		window.addEventListener('load', fn, false);
	}else if (typeof document.addEventListener != 'undefined'){
		document.addEventListener('load', fn, false);
	}else if (typeof window.attachEvent != 'undefined'){
		window.attachEvent('onload', fn);
	}else{
		var oldfn = window.onload;
		if (typeof window.onload != 'function'){
			window.onload = fn;
		}else{
			window.onload = function(){
				oldfn();
				fn();
			};
		}
	}
}
//preload mouseover images in main menu
function loadMenuImgs(){
	simplePreload('img/nav-main-bio-over.gif', 'img/nav-main-home-over.gif', 'img/nav-main-live-over.gif','img/nav-main-music-over.gif', 'img/nav-main-press-over.gif', 'img/nav-main-tour-over.gif');
}
function simplePreload(){ 
	var args = simplePreload.arguments;
	document.imageArray = new Array(args.length);
	for(var i=0; i<args.length; i++){
		document.imageArray[i] = new Image;
		document.imageArray[i].src = args[i];
	}
}
function detectJS(){
	var eAll = document.getElementsByTagName('*');
	var i;
	for(i = 0; i < eAll.length; i++){
		if(eAll[i].className == "noJS"){
			eAll[i].style.display = "none";	
		}
		if(eAll[i].className == "orderButton"){
			eAll[i].disabled = false;	
		}
	}
}
//load flash header
function loadHeader(){
	var flashDiv = document.getElementById("headerFlash");
	var fc = "<object type='application/x-shockwave-flash' data='pcauto.swf' width='850' height='150' id='PCHeader'>\n";
	fc += "<param name='movie' value='pcauto.swf' />\n";
	fc += "<param name='allowScriptAcess' value='sameDomain' />\n";
	fc += "<param name='quality' value='best' />\n";
	fc += "<param name='scale' value='noScale' />\n";
	fc += "<param name='salign' value='TL' />\n";
	fc += "<param name='wmode' value='transparent' />\n";
	fc += "</object>";
	flashDiv.innerHTML = fc;
}
function loadPlayer(){
	if(document.getElementById("player")){
		var player = document.getElementById("player");
		var fc = "<object type='application/x-shockwave-flash' data='player/mp3player.swf' width='370' height='130' id='mp3player'>\n";
		fc += "<param name='movie' value='player/mp3player.swf' />\n";
		fc += "<param name='allowScriptAcess' value='sameDomain' />\n";
		fc += "<param name='quality' value='best' />\n";
		fc += "<param name='scale' value='noScale' />\n";
		fc += "<param name='salign' value='TL' />\n";
		/*fc += "<param name='wmode' value='transparent' />\n";*/
		fc += "</object>";
		player.innerHTML = fc;
	}
}
//open links with rel='external' in new window
function externalLinks() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a");
 var forms = document.getElementsByTagName("form");
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href") && 
       anchor.getAttribute("rel") == "external") 
     anchor.target = "_blank"; 
 } 
 for (var j=0; j<forms.length; j++) { 
   var form = forms[j]; 
   if (form.getAttribute("rel") == "external") 
     form.target = "_blank"; 
 } 
} 
//(3 functions) change png images to gif in IE6 for transparency
function changeImg(){
	var el = new Array('a', 'div', 'body', 'li', 'h1', 'h2', 'h3', 'html');
	var br = navigator.appName;
	if (typeof document.body.style.maxHeight == "undefined" && br == "Microsoft Internet Explorer") {
		for(var i = 0;i < el.length;i++){
			bgImgReplace(el[i]);
		}
	}
}
function bgImgReplace(elem){
	var el = document.getElementsByTagName(elem);
	for(var i=0;i < el.length;i++){
		 var els = el[i].currentStyle.backgroundImage;
		 if(els.substr(0,3) == "url"){
			 if(els.substr(els.length-6,4) == ".png"){
					var newEls = els.replace(".png",".gif");
					el[i].style.backgroundImage = newEls;
			 }
		 }
	}
}
function imgReplace(){
	var br = navigator.appName;
	if (typeof document.body.style.maxHeight == "undefined" && br == "Microsoft Internet Explorer") {
		var im = document.getElementsByTagName('img');
		var imSrc, newImg;
		for(var i = 0; i < im.length; i++){
			imSrc = im[i].src;
			if(imSrc.substr(imSrc.length-4,4) == ".png"){
				newImg = imSrc.replace(".png",".gif");
				im[i].src = newImg;
			}
		}
	}
}
//change menu image colour depending on which page
function changeNavColour(){
	var u = document.getElementById('navMainList').getElementsByTagName('li');
	var n = document.URL;
	var i;
	for(i = 0; i < u.length; i++){
		if(u[i].childNodes[0].href == document.URL){
			switch(u[i].childNodes[0].innerHTML){
				case 'Biography':
				u[i].childNodes[0].style.backgroundImage = 'url(img/nav-main-bio-over.gif)';
				break;
				case 'Tour Dates':
				u[i].childNodes[0].style.backgroundImage = 'url(img/nav-main-tour-over.gif)';
				break;
				case 'Buy Music':
				u[i].childNodes[0].style.backgroundImage = 'url(img/nav-main-music-over.gif)';
				break;
				case 'Press':
				u[i].childNodes[0].style.backgroundImage = 'url(img/nav-main-press-over.gif)';
				break;
				case 'Live':
				u[i].childNodes[0].style.backgroundImage = 'url(img/nav-main-live-over.gif)';
				break;
				default:
				u[i].childNodes[0].style.backgroundImage = 'url(img/nav-main-home-over.gif)';
			}
		}
	}
}
/* music.php
-----------------------------------------------------------------------------*/
//checks that a number has been entered into at least one text box on submit
function submitOrder(){
	if(document.getElementById('frmProduct')){
		var fProd = document.getElementById('frmProduct');
		fProd.onsubmit = checkMusicPage;
	}
}
function checkMusicPage(){
	var q = document.getElementsByTagName('input');
	var ordered = false;
	var i;
	for(i = 0; i < q.length; i++){
		if(q[i].type != 'submit' && q[i].value > 0){
			ordered = true;
		}
	}
	if(!ordered){
		alert("Please indicate quantity you wish to purchase...");	
	}
	return ordered;
}
/*details.php
-------------------------------------------------------------------------*/
//recalculates amounts when quantity changed
function changeQty(){
	var orderFs = document.getElementById('orderDetails');
	var qtys = orderFs.getElementsByTagName('input');
	var i;
	
	for(i = 0; i < qtys.length; i++){
		qtys[i].onchange = recalcAmts;	
	}
}
function recalcAmts(){
	var line = this.parentNode.parentNode.childNodes;
	var i;
	itemQty = this.value;
	for(i = 0; i < line.length; i++){
		if(line[i].className == 'itemPrice'){
			lineId = line[i].childNodes[1];
			var id = line[i].childNodes[1].id.substr(5);
			var u = 'id='+id
			var p = new Ajax('post', 'ax_get_price.php', u);
			p.onload = calcPrice;
		}
	}
}
function calcPrice(){
	var prices = document.getElementsByName('prdPrice');
	var i;
	var totPrice = 0;
	lineId.innerHTML = (parseFloat(this.response)*itemQty).toFixed(2);
	for(i = 0; i < prices.length; i++){
		totPrice += parseFloat(prices[i].innerHTML);	
	}
	orderTotal = totPrice;
	calcShipping();
}
//recalculate shipping on products when country dropdown changes
function changeCountry(){
	if(document.getElementById('custCountry')){
		var c = document.getElementById('custCountry');
		c.onchange = calcShipping;
		//reset dropdown after refresh
		c.value = 'NZ';
		if(document.getElementById('orderTotal')){
			orderTotal = parseFloat(document.getElementById('orderTotal').innerHTML);
			var ordTot = (orderTotal + parseFloat(document.getElementById('shippingCalc').innerHTML)).toFixed(2);
			document.getElementById('orderTotal').innerHTML = ordTot;
			document.getElementById('inputOrderTotal').value = ordTot;
		}
	}
}
function calcShipping(){
	if(document.getElementById('shippingCalc')){
		var s = document.getElementById('shippingCalc');
		var of = document.getElementById('orderDetails');
		var ti = document.getElementById('totItems')
		var q = of.getElementsByTagName('input');
		var cty = document.getElementById('custCountry');
		var c = new Number;
		var ship;
		var i;
		for(i = 0; i < q.length; i++){
			c += parseFloat(q[i].value);
		}
		if(cty.value == 'NZ'){
			ship = c*3;
		}else{
			ship = c*5;
		}
		ti.innerHTML = c;
		s.innerHTML = ship.toFixed(2);
		ordTot = new Number(orderTotal + ship);
		document.getElementById('orderTotal').innerHTML = ordTot.toFixed(2);//formats to currency
		document.getElementById('inputOrderTotal').value = ordTot;
	}
}
function detailsFormSubmit(){
	if(document.getElementById('customerDetails')){
		fCD	= document.getElementById('customerDetails');
		fCD.onsubmit = validateDetails;
	}
}
//validate customer details when buying products and displays error on failure, submits form on success
function validateDetails(){
	var e = document.getElementById('email');
	var fn = document.getElementById('firstName')
	var ln = document.getElementById('lastName')
	var p = document.getElementById('phone');
	var a = document.getElementById('address1');
	var su = document.getElementById('suburb');
	var st = document.getElementById('state');
	var pc = document.getElementById('pCode');
	var msg = "The following fields have not been entered correctly:\n";
	var err = false;
//check for valid email address
	if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(e.value)){
		err = true;
		msg += "Email Address\n";
	}
//Check firstname field is longer than 2 characters	
	if(fn.value.length < 2){
		err = true;
		msg += "First Name\n";
	}
//Check lastname field is longer than 2 characters	
	if(ln.value.length < 2){
		err = true;
		msg += "Last Name\n";
	}
// Check phone number entered correctly
	if(!/^\+?\d{0,5}\-?\(?\d{1,}\)?[0-9\-]{7,}$/.test(p.value)){
		err = true;
		msg += "Phone\n";
	}
//check if address has been entered
	if(a.value.length < 2){
		err = true;
		msg += "Address\n"
	}
//check if suburb has been entered
	if(su.value.length < 2){
		err = true;
		msg += "Suburb/City\n"
	}
//check if state has been entered
	if(st.value.length < 2){
		err = true;
		msg += "State/Province\n"
	}
//check if address has been entered
	if(pc.value.length < 3){
		err = true;
		msg += "PostCode/ZIP\n"
	}
//if all ok return true (submit the form)
	if(err){
		alert(msg);
		return false;
	}else{
		return true;
	}
}
