// JavaScript Document
var clothingObj = null; // current swf obj used in main display
var currentItem = null; // current item in clothing_templates Array
var currentArea = null;
var clothingImageArray = [];
var orderObj = []; // faux associatve array used to gather colour specs
var clothingOrderHasBeenSent = false;

var clothing_templates = [
						  
	{itemName: "Polo Top",
	swfPath: "polo_top.swf",
	thumbnailID: "polo_top",
	dimensions: [284, 256],
	swfObj: null,
	colours: ["Navy", "Sky", "Royal", "Yellow", "Red", "White", "Black", "Maroon", "Purple", "Emerald", "Bottle green"],
	areas: ["Collar", "Sleeves", "Body", "Sides"],
	sizes: ["Small", "Medium", "Large", "XL"]
	},
	
	
	{itemName: "Tracksuit Top",
	swfPath: "tracksuit_top.swf	",
	thumbnailID: "tracksuit_top",
	dimensions: [432, 260],
	swfObj: null,
	colours: ["Navy", "Sky", "Royal", "Yellow", "Red", "White", "Black", "Maroon", "Purple", "Emerald", "Bottle green"],
	areas: ["Sleeves", "Sides", "Body"],
	sizes: ["Small", "Medium", "Large", "XL"]
	},
	
	{itemName: "Tracksuit Bottom",
	swfPath: "tracksuit_bottoms.swf	",
	thumbnailID: "tracksuit_bottoms",
	dimensions: [250, 282],
	swfObj: null,
	colours: ["Navy", "Sky", "Royal", "Yellow", "Red", "White", "Black", "Maroon", "Purple", "Emerald", "Bottle green"],
	areas: ["Main", "Side Panels"],
	sizes: ["Small", "Medium", "Large", "XL"]
	},
						  
	{itemName: "Hoodie",
	swfPath: "hoodie_ii.swf",
	thumbnailID: "hoodie",
	dimensions: [246, 272],
	swfObj: null,
	colours: ["Navy", "Sky", "Royal", "Yellow", "Red", "White", "Black", "Maroon", "Purple", "Emerald", "Bottle green"],
	areas: ["Hood", "Sleeves", "Body", "Pocket"],
	sizes: ["Small", "Medium", "Large", "XL"]
	}				  
					  
						  
						  
						  ]





function clothing_bindings(){
for(var i=0;i < clothing_templates.length;i++) {
var thisImage = getElm(clothing_templates[i].thumbnailID);
thisImage.i = i; // add as propery so we can pass "i" in onclick
thisImage.onclick = function(){getObj(this.i); currentItem = clothing_templates[this.i]};
thisImage.onmouseover = function(){this.style.border = "1px solid #888";};
thisImage.onmouseout = function(){this.style.border = "1px solid #fff";};

 }
getElm("cont_order_button").disabled = true;

$('#cont_order_button').bind('click', function() {
  		$("#clothing_form").slideToggle(300);
		this.onmouseout = function(){this.blur()};
		embedMini();
		getElm("custom_clothing_messageDiv").innerHTML = "";
			
		});	

$('#clothing_submit_button').bind('click', function() {
		gatherClothingEnquiryData();
		});	
	
	$('#hide_icon_form').bind('click', function() {
  		$("#clothing_form").slideToggle(300);
		});
	
	
	// preload these images
	if (document.images) {
		var clothingImageArray = [
		["custom_clothing/images/white_gell_background.png"],
		["custom_clothing/images/top_small_grey_panel.png"],
		["custom_clothing/images/background.png"]
		]
	var len = clothingImageArray.length;
	var imageObj = new Image();
	 for(var i=0;i < len;i++) {
		imageObj.src = clothingImageArray[i];
	 }
	 }
   }



function deleteprior(div){
	while (div.firstChild) 
 	{
    div.removeChild(div.firstChild);
 	}
	}
	
function getObj(key){
var params = {wmode: "transparent"};
var width = clothing_templates[key].dimensions[0];
var height = clothing_templates[key].dimensions[1];
swfobject.embedSWF("custom_clothing/swf/"+clothing_templates[key].swfPath, "templateDiv", width, height, "9.0.0", false, false, params, false, getRef);
createAreaButtons(clothing_templates[key]);	
createColourPicker(clothing_templates[key]);
	function getRef(e){
	clothingObj = e.ref;
	}
	getElm("clothing_instructions").style.display = "block";
	getElm("cont_order_button").disabled = false;
}

function embedMini(){
	var params = {wmode: "opaque"};
	swfobject.embedSWF("custom_clothing/swf/"+currentItem.swfPath, "orderSwfwDiv", "142", "128", "9.0.0", false, false, params, false, displayForm);
}

function getElm(elm){
return document.getElementById(elm);

}

