window.onload = init;

function init() {
	
	var dlButton = document.getElementById('download');
	if(dlButton) {
            dlButton.onclick = download;
	}
	
	var tshirtButton = document.getElementById('buyTshirt');
	var cdButton = document.getElementById('buyCD');
	var posterButton = document.getElementById('buyPoster');
	var digitalAlbumButton = document.getElementById('buyDigitalAlbum');
        
    orderErrors = false;
        
	tshirtButton.onclick = function() { basket('tshirt'); }
	cdButton.onclick = function() { basket('CD'); }
	posterButton.onclick = function() { basket('poster'); }
	digitalAlbumButton.onclick = function() { basket('digitalAlbum'); }
}

function download() {
	document.getElementById('dlResponse').innerHTML = '<img src="images/loader.gif" />';
	
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
	    return;
	}
	var code = document.getElementById('code').value;
	var email = document.getElementById('dlEmail').value;
	var url = "js/ajax.php?action=download&code=" + code + "&email=" + email + "&sid=" + Math.random();
	
	xmlHttp.onreadystatechange = function(){
	    if(xmlHttp.readyState == 4) {
		// Everything is OK!
		document.getElementById('dlResponse').innerHTML = xmlHttp.responseText;			
	    }
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);	
}

function basket(product) {
	if(product == 'tshirt') {
		num = Math.floor(Math.random()*9999);
		$('#basket').append("<p><label>T-shirt</label><select  rel='tshirt' id='tshirtQty_"+num+"' name='"+num+"' onchange='update(\"tshirt\", this.name)'><option value='0'>Quantity</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select><select id='tshirtType_"+num+"' name='"+num+"' onchange='update(\"tshirt\", this.name)'><option value='0'>Type</option><option value='mens'>Mens</option><option value='womens'>Womens</option></select><select id='tshirtSize_"+num+"' name='"+num+"' onchange='update(\"tshirt\", this.name)'><option value='0'>Size</option><option value='s'>Small</option><option value='m'>Medium</option><option value='l'>Large</option><option value='xl'>X-Large</option><option value='2xl'>2X-Large</option></select><select id='tshirtColour_"+num+"' name='"+num+"' onchange='update(\"tshirt\", this.name)'><option value='0'>Colour</option><option value='organic'>Organic</option><option value='asphalt'>Asphalt</option></select></p>");
		$('#basket').append("<input type='hidden' id='"+num+"' product='tshirt' qty='0' value='' />");
	}
	if(product == 'CD' && !document.getElementById('cdQty')) {
		num = Math.floor(Math.random()*9999);
		$('#basket').append("<p><label>CD</label><select name='"+num+"' id='cdQty' onchange='update(\"cd\", this.name)'><option value='0'>Quantity</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select></p>");
		$('#basket').append("<input type='hidden' id='"+num+"' product='cd' qty='0' value='' />");
	}
	if(product == 'poster' && !document.getElementById('posterQty')) {
		num = Math.floor(Math.random()*9999);
		$('#basket').append("<p><label>A3 Poster</label><select name='"+num+"' id='posterQty' onchange='update(\"poster\", this.name)'><option value='0'>Quantity</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select></p>");	
		$('#basket').append("<input type='hidden' id='"+num+"' product='poster' qty='0' value='' />");
	}	
	if(product == 'digitalAlbum' && !document.getElementById('digitalAlbumQty')) {
		num = Math.floor(Math.random()*9999);
		$('#basket').append("<p><label>Digital album</label><select name='"+num+"' id='digitalAlbumQty' onchange='update(\"digitalAlbum\", this.name)'><option value='0'>Quantity</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select></p>");	
		$('#basket').append("<input type='hidden' id='"+num+"' product='poster' qty='0' value='' />");
	}
}

function update(product, name) {
	if(product == 'tshirt') {
            type = document.getElementById('tshirtType_' + name).value;
            if(type == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            qty = document.getElementById('tshirtQty_' + name).value;
            if(qty == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            size = document.getElementById('tshirtSize_' + name).value;
            if(size == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            colour = document.getElementById('tshirtColour_' + name).value;
            if(colour == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            document.getElementById(name).value = type + '-' + size + '-' + colour + '-' + qty;
            document.getElementById(name).qty = qty;
	} else if(product == 'cd') {
            qty = document.getElementById('cdQty').value;
            if(qty == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            document.getElementById(name).value = 'cd-' + qty;
            document.getElementById(name).qty = qty;
	} else if(product == 'poster') {
            qty = document.getElementById('posterQty').value;
            if(qty == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            document.getElementById(name).value = 'poster-' + qty;
            document.getElementById(name).qty = qty;
	} else if(product == 'digitalAlbum') {
			qty = document.getElementById('digitalAlbumQty').value;
            if(qty == 0) {
                orderErrors = true;
            } else {
                orderErrors = false;
            }
            document.getElementById(name).value = 'digitalAlbum-' + qty;
            document.getElementById(name).qty = qty;	
	}

	calculate();
        
    $('#errors').fadeOut();
        
}

function calculate() {
    
	// Prices
	var tshirtPrice = 35;
	var cdPrice = 20;
	var posterPrice = 12;
	var digitalAlbumPrice = 12;
	var postage = 0;
	var subtotal = 0;
	
	// Quantities
	
	if(document.getElementById('digitalAlbumQty')) {
	    var digitalAlbumQty = document.getElementById('digitalAlbumQty').value;
	} else {
	    var digitalAlbumQty = 0;	
	}
	
	if(document.getElementById('posterQty')) {
	    var posterQty = document.getElementById('posterQty').value;
		postage = 3;
	} else {
	    var posterQty = 0;	
	}
        
	if(document.getElementById('cdQty')) {
	    var cdQty = document.getElementById('cdQty').value;
	    postage = 4;
	} else {
	    var cdQty = 0;	
	}

	tshirtsQty = 0;
	tshirts = $('input[product="tshirt"]');
	tshirtsCount = tshirts.length;
	if(tshirtsCount >= 1) {
            for(i = 0; i <= tshirtsCount-1; i++) {
                if(tshirts[i].qty) {
                        tshirtsQty += parseInt(tshirts[i].qty);	
                }
            }
            postage = 4;
	}
	subtotal = (cdQty * cdPrice) + (posterQty * posterPrice) + (tshirtsQty * tshirtPrice) + (digitalAlbumQty * digitalAlbumPrice);
	
	totalsOutput = document.getElementById('totals');
	totalsOutput.innerHTML = "<p><strong>Sub total:</strong> $" + subtotal + "<br /><strong>Postage:</strong> $" + postage + "<br /><strong>TOTAL:</strong> $" + (postage + subtotal) + "</p><div id='purchaseForm'><p><label for='purchaseName'>Name:</label> <input type='text' id='purchaseName' /></p><p><label for='purchaseEmail'>Email:</label></p><p><input type='text' id='purchaseEmail' /></p><p><label for='purchaseAddress'>Delivery address:</label></p><p><input type='text' id='purchaseAddress' /></p><p><a href='#basket' id='orderNow' onclick='processOrder()'>Order now!</a></p></div>";
        
        orderTotals = [];
        orderTotals['subtotal'] = subtotal;
        orderTotals['postage'] = postage;
        
}

function processOrder() {
    
    // Get customer details (Calculate function will overwrite the form, so data must be grabbed here)
    var name = document.getElementById('purchaseName').value;
    var email = document.getElementById('purchaseEmail').value;
    var address = document.getElementById('purchaseAddress').value;
    
    if(!name || !email || !address) {
        orderErrors = true;
    }
    
    var pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    var matches = pattern.test(email);
    if(!matches) {
        orderErrors = true;
    } else {
        orderErrors = false;
    }
    
    if(!orderErrors) {    
        // Calculate
        calculate();
        var subtotal = orderTotals['subtotal'];
        var postage = orderTotals['postage'];
        
        // Generate order
        var order = [];
        
        // Get posters
        if(document.getElementById('posterQty')) {
            var posterQty = document.getElementById('posterQty').value;
            order.push('poster-' + posterQty);
        }
        // Get CDs
        if(document.getElementById('cdQty')) {
            var cdQty = document.getElementById('cdQty').value;
            order.push('cd-' + cdQty);
        }
		// Get Downloads
        if(document.getElementById('digitalAlbumQty')) {
            var digitalAlbumQty = document.getElementById('digitalAlbumQty').value;
            order.push('digitalAlbum-' + cdQty);
        }
        // Get Tshirts
        tshirtsQty = 0;
        tshirts = $('input[product="tshirt"]');
        tshirtsCount = tshirts.length;
        if(tshirtsCount >= 1) {
            for(i = 0; i < tshirtsCount; i++) {
                order.push('tshirt-' + tshirts[i].value);	
            }
        }
        
        // Ajax - process order
        xmlHttp = GetXmlHttpObject();
        if(xmlHttp == null) {
            return;
        }
        
        var url = "js/ajax.php?action=buy&products=";
        orderCount = order.length;
        for(i = 0; i < orderCount; i++) {
            url += (order[i] + ';');   
        }
        
        // Totals
        subtotal = orderTotals['subtotal'];
        postage = orderTotals['postage'];
        
        url += "&name=" + name + "&email=" + email + "&address=" + address + "&subtotal=" + subtotal + "&postage=" + postage;
        
        url += "&sid=" + Math.random();
        
        document.getElementById('totals').innerHTML = '<img src="images/loader.gif" />';
        
        xmlHttp.onreadystatechange = function(){
            if(xmlHttp.readyState == 4) {
                // Everything is OK!
                document.getElementById('merchOperation').innerHTML = xmlHttp.responseText;			
            }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    } else {
        $('#errors').hide();
        $('#errors').html("<p>Sorry, your order couldn't be processed. Please check the following:</p><ul><li>All options have been selected</li><li>Name, email address and delivery address have been filled in</li><li>Email address is correct</li></ul>");
        $('#errors').fadeIn();
    }
}

function GetXmlHttpObject() {
   var xmlHttp = null;
   try {
    xmlHttp=new XMLHttpRequest();
   } 
   catch (e) {
     try {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
     } 
     catch (e) {
      alert("Sorry, the shop is not compatible with your browser!");
      return false;  
     }  
  }
  return xmlHttp;  
}