// this allows for IE bugs when trying to create dynamic radio buttons
function createRadioElement( name, checked ) {
    var radioInput;
    try {
        var radioHtml = '<input type="radio" name="' + name + '"';
        if ( checked ) {
            radioHtml += ' checked="checked"';
        }
        radioHtml += '/>';
        radioInput = document.createElement(radioHtml);
    } catch( err ) {
        radioInput = document.createElement('input');
        radioInput.setAttribute('type', 'radio');
        radioInput.setAttribute('name', name);
        if ( checked ) {
            radioInput.setAttribute('checked', 'checked');
        }
    }

    return radioInput;
}



function createAreaButtons(obj){
var areaButsDiv = getElm("area_buttons");
deleteprior(areaButsDiv);
for(var i=0;i < obj.areas.length;i++) {
	var span = document.createElement("span");
	var checked = (i==0)? true : false;
	var but = createRadioElement("areaTabGroup", checked);
	
	but.area = obj.areas[i]; // to pass out
	but.id = "but_"+i;
	but.style.cssText = "vertical-align: middle";
	
	if (i == 0){
		but.checked = true;
		currentArea = obj.areas[i];
	}
	but.onclick = function(){ currentArea = this.area };
	//but.value = obj.colours[i];
	var label = document.createElement("label");
	label.style.cssText = "margin-left: 3px;";
	label.htmlFor = "but_"+i; 
	var textNode = document.createTextNode(obj.areas[i]);
	label.appendChild(textNode);
	label.appendChild(but);
	span.appendChild(but);
	span.appendChild(label);
	areaButsDiv.appendChild(span);
	var br = document.createElement("br");
	areaButsDiv.appendChild(br);
 }
	
}




function createColourPicker(obj){
	var tabsDiv = getElm("tabs");
	tabsDiv.style.cssText = "font-size: 1.3em;"
	deleteprior(tabsDiv);
	for(var i=0;i < obj.colours.length;i++) {
	
		var colourTab = document.createElement("div");
		var colourValue;
		switch( obj.colours[i] ){
			case "Navy":
			colourValue = "#000080";
			break;
			case "Sky":
			colourValue = "#4fc1f5";
			break;
			case "Royal":
			colourValue = "#001ca8";
			break;
			case "Yellow":
			colourValue = "#f3e800";
			break;
			case "Red":
			colourValue = "#ff3333";
			break;
			case "White":
			colourValue = "#ffffff";
			break;
			case "Black":
			colourValue = "#000000";
			break;
			case "Maroon":
			colourValue = "#800000";
			break;
			case "Purple":
			colourValue = "#800080";
			break;
			case "Emerald":
			colourValue = "#009a3d";
			break;
			case "Bottle green":
			colourValue = "#006400";
			break;
			default: colourValue = "#999999";
		}
		colourTab.style.cssText = "vertical-align: middle; float:left; width: 20px; height: 20px; margin-bottom: 3px; margin-right: 6px; border: 1px solid #000; cursor: pointer; background-color: "+colourValue;
		colourTab.colourVal = colourValue; // add crafty property to carry values to feed to onclick
		colourTab.colourName = obj.colours[i];
		colourTab.onclick = function(){sendValueToSwf(this.colourName, this.colourVal)};
		tabsDiv.appendChild(colourTab);
		// also add onclick to discriptive text field
		var p = document.createElement("p");
		p.colourVal = colourValue;
		p.colourName = obj.colours[i];
		p.onclick = function(){sendValueToSwf(this.colourName, this.colourVal)};
		p.style.cssText = "float: left; width: 90px;  margin-bottom: 0; margin-top: 0; cursor: pointer; "
		var textNode = document.createTextNode(obj.colours[i]);
		p.appendChild(textNode);
		tabsDiv.appendChild(p);
		var div = document.createElement("div");
		div.style.cssText = "clear: both;";
		tabsDiv.appendChild(div);
	}
	
}

// send values to swf
function sendValueToSwf(colName, colValue){
try{
clothingObj.receiveValues(colValue, currentArea);
clothingObj[currentArea] = colValue;
}catch(e){
alert("Sorry, there was an error: "+e.description);	
}
orderObj[currentArea] = colName;
}

function displayForm(e){
var	miniObj = e.ref;
setTimeout(fill, 500); // timer to allow swf to embed
	// fill clothing template with colours as per large version
	function fill(){
	for(var i=0;i < currentItem.areas.length;i++) { 
	var colValue = clothingObj[ currentItem.areas[i]];
	if(colValue) miniObj.receiveValues(colValue, currentItem.areas[i]); 
	}
	}
	var label;
	// make size list
	var sizeButsDiv = getElm("inputs");
	//sizeButsDiv.style.cssText = "font-size: 1.2em";
	deleteprior(sizeButsDiv);
	label = document.createElement("label");
	var textNode = document.createTextNode("Size: ");
	label.appendChild(textNode);
	sizeButsDiv.appendChild(label);
	var sizeListbox = document.createElement("select");
	sizeListbox.id = "size";
	for (var i=0; i<currentItem.sizes.length; i++){
	sizeListbox.options[i] = new Option(currentItem.sizes[i], currentItem.sizes[i]);
	}
	sizeButsDiv.appendChild(sizeListbox);
	var br = document.createElement("br");
	sizeButsDiv.appendChild(br);
	// quantity box
	label = document.createElement("label");
	var textNode = document.createTextNode("Quantity: ");
	label.appendChild(textNode);
	sizeButsDiv.appendChild(label);
	var input = document.createElement("input");
	input.id = "quantity";
	input.setAttribute('type', 'text');
	input.setAttribute('id', 'quantity');
	input.setAttribute('size', '5');
	sizeButsDiv.appendChild(input);
	var br = document.createElement("br");
	sizeButsDiv.appendChild(br);
	label = document.createElement("label");
	label.style.cssText = "display: block; margin-top: 10px; font-size: 0.8em;";
	var textNode = document.createTextNode("(Minimum quantities apply)");
	label.appendChild(textNode);
	sizeButsDiv.appendChild(label);
	}
	
	function gatherClothingEnquiryData(){
	var error_flag = false;
	var size = getElm("size").value;	
	var quantity = getElm("quantity").value;
	var organisation = getElm("cc_organisation").value;
	var delivery_address = getElm("cc_delivery_address").value.replace(/\r\n|\n/g,'<br />');
	var account_num = getElm("cc_account_num").value;
	var email = getElm("cc_email").value;
	var name = getElm("cc_name").value;
	var phone = getElm("cc_phone").value;
	var message_Div = getElm("custom_clothing_messageDiv");
	
	//form checking
	if (!valid_email_check(email)) error_flag = 2;
	if (!organisation)  error_flag = 1;
	if (!delivery_address)  error_flag = 1;
	if (!name) error_flag = 1;
	if (!phone) error_flag = 1;
	
		switch(error_flag){
		case 1:
	 	message_Div.innerHTML = "Sorry, a mandatory field has not been completed.";
		return;
		break;
		case 2:
		document.getElementById("email").focus();
		message_Div.innerHTML = "Sorry, the e-mail address is incomplete or malformed.";
		return;
		break
		}
		
	/*if(clothingOrderHasBeenSent){
	alert("Sorry, this order has already been sent.");
	return;
	} */
	 if (!error_flag){
		// parse product colours
		var clothingSpec = [];	
		for (var area in orderObj) { 
		clothingSpec.push( {area: area, colour: orderObj[area]} ); // get into obj array so we can get its length etc.
		}
		
		var thetables = '<table width="100%" border="1" cellpadding="4" cellspacing="1" style="border-collapse: collapse; font-family:Arial,Helvetica,sans-serif;font-size:11px;">';
		thetables += '<tr style="background-color: #eee;"><td><b>Item:</b> '+currentItem.itemName+'</td><td><b>Size:</b> '+size+'</td><td><b>Quantity:</b> '+quantity+'</td></tr>';
		for(var i = 0; i < clothingSpec.length; i++) {
		thetables += '<tr><td colspan="3"><b>'+clothingSpec[i].area+':</b> '+clothingSpec[i].colour+'</td></tr>';
		}
					
	thetables += '</tr></table>';
		 
		var sendstring = 'organisation='+organisation+'&delivery_address='+delivery_address+'&account_num='+account_num;
		 sendstring+= '&email='+email+'&name='+name+'&phone='+phone+'&size='+size+'&quantity='+quantity+'&thetables='+thetables;
		 
		post_clothing_enquiry(sendstring);
		
	 }

	}
	
	function post_clothing_enquiry(sendstring){
	var message_Div = getElm("custom_clothing_messageDiv");
	message_Div.innerHTML = "<img src='images/ajax-loader.gif' />";
	var ajaxRequest = setupAJAX();	
	ajaxRequest.open("POST", "php/send_clothing_enquiry_to_woolmers.php", true); 
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//Wait for response
	ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4){
		    if(ajaxRequest.status==200){
			var returned_message = ajaxRequest.responseText;
			if(returned_message == 1){
			message_Div.innerHTML = "Thank you for your enquiry - we will contact you in due course";	
			clothingOrderHasBeenSent = true;
			}else{
			message_Div.innerHTML = "Sorry, there was a server problem, please try again later.\n\nIf the problem persists please use e-mail, fax or phone to send us your order.";	
			}
			}else{
            message_Div.innerHTML = "Sorry, there was a server problem, please try again later.\n\nIf the problem persists please use e-mail, fax or phone to send us your order.";
			}
		}
	}
	ajaxRequest.send(sendstring);

	}
