// JavaScript Document

var steps = {};
var fileUploader = null;
var binderDimensions = {};
var extraAnswer = false;
//actual dims
//a3 width 297mm height 420mm

//a3land width 420mm height 297mm
//a4 width 210mm height 297mm
//a4land width 297mm height 210mm
//a5 width 210mm height 148mm 
//a6 width 148mm height  105mm


/*
binderDimensions["A3"] = {"page" : {"height":"300","width":"200"}, "spine" : {"height":"300","width":"30"}}
binderDimensions["A3Land"] = {"page" : {"height":"175","width":"200"}, "spine" : {"height":"175","width":"30"}}
binderDimensions["A4Prof"] = {"page" : {"height":"250","width":"175"}, "spine" : {"height":"250","width":"25"}}
binderDimensions["A4Land"] = {"page" : {"height":"175","width":"200"}, "spine" : {"height":"175","width":"30"}}
binderDimensions["A5"] = {"page" : {"height":"200","width":"150"}, "spine" : {"height":"200","width":"20"}}
binderDimensions["A6"] = {"page" : {"height":"125","width":"100"}, "spine" : {"height":"125","width":"15"}}

var capacitySize = {};
capacitySize["15"] = "15";// { "name": "15" "size": "26" };
capacitySize["25"] = "25";// { "name": "25" "size": "38" };
capacitySize["40"] = "40";//{ "name": "40" "size": "53" };
capacitySize["50"] = "50";//{ "name": "50" "size": "70" };
capacitySize["65"] = "65";//{ "name": "65" "size": "90" };


var mechanismSize = {};
mechanismSize["2D"] = { "height": 125, "width": 20 }
mechanismSize["3D"] = { "height": 209, "width": 20 }
mechanismSize["4D"] = { "height": 286, "width": 20 }
mechanismSize["lever"] = { "height": 94, "width": 55 }
*/

binderDimensions["A3"] = {
	"page" : {"height":"300","width":"200"},
	"spine" : {"height":"300","width":"30"},
	"capacityDimensions" : {"15" : [440,715], "25" : [440,734], "40" : [440,772] }, 
	"binderCSS" : {
		'2D':{'height' : '60%', 'top' : '22%'},
		'3D':{'height' : '70%', 'top' : '16%'},
		'4D':{'height' : '80%', 'top' : '11%'},
		'LeverArch':{'height' : '150px', 'top' : '10%'}
	}
}
binderDimensions["A4Prof"] = {
		"page" : {"height":"250","width":"175"},
		"spine" : {"height":"250","width":"25"},
		"capacityDimensions" : {"15" : [311,535], "25" : [ 311,557], "40" : [311,592], "50" : [311,637], "65" : [311,671] },
		"capacityLeverArchDimensions" :  {"15" : [311,535], "25" : [ 311,557], "40" : [311,613], "50" : [311,631], "65" : [311,643] },
		"binderCSS" : {
		'2D':{'height' : '80%', 'top' : '10%'},
		'3D':{'height' : '85%', 'top' : '8%'},
		'4D':{'height' : '85%', 'top' : '8%'},
		'LeverArch':{'height' : '150px', 'top' : '20%'}
	}
}
binderDimensions["A4Land"] = {
		"page" : {"height":"175","width":"200"},
		"spine" : {"height":"175","width":"30"},
		"capacityDimensions" : {"15" : [230,704], "25" : [230,734], "40" : [230,772], "50" : [230,800]},
		"binderCSS" : {
		'2D':{'height' : '70%', 'top' : '16%'},
		'3D':{'height' : '80%', 'top' : '10%'},
		'4D':{'height' : '80%', 'top' : '10%'},
		'LeverArch':{'height' : '150px', 'top' : '10%'}
		}
}
binderDimensions["A5"] = {
		"page" : {"height":"200","width":"150"},
		"spine" : {"height":"200","width":"20"},
		"capacityDimensions" : {"15" : [225,400], "25" : [225,417], "40" : [225,456],  "50" : [225,491], "65" : [225,529]},
		"binderCSS" : {
		'2D':{'height' : '80%', 'top' : '10%'},
		'3D':{'height' : '80%', 'top' : '10%'},
		'4D':{'height' : '85%', 'top' : '7%'},
		'LeverArch':{'height' : '150px', 'top' : '14%'}
		}
}

var capacitySize = {};
capacitySize["15"] = "26";// { "name": "15" "size": "26" };
capacitySize["25"] = "38";// { "name": "25" "size": "38" };
capacitySize["40"] = "53";//{ "name": "40" "size": "53" };
capacitySize["50"] = "70";//{ "name": "50" "size": "70" };
capacitySize["65"] = "90";//{ "name": "65" "size": "90" };

var quationAnswers = {};

var mechanismSize = {};
mechanismSize["2D"] = { "height": 124, "width": 20 }
mechanismSize["3D"] = { "height": 209, "width": 20 }
mechanismSize["4D"] = { "height": 286, "width": 20 }
mechanismSize["lever"] = { "height": 94, "width": 55 }

var $stepNumber = 0
var $answerText = "";
var $answerUnformattedText = "";
var $configuration = "";
var $quantity = 1
//var $productID = 32582;
//var $productID = 32583;
var $productID = 31074;
var $answers = {};//{ 0:{"id":"none","text":"none","unformattedText":"none"}};
var $numquestions = 0;
var $webBiviCode = null
var $error = false;
var $areaToConfigure = "inside";
var $currentArea = "inside";
var $uploadeFile = null;
var $originalFile = null;

var steps = {};


(function($){				
	$.extend({
		winman:
		{
			finish: function(quantity, binderList)
			{
				var html = $.ajax({ 
						type: "POST",
						url: '/winman/configurator_finish',
						async: false,
						data: {'data[product]' : $productID, 'data[quantity]' : quantity, 'data[configuration]' : $configuration, 'data[binderProp]' : $.toJSON(binderList) }	
					}).responseText;	
				if(html.indexOf("error") != -1)
				{
					json = "error";
				}
				else
				{
					eval("json = "+ html);
				}
				
				return json;
			},
			answer: function(value)
			{				
				var html = $.ajax({ 
							type: "POST",
							url: '/winman/configurator_answer',
							async: false,
							data: {'data[product]' : $productID, 'data[quantity]' : $quantity, 'data[configuration]' : $configuration, 'data[answerId]': value}	
						}).responseText;
				
				eval("answer = " + html);
				return answer;				
			},
			returnVisibleOptions: function(questionID)
			{				
				$answerID = 'None';	
				var html = $.ajax({ 
					type: "POST",
					url: '/configurator/configurator_getMenuContents',
					async: false,
					data: {'data[product]' : $productID, 'data[quantity]' : $quantity, 'data[configuration]' : $configuration, 'data[question]': questionID}	
				}).responseText;
				eval("answerList = " + html);
				return answerList;
			},
			getQuestions: function()
			{
				var html = $.ajax({ 
					type: "POST",
					//url: '/winman/configurator_start', 
					url: '/configurator/configurator_getQuestionList',
					async: false,
					data: {'data[product]' : $productID}	
				}).responseText;
				if(html.indexOf("error") != -1 || html == "")
				{
					json = "error";
				}
				else
				{
					eval("json = "+ html);
				}
				return json;
			},
			reprice: function(quantity, id)
			{
				if(id == null || id == "")
				{
					id = $webBiviCode
				}
				var html = $.ajax({ 
						type: "POST",
						url: '/winman/configurator_rePrice',
						async: false,
						data: {'data[product]' : id, 'data[quantity]' : quantity, 'data[configuration]' : $configuration }	
					}).responseText;			
				if(html.indexOf("error") != -1)
				{
					json = "error";
				}
				else
				{
					eval("json = "+ html);
				}
				return json;
			}
		},
		display: 
		{
			fullDescription: function(description)
			{
		
				var a = document.createElement("a");
				a.href = "/configurator/description?description=" + escape(description)
				a.rel = "lyteframe";
				a.title = "Full Description";
				a.rev = "width: 700px; height: 300px";
				myLytebox.start( a, false, true);	
			},
			help: function(toShow)
			{
				var a = document.createElement("a");
				a.href = "/configurator/help/" + toShow
				a.rel = "lyteframe";
				a.title = "Configurator Help";
				a.rev = "width: 700px; height: 500px; scrolling: auto;";
				myLytebox.start( a, false, true);	
			},
			changeDisplay: function(clickedItem, menuID)
			{				
			
				currentID = $(clickedItem).attr('id');
				classNames = $(clickedItem)[0].className;
				
			
				numQuestions = $.configurator.getObjectSize(steps[$stepNumber].stepOptions);
				currentQuestion = $.configurator.findCurrentQuestion(menuID, clickedItem,-1)

				$answerText = $(clickedItem).parent().attr('id');
				$answerUnformattedText = $(clickedItem).attr('title');
			
				if(classNames.indexOf("current") > -1 || classNames.indexOf("colourList") > -1 )
				{					
					if(steps[$stepNumber].stepOptions.type == "group")
					{
						$answers[currentQuestion] = {};
						$answers[currentQuestion] = {"id": classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ",""), "text":$answerText,"unformattedText":$answerUnformattedText, "menuID":menuID}
						answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");
					}
					else
					{
						$answers[currentQuestion] = {};
						$answers[currentQuestion] = {"id": classNames.replace("current", "").replace("headerOption", "").replace("colourList", "").replace(" ",""), "text":$answerText,"unformattedText":$answerUnformattedText, "menuID":menuID}
						answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");
					}					
				}
				else
				{
					if(steps[$stepNumber].stepOptions.type == "group")
					{
						$answers[currentQuestion] = {};
						$answers[currentQuestion] = {"id": classNames, "text":$answerText,"unformattedText":$answerUnformattedText, "menuID":menuID} 				
						answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");
					}
					else
					{
						$answers[currentQuestion] = {};
						$answers[currentQuestion] = {"id": classNames, "text":$answerText,"unformattedText":$answerUnformattedText, "menuID":menuID} 				
						answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");
					}					
				}

				$.configurator.makeActive($(clickedItem))
			
				switch(menuID)
				{
					case 'binder_size': $.display.changeBinderDisplay(currentID); break;
					case 'capacity': $.display.changeCapacityDisplay(currentID); break;
					case 'mechanism': $.display.changeMechanismDisplay(currentID); break;
					case 'inside_front_pocket': $.display.changePocketImage(currentID, "front", currentQuestion, menuID); break;
					case 'inside_back_pocket': $.display.changePocketImage(currentID, "back", currentQuestion, menuID); break;
					case 'material_outer_type' : $.display.changeColourDisplay(currentID); break;
					case 'encapsulation_clear_overlay' : $.display.changeEncapsulation(currentID, currentQuestion, menuID); break;
					case 'spine_pocket' : $.display.changeSpinePocket(currentID, currentQuestion, menuID); break;
					case 'material_outer_range' : $.display.changeColourList($(clickedItem), answerID); break;
					case 'printing': $.display.changePrintOptions(currentID); break;
				}
				
			},
			changePrintOptions: function(currentID)
			{
				$('.selectedPrint').html($('#'+currentID).text() + ' selected')
			},
			changeColourList: function(currentItem, answerID)
			{
				//$.display.showLoader();
				$.display.showLoader();
				setTimeout(function() { $.display.doChangeColourList(currentItem, answerID)},200);
				
			},
			doChangeColourList: function(currentItem, answerID)
			{
				$.display.removeColour();
				currentQuestion = $.configurator.findCurrentQuestion('material_outer_range', currentItem,-1);
				$('li',$('#config_options')).css({ 'background-color' : '#FFF' });
				$('.current',$('li',$('#config_options'))).removeClass('current')
				$($(currentItem).parent()).css({ 'background-color' : '#CCC' });
				$(currentItem).addClass('current')
				nextQuestion = parseInt(currentQuestion) + 1;
				answer = $.winman.answer(answerID);
				questionlist = $.winman.returnVisibleOptions(steps[$stepNumber].stepOptions[nextQuestion].id);
				$.display.showColours('material_outer_type', questionlist);
				
				$.display.hideLoader();
			},
			changeBinderDisplay: function(currentID)
			{
				dims = binderDimensions[currentID];
				$('.pageVert').css({'height': dims.page.height+'px','width': dims.page.width+'px' });
				$('.spineVert').css({'height': dims.spine.height+'px','width': dims.spine.width+'px' });
				$.display.updateDimensionsText(currentID);
				steps[0].stepOptions[0].binderReference = currentID;
			},
			updateDimensionsText: function(currentID)
			{
				$('#config_prod_preview').css('visibility','visible');
				$('#next_step img').css('visibility','visible');
				dims = binderDimensions[currentID];
								
				if(steps[2].stepOptions[0].capacityKey!=undefined){
					capacityWidth = steps[2].stepOptions[0].capacityKey;
				}
				else{
					capacityWidth = '15';
				}
				
				if(steps[1].stepOptions[0].answerText == 'lever_arch_mechanism')
				{										
					capacityWidthText = (dims.capacityLeverArchDimensions[capacityWidth]==undefined) ? dims.capacityLeverArchDimensions['15'][1] : dims.capacityLeverArchDimensions[capacityWidth][1];
				}
				else
				{
					capacityWidthText = (dims.capacityDimensions[capacityWidth]==undefined) ? dims.capacityDimensions['15'][1] : dims.capacityDimensions[capacityWidth][1];
				}
				$('#productWidth label').html(capacityWidthText+' mm');
				
				$rulerWidth = ((parseInt(dims.page.width)*2) + parseInt($('.spine').css('width')) );
																						
				$('#productWidth').css({'width': $rulerWidth+'px'});
				
				$('#productHeight label').html(dims.capacityDimensions[capacityWidth][0]+' mm').css({'background':'#ffffff','line-height' :'14px','margin-top' : Math.round(((dims.page.height)/2) - 6)+'px'});
				$('#productHeight').css({'height': dims.page.height+'px', 'margin-left':'22px'});
				
				
			},
			changeCapacityDisplay: function(currentID)
			{
				capacityWidth = capacitySize[currentID];
				$('.spine').css({"width": capacityWidth +"px" });
				steps[2].stepOptions[0].capacityKey = currentID;
				$.display.updateDimensionsText(steps[0].stepOptions[0].binderReference);
			},
			changeMechanismDisplay: function(currentID)
			{				
				$('#mechanismImage').attr({"src": "/img/configImgs/mech"+currentID+".png"});
				$('#rivetsImage').attr({"src": "/img/configImgs/rivets"+currentID+".png"});
			},
			changePocketImage: function(currentID, location, currentQuestion, menuID)
			{
				
				// Check for the landscape option...
				var myAnswerText = steps[0]["stepOptions"][0]["answerText"];
				var landscapeRegExp = /landscape/;
				var checkLandscape = myAnswerText.search(landscapeRegExp);
				if($('.inside').is(':hidden'))
				{
					$.display.showInside();	
				}
				
				if(location == "front" || location == "back" )
				{
					// Diagonal pockets for landscape overriden after...
						
					if(currentID.toLowerCase().replace(/,/gi,"").replace(" ", "_") == "cdpocket")
					{
						$backgroundImage = 'url(/img/configImgs/'+currentID.toLowerCase().replace(/,/gi,"").replace(" ", "_") +'_'+location.toLowerCase().replace(" ", "_").replace(/\)/gi,"").replace(/\(/gi,"")+'.png)';
						if($('.' + location,$('.inside')).css("backgroundImage") == $backgroundImage)
						{
							$('.' + location,$('.inside')).css({"background-image": 'none'});
							$wrapper = 'inside_'+location+'_pocket';
							$.configurator.makeInactive($('#'+currentID,$('#'+$wrapper)));
							if(location == "back")
							{
								$answers[currentQuestion] = {};
								$answers[currentQuestion] = {"id": 5094, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
								answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");		
							}
							else
							{
								$answers[currentQuestion] = {};
								$answers[currentQuestion] = {"id": 5089, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
								answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");	
							}
							return;
						}
						$wrapper = 'inside_'+location+'_pocket';
						$.configurator.makeInactive($('#'+$wrapper+' span'));
						$.configurator.makeActive($('#'+currentID,$('#'+$wrapper)));
						$('.' + location,$('.inside')).css({"background-image": $backgroundImage, "background-repeat":"no-repeat"});				
					
						if(location == "back")
						{
							$('.' + location,$('.inside')).css({"background-position" : "80% 50%" });
						}
						else
						{
							 $('.' + location,$('.inside')).css({"background-position" : "center 50%" });
						}
					}
					else if(currentID.toLowerCase().replace(/,/gi,"").replace(" ", "_") == "businesscardpocket")
					{
						$backgroundImage = 'url(/img/configImgs/'+currentID.toLowerCase().replace(/,/gi,"").replace(" ", "_") +'_'+location.toLowerCase().replace(" ", "_").replace(/\)/gi,"").replace(/\(/gi,"")+'.png)';
						if($('.' + location,$('.inside')).css("backgroundImage") == $backgroundImage)
						{
							$('.' + location,$('.inside')).css({"background-image": 'none'});
							$wrapper = 'inside_'+location+'_pocket';
							$.configurator.makeInactive($('#'+currentID,$('#'+$wrapper)));
							if(location == "back")
							{
								$answers[currentQuestion] = {};
								$answers[currentQuestion] = {"id": 5094, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
								answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");		
							}
							else
							{
								$answers[currentQuestion] = {};
								$answers[currentQuestion] = {"id": 5089, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
								answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");	
							}
							return;
						}
						$wrapper = 'inside_'+location+'_pocket';
						$.configurator.makeInactive($('#'+$wrapper+' span'));
						$.configurator.makeActive($('#'+currentID,$('#'+$wrapper)));
						$('.' + location,$('.inside')).css({"background-image": $backgroundImage, "background-repeat":"no-repeat"});				
					
						$('.' + location,$('.inside')).css({'background-position' : '14% 94%'});
					}
					else
					{
						binderSizeArray = myAnswerText.split('_');
						if(currentID == "diagonal")
						{
							if(binderSizeArray[1] == "landscape")
							{
								$backgroundImage = 'url(/img/configImgs/' + binderSizeArray[0] + "_" + binderSizeArray[1] + "_" + currentID + "_" + location + ".png)";
								
							}
							else
							{
								$backgroundImage = 'url(/img/configImgs/' +binderSizeArray[0] + "_" + currentID + "_" + location + ".png)";
							}
						}
						else
						{
							$backgroundImage = 'url(/img/configImgs/'+currentID.toLowerCase().replace(/,/gi,"").replace(" ", "_") +'_'+location.toLowerCase().replace(" ", "_").replace(/\)/gi,"").replace(/\(/gi,"")+'.png)';
						}
							
						if($('.' + location,$('.inside')).css("backgroundImage") == $backgroundImage)
						{
							$('.' + location,$('.inside')).css({"background-image": 'none'});
							$wrapper = 'inside_'+location+'_pocket';
							$.configurator.makeInactive($('#'+currentID,$('#'+$wrapper)));
							if(location == "back")
							{
								$answers[currentQuestion] = {};
								$answers[currentQuestion] = {"id": 5094, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
								answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");		
							}
							else
							{
								$answers[currentQuestion] = {};
								$answers[currentQuestion] = {"id": 5089, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
								answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");	
							}
							return;
						}
						$wrapper = 'inside_'+location+'_pocket';
						$.configurator.makeInactive($('#'+$wrapper+' span'));
						$.configurator.makeActive($('#'+currentID,$('#'+$wrapper)));
						$('.' + location,$('.inside')).css({"background-image": $backgroundImage, "background-repeat":"no-repeat"});		
					
					
						if(location == "back")
						{
							if(currentID == "diagonal")
							{
								$('.' + location,$('.inside')).css({"background-position" : "right bottom" });
							}
							else if(currentID == "horizontal")
							{
								$('.' + location,$('.inside')).css({"background-position" : "center center" });
							}
							else
							{
								$('.' + location,$('.inside')).css({"background-position" : "center center" });
							}
						}
						else
						{
							if(currentID == "diagonal")
							{
								$('.' + location,$('.inside')).css({"background-position" : "left bottom" });
							}
							else if(currentID == "horizontal")
							{
								$('.' + location,$('.inside')).css({"background-position" : "center center" });
							}
							else
							{
								$('.' + location,$('.inside')).css({"background-position" : "center center" });
							}
						}
					}

					
				}
				else
				{
					
				}
			},
			removeColour: function()
			{
				$('.box').css({"background-color":''});
			},
			changeColourDisplay: function(currentID)
			{
				$('.box').css({"background-color":'#'+currentID});
			},
			changeEncapsulation: function(currentID, currentQuestion, menuID)
			{			
				if($('#'+currentID).parent().is(".current"))
				{
					currentID = "";
					$('.config_overlays li').each( function(){$.configurator.makeInactive($(this))} );
					$answers[currentQuestion] = {};
					$answers[currentQuestion] = {"id": 5097, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
					answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");
				}
				else
				{
					$('.config_overlays li').each( function(){$.configurator.makeInactive($(this))} );
					$.configurator.makeActive($('#'+currentID).parent());
				}
				if(currentID == "of")
				{
					$('.front', $('.outside')).css({"background-image": "url('/img/configImgs/overlayHatch.png')" })
					$('.front', $('.outside')).css({"background-repeat": "no-repeat" })
					$('.front', $('.outside')).css({"background-position": '0 7px' })
					$('.spine', $('.outside')).css({"background-image": "none" })
					$('.back', $('.outside')).css({"background-image": "none" })
				}
				else if(currentID == "ofs")
				{
					$('.front', $('.outside')).css({"background-image": "url('/img/configImgs/overlayHatch.png')" })
					$('.front', $('.outside')).css({"background-repeat": "no-repeat" })
					$('.front', $('.outside')).css({"background-position": '0 7px' })
					$('.spine', $('.outside')).css({"background-image": "url('/img/configImgs/overlayHatch.png')" })
					$('.spine', $('.outside')).css({"background-repeat": "no-repeat" })
					$('.spine', $('.outside')).css({"background-position": '0 7px' })
					
					$('.back', $('.outside')).css({"background-image": "none" })
				}
				else if(currentID == "ef")
				{
					$('.front', $('.outside')).css({"background-image": "url('/img/configImgs/encpHatch.png')","background-repeat": "repeat"})
					$('.spine', $('.outside')).css({"background-image": "none" })
					$('.back', $('.outside')).css({"background-image": "none" })
				}
				else if(currentID == "efs")
				{
					$('.front', $('.outside')).css({"background-image": "url('/img/configImgs/encpHatch.png')","background-repeat": "repeat" })
					$('.spine', $('.outside')).css({"background-image": "url('/img/configImgs/encpHatch.png')","background-repeat": "repeat" })
					$('.back', $('.outside')).css({"background-image": "none" })
				}
				else if(currentID == "efbs")
				{
					$('.front', $('.outside')).css({"background-image": "url('/img/configImgs/encpHatch.png')","background-repeat": "repeat" })
					$('.spine', $('.outside')).css({"background-image": "url('/img/configImgs/encpHatch.png')","background-repeat": "repeat" })
					$('.back', $('.outside')).css({"background-image": "url('/img/configImgs/encpHatch.png')","background-repeat": "repeat" })
				}
				else
				{
					$('.front', $('.outside')).css({"background-image": "none" })
					$('.spine', $('.outside')).css({"background-image": "none" })
					$('.back', $('.outside')).css({"background-image": "none" })
				}	
				
				if(currentID.indexOf('ef') > -1)
				{
					extraAnswer = true;
					extraAnswerID = {'custToSupply' : 5125, 'DuraToPrint' : 5124} ;
				}
				else
				{
					extraAnswer = false;
				}
			},
			changeSpinePocket: function(currentID, currentQuestion, menuID)
			{
					
						
					
					//$('.spine').css({"background-image" : "url('/img/configImgs/spine.png)" });
					//toggle
					if($('.spine',$('.outside')).css('backgroundImage')=='none'){
						$('.spine',$('.outside')).css({'background-image' : "url('/img/configImgs/spinePocket.png')"});
						$('.spine',$('.outside')).css({'background-repeat' : "no-repeat"});
						$('.spine',$('.outside')).css({'background-position' : "center center"});
						
						$('.spine',$('.inside')).css({'background-image' : "url('/img/configImgs/spinePocketInner.png')"});
						$('.spine',$('.inside')).css({'background-repeat' : "no-repeat"});
						$('.spine',$('.inside')).css({'background-position' : "center center"});
					}
					else
					{
						$answers[currentQuestion] = {};
						$answers[currentQuestion] = {"id": 5084, "text":'None Selected',"unformattedText":'None Selected', "menuID":menuID} 				
						answerID = classNames.replace("current", "").replace("colourList", "").replace("headerOption", "").replace(" ","");
						
						$('.spine',$('.outside')).css({'background-image' : "none"});
						$('.spine',$('.outside')).css({'background-repeat' : "no-repeat"});
						$('.spine',$('.outside')).css({'background-position' : "center center"});
						
						$('.spine',$('.inside')).css({'background-image' : "none"});
						$('.spine',$('.inside')).css({'background-repeat' : "no-repeat"});
						$('.spine',$('.inside')).css({'background-position' : "center center"});
						$.configurator.makeInactive($('#'+currentID));
					}
			},
			showInside: function()
			{
				$('.outside').hide();
				$('#outsideLink').removeClass('selected');
				$('#insideLink').addClass('selected');
				$('.inside').show();
			},
			showOutside: function()
			{
				$('.outside').show();
				$('#outsideLink').addClass('selected');
				$('#insideLink').removeClass('selected');
				$('.inside').hide();
			},
			showColours: function(questionText, answerList)
			{
				$('li', $('#'+questionText)).remove();
				$.each(answerList, function(key, value)
				{
					if(value.AnswerText.indexOf('{') > -1)
					{											
						listText = value.AnswerText.split(" {");
						answername = listText[0];
						colourCode = listText[1].replace("}","");
					}
					else
					{
						listText = value.AnswerText.split(" (");
						answername = listText[0];
						colourCode = listText[1].replace(")","");
					}
					newHtml = '<li><span id="'+colourCode.replace("#","")+'" style="background-color:'+colourCode+'" class="'+value.AnswerId.toString()+' colourList" title="'+value.AnswerText+'"></span></li>';
					$('ul',$('#' + questionText)).append(newHtml)
				})
			
				$.configurator.makeOpacity($('span:not(.headerOption)', $('li')), false);
				
				$('span', $('li', $('#'+questionText))).bind('click', function() { $.display.changeDisplay($(this), questionText) });
				$('span:not(.headerOption)', $('li', $('#'+questionText))).hover(function() { if($(this).is('.current')) {} else{ $.configurator.makeOpacity($(this), true) }}, function() {  if($(this).is('.current')) {}else{ $.configurator.makeOpacity($(this), false) }} ) 
			},
			makeStepActive: function(stepID)
			{
				$('span',$('#config_tabs')).removeClass("current");
				$('#'+stepID, $('#config_tabs')).addClass("current");
				$('#config_tabs').show();
			},
			showLoader: function()
			{
				$('#loader').show();
			},
			hideLoader: function()
			{				
				$('#loader').hide();
				setTimeout("$('#productHeight').hide().show()",50);
	
			}
		},
		configurator: 
		{
			fillFileName: function()
			{
				$('#dummyFileName').val($('#configuratorFile').val())
			},
			doReprice: function()
			{
				quantity = $('#qtyToBuy').val();
				$('#quantityToBasket').val(quantity)
				returnedData = $.winman.reprice(quantity)
				if(returnedData != "error")
				{
					strPricePerUnit = returnedData.ConfiguratorRePriceResult.Price;
					strDiscountPerUnit = returnedData.ConfiguratorRePriceResult.Discounted;

					$('#pricePerUnit').html("&pound;" + (parseFloat(strPricePerUnit) / quantity).toFixed(2));
					$('#priceTotalCost').html("&pound;" + parseFloat(strPricePerUnit).toFixed(2));
					$('#BasketItemPrice').val(strPricePerUnit);
					//Over-ride total with discount amount if necessary
					if(strDiscountPerUnit != '')
					{
						$('#pricePerUnit').html("&pound;" + (parseFloat(strDiscountPerUnit) / quantity).toFixed(2));
						$('#priceTotalCost').html("&pound;" + parseFloat(strDiscountPerUnit).toFixed(2));
						$('#BasketItemPrice').val(strDiscountPerUnit);
					}
										
					
					$('#BasketConfigKey, #BasketConfigKey2').val(returnedData.ConfiguratorRePriceResult.Configuration);
				}
				else
				{
						
				}	
				$.display.hideLoader();
			},
			reprice: function()
			{
				$.display.showLoader();
				setTimeout('$.configurator.doReprice()',200);
			},
			uploadImage: function ()
			{
				
				fileUploader.submit();
			},
			submitAnswers: function()
			{				
				numAnswers = $.configurator.getObjectSize($answers);
				$.each($answers, function(key, value) { 
				
						answer = $.winman.answer(value.id.toString())
						
						questionNum = $.configurator.findCurrentQuestion(value.menuID, "", -1);
						if(steps[$stepNumber].stepOptions[questionNum].type == "question")
						{
						
							steps[$stepNumber].stepOptions[questionNum].answer = value.id;
							steps[$stepNumber].stepOptions[questionNum].answerText = value.text
							steps[$stepNumber].stepOptions[questionNum].text = value.unformattedText
						}
						else
						{						
							groupNum = $.configurator.getGroupFromQuestion(value.menuID, -1);
							steps[$stepNumber].stepOptions[groupNum].stepOptions[questionNum].answer = value.id;
							steps[$stepNumber].stepOptions[groupNum].stepOptions[questionNum].answerText = value.text;
							steps[$stepNumber].stepOptions[groupNum].stepOptions[questionNum].text = value.unformattedText;							
						}				
					})
				
			},
			test: function(questionText, subNumber)
			{
				var theID
				$.each(steps[$stepNumber].stepOptions,function(key, values)
								{
								  	if(values.type == "question")	
									{
									}
									else
									{
										 theID = $.configurator.findCurrentQuestion(questionText,'',-1);
										
										
									}
							  	}
							  	)
				return theID
				
			},
			getGroupFromQuestion: function(questionText, subNumber)
			{
				//to do need to search object for question text and return the group key
				if(questionText == "encapsulation_clear_overlay")
				{
					return 0;
				}
				else if(questionText == "spine_pocket" || questionText == "inside_front_pocket" || questionText == "inside_back_pocket")
				{
					return 1;
				}
				else
				{
					return 2;	
				}
				/*
			if(subNumber == -1)
				{
					theArray = 	steps[$stepNumber].stepOptions
				}
				else
				{					
					theArray = 	steps[$stepNumber].stepOptions[subNumber].stepOptions;
				}
				
				counter = 0
				$.each(theArray,function(key, values)
									  {
											if(values.type == "question")	
											{
											}
											else
											{
												 $.configurator.getGroupFromQuestion(questionText,counter);
												 counter = counter + 1
											}
									  }
									  )*/
			},			
			findCurrentQuestion: function(questionText, clickedItem, subNumber)
			{
				theId = 0;
				if(subNumber == -1)
				{
					theArray = 	steps[$stepNumber].stepOptions
				}
				else
				{					
					theArray = 	steps[$stepNumber].stepOptions[subNumber].stepOptions;
				}
				counter = 0;
				$.each(theArray, function(id,values)
								{
									if(values.type == "question")
									{
										if(values.questionText == questionText)
										{
											theId = id;	
											//return false;
										}
									}
									else
									{
										if(subNumber > -1)
										{
											theId = id;
										}
										else
										{
											theId = $.configurator.findCurrentQuestion(questionText, clickedItem, counter);
											counter = counter + 1
										}
										//todo
										//need to find current question in groups
									}
								})
				
				return theId;				
			},
			makeActive: function(clickedItem)
			{	
			
				$('span:not(headerOption)',$('.config_options')).removeClass("current");
				$.configurator.makeOpacity($('span:not(headerOption)',$('.config_options')), false);
				$.configurator.makeOpacity($('span:not(headerOption)',$('.config_print')), false);
				$(clickedItem).addClass("current");
			
				if($(clickedItem).is('.headerOption'))
				{
					
				}
				else
				{
					$.configurator.makeOpacity($(clickedItem), true);
				}
				//
			},
			makeInactive: function(clickedItem)
			{	
				$(clickedItem).removeClass("current");
				$.configurator.makeOpacity($(clickedItem), false);
			},
			nextStep: function()
			{
				$.display.showLoader();
				setTimeout('$.configurator.donextStep()',200);
				$('#productHeight').hide().show();
			},
			donextStep: function()
			{
				
				quantity = null;				
				if($('input',$('.menuContent:visible')).length ==  1)
				{
					numAnswers = $.configurator.getObjectSize($answers);
					if($('input',$('.menuContent:visible')).val() != "")
					{
						quantity = $('input',$('.menuContent:visible')).val();		
					}
				}

				if($stepNumber==5 && (quantity=='' || quantity==0))
				{
					alert("You need to select an answer for this step");
				} //check quantity is not null on the final step or otherwise check required fields for the winman stage
				if($stepNumber!=5 && $('.menuContent:visible').is('.required') && $.configurator.getObjectSize($answers) == 0)
				{				
					alert("You need to select an answer for this step");
				}
				else
				{
					$('#start_over').show();
					if($('.menuContent:visible').attr("id") == "quantityinput")
					{	
					//	alert('check if colour print and then check qty');
						 $quantity = $('#desiredQty').val()
						 if(isNaN($quantity))
						 {
							 alert('Please enter a number'); 
							 $.display.hideLoader();
							 return false;
						 }
						 else if($quantity.indexOf('.') > -1 || parseInt($quantity) < 1)
						 {
							 alert("Please enter a whole number greater than 1")
							 $.display.hideLoader();
							 return false;
						 }
									   
						
					}
					if($stepNumber == 5)
					{
						$.configurator.calculatePrice($quantity)
						$.configurator.setUpHelpLink('quote')
					}
					
					else
					{	
						//if they clicked next on the options step - no more winman questions
						if($stepNumber == 4)
						{
							$.configurator.submitAnswers();
							if(extraAnswer == true)
							{
								$.winman.answer(5125);
								extraAnswer = false;
							}
							$('.menuContent').hide();
							$answers = {};
							$.display.makeStepActive('qty');
							$('#quantityinput').show();
							$stepNumber = $stepNumber + 1;
							$.configurator.setUpHelpLink('quantity')
						}						
						else
						{
							$.configurator.submitAnswers();
							$stepNumber = $stepNumber + 1;
							$answers = {};
							$.configurator.loadMenu(steps[$stepNumber]);							
						}
					}
					$.configurator.bindMenuClicks();
						
				}
				$.display.hideLoader();
				
				/*
				if(($('.menuContent:visible').is('.required') && ($answerID.toLowerCase() == 'none') || $('input',$('.menuContent:visible')).val() == ""))
				{
					alert("You need to select an answer for this step");
				}
				else
				{
					if($('.menuContent:visible').attr("id") == "quantityinput")
					{
						calculatePrice($('#desiredQty').val())
					}
					else
					{
														 
						if($answerID.toLowerCase() != 'none')
						{
							var html = $.ajax({ 
								type: "POST",
								url: '/winman/configurator_answer',
								async: false,
								data: {'data[product]' : $productID, 'data[quantity]' : 1, 'data[configuration]' : $configuration, 'data[answerId]': $answerID.toString()}	
							}).responseText;
						
							eval("answer = " + html);
							
							configQuestions[configQuestionOrder[$stepNumber]]["answerID"] =  $answerID;
							configQuestions[configQuestionOrder[$stepNumber]]["answerText"] = $answerText;
							configQuestions[configQuestionOrder[$stepNumber]]["answerUnformattedText"] = $answerUnformattedText;
										
							$answerID = 'None';
							if(answer.ConfiguratorAnswerResult != undefined)
							{
								if(answer.ConfiguratorAnswerResult.Result == "Success")
								{
									
									$stepNumber = $stepNumber + 1;
						
									if($stepNumber >= $numquestions)
									{
										calculatePrice()
									}
									else
									{
										loadMenu(configQuestionOrder[$stepNumber]);	
									}
									
								}
								else
								{
									alert(answer.ConfiguratorAnswerResult.Result);	
								}
							}
							else
							{
								$error = true;
							}
						}
						else
						{
							$stepNumber = $stepNumber + 1;
						
							if($stepNumber >= $numquestions)
							{
								$('.menuContent').hide();
								$('#quantityinput').show();
								//calculatePrice()
							}
							else
							{
								loadMenu(configQuestionOrder[$stepNumber]);	
							}
						}
					}
				}*/
			},
			doStartOver: function()
			{
				$(this).dialog("close");
				$('#next_step').show();
				$('#config_prod_preview').css({'visibility':'hidden'});		
				$('#configuratorFile').val('');
				$('#uploadMessage').html('');
				$uploadeFile = null;
				$originalFile = null;
				$('#dummyFileName').val('');
				$('#start_over').hide();
				
				$.configurator.getQuestionsList();
				if($error == true)
				{
					alert("There has been a problem with the configurator.  Please try again later")	
				}
				else
				{
					$.configurator.createStepList();
					$('.menuContent').hide();
					$('.box').css({"background-color":"#EEEEEE", 'background-image':''});
					$('#mechanismImage').attr({"src": "/img/configImgs/mech.png"});
					$('#rivetsImage').attr({"src": "/img/configImgs/rivets.png"});
				
					$stepNumber = 0;
					$.configurator.loadMenu(steps[$stepNumber]);
				}
				$.display.hideLoader();
			},
			startOver: function()
			{
				$.display.showLoader();
				setTimeout('$.configurator.doStartOver()',200)
			},
			setupConfigurator: function()
			{

				$stepNumber = 0;
				$.display.showLoader();
				$('#next_step').show();
				$('.menuContent').hide();
				$('#start_over').hide();
				$('#mechanismImage').attr({"src": "/img/configImgs/mech.png"});
				$('#rivetsImage').attr({"src": "/img/configImgs/rivets.png"});
				
				$('#configuratorFile').val('');
				$uploadeFile = null;
				$originalFile = null;
				$('#dummyFileName').val('');
				
				$.configurator.getQuestionsList();
				if($error == true)
				{
					alert("There has been a problem with the configurator.  Please try again later")	
				}
				else
				{
					
					$.configurator.createStepList();
					$numquestions = $.configurator.getObjectSize(steps);
					$.configurator.loadMenu(steps[$stepNumber]);
					$('#next_step').bind('click', function(){ $.configurator.nextStep(); });
					$('#start_over').bind('click', function(){ $.configurator.startOver(); });
					$('#outsideLink').bind('click', function(){ $.display.showOutside(); return false; });
					$('#insideLink').bind('click', function(){ $.display.showInside();  return false; });
				}
				
				$.display.hideLoader();
			},
			binderDescription: function(properties)
			{
				
				return "Binder Size: " + properties['Orientation_size'] + ", Mechanism: " + properties['Mechanism'];
			},
			binderProperties: function()
			{
				var properties = {}
				var pockets = {};
				var overlays = {};
				
				//overlays 
				properties['overlays'] = steps[4].stepOptions[0].stepOptions[0].text;
				properties['artwork'] = null;
				
				$.each(steps, function(key, value){
									   
									   $.each(value.stepOptions, function(keys, values)
																		  {
																			if(values.type == "question")
																			{
																				if(values.questionText == 'binder_size')
																				{
																					binderText = values.text.split(" ");
																					binderString = (binderText[1] == "Landscape") ? binderText[0] + ' ' + binderText[1] : binderText[0];
																					properties['Orientation_size'] = binderString;
																				}
																				else if(values.questionText == 'capacity')
																				{
																					properties['Capacity'] =  values.answerText + 'mm';
																				}
																				else if(values.questionText == 'mechanism')
																				{
																					mechanismText =  values.text.split(" ");																					if(mechanismText.length > 3)
																					{
																						if(mechanismText[3].toLowerCase() == "dee")
																						{
																							properties['Mechanism'] = mechanismText[0]+'D';
																						}
																						else
																						{
																							properties['Mechanism'] = mechanismText[0] + ' ' + mechanismText[1]
																						}	
																					}
																					else
																					{
																						properties['Mechanism'] = mechanismText[0] + ' ' + mechanismText[1]
																					}
																				}
																				else if(values.questionText == 'material_outer_type')
																				{
																					properties['Colour'] = values.text
																				}																				
																			}
																			else
																			{
																				if(values.name == "Pockets")
																				{
																					
																					  $.each(values.stepOptions, function(keyss, valuess)
																														 {
																															pockets[valuess.questionText] = valuess.text;
																														 })
																				}
																				else if(values.name == "Print")
																				{
																					properties['artwork'] = steps[4].stepOptions[2].stepOptions[0].text;
																				}
																			}
																			
																		  })
									   
									   
									   })
								properties['pockets'] = pockets	
			
				return properties;
			},
			calculatePrice: function(quantity)
			{
				binderPropertiesList = $.configurator.binderProperties();
				json = $.winman.finish(quantity, binderPropertiesList);
				setTimeout(function() { $.configurator.doCalculatePrice(quantity) },100)
			},
			doCalculatePrice: function(quantity)
			{
				
				$('#next_step').hide();
				
				
				if(json == "error" || typeof(json)!='object')
				{
					alert("The system did not return a price for this quantity.\nYou could try a different quantity or contact us for more information.");
					$('#next_step').show();
				}
				else
				{
					newProductId = json.ConfiguratorFinishResult.ProductId;
					strPricePerUnit = json.ConfiguratorFinishResult.Price
					strDiscountPerUnit = (json.ConfiguratorFinishResult.Discounted != undefined) ? json.ConfiguratorFinishResult.Discounted : ''
					// Set-up full description
					var fullDescription = json.ConfiguratorFinishResult.Description;
					$.configurator.setUpDescriptionLink(fullDescription);
					////////////////////////////////////////////////////////////////////////////////
					
					$webBiviCode = newProductId;
					$.display.makeStepActive("quoteMenu");
					
					$('#config_tabs').hide();
					
					var detailsText = "";
					
					$('#pricePerUnit').html("&pound;" + (parseFloat(strPricePerUnit) / quantity).toFixed(2));
					$('#priceTotalCost').html("&pound;" + parseFloat(strPricePerUnit).toFixed(2));
					$('#BasketItemPrice').val(strPricePerUnit);
					//Over-ride total with discount amount if necessary
					if(strDiscountPerUnit != '')
					{
						$('#pricePerUnit').html("&pound;" + (parseFloat(strDiscountPerUnit) / quantity).toFixed(2));
						$('#priceTotalCost').html("&pound;" + parseFloat(strDiscountPerUnit).toFixed(2));
						$('#BasketItemPrice').val(strDiscountPerUnit);
					}
					
					//$('#discountPrice').html("&pound;" + parseFloat(strDiscountPerUnit).toFixed(2));
					$('.menuContent').hide();
					$('#quoteMenu').show();
					$('div',$('#quoteMenu')).show();
					
					
					$('#BasketSizeSelect, #BasketSizeSelect2').val(newProductId);
					binderPropertiesList = $.configurator.binderProperties();
					detailsText = "<strong>Binder Size:</strong> " + binderPropertiesList["Orientation_size"] + "<br /><strong>Mechanism:</strong> " +  binderPropertiesList["Mechanism"] + "<br /><strong>Capacity:</strong> " +  binderPropertiesList["Capacity"];
				
					$('#theDetails').html(detailsText);
					$('#qtyToBuy').val(quantity)
					$('#quantityToBasket').val(quantity)
					
					$('#BasketConfigKey, #BasketConfigKey2').val($configuration);
					$('#BasketLongDesc').val(fullDescription);
					if($uploadeFile == null)
					{
					$uploadeFile = "";	
					}
					$('#BasketFileName, #BasketFileName2').val($uploadeFile);
					pocketsText = "";
					$.each(binderPropertiesList["pockets"], function(key, value){
								
								if(value != "" && value != undefined)
								 {
									pocketsText = pocketsText + key.replace(/_/gi, " ") + ": " + value + "<br>";
								 }
								 })
				
					//overlayText = (binderPropertiesList["overlay"] != "" ) ? binderPropertiesList["overlay"] : 'None';
					if(pocketsText == "")
					{
						pocketsText = "None selected";	
					}
					
					$('#thePockets').html(pocketsText);
					
					colourText = (binderPropertiesList["Colour"]!=undefined) ? binderPropertiesList["Colour"] : '';
					
					overlayText = 'No overlay selected';
					overlayText = (binderPropertiesList["overlays"]!=undefined) ? binderPropertiesList["overlays"] : overlayText;
					//overlayText = overlayText.replace(/_/gi, " ") + ": " + value + "<br>";
					
					var printText = 'No print option selected';
					printText = (binderPropertiesList["artwork"] != undefined && binderPropertiesList["artwork"] != null) ? binderPropertiesList["artwork"] : printText;
					
					var artworkText = 'No artwork selected';
					artworkText = ($originalFile != undefined && $originalFile != null) ? $originalFile : artworkText;
					
					//////////////////////////////////////////////////////////////////////////////////////////
					$('#theColour').html(colourText);
					$('#theOverlays').html(overlayText);
					$('#theArtwork').html(artworkText);
					$('#thePrint').html(printText);
					
					// $('#theArtwork').html($originalFile);
					strDescription = $.configurator.binderDescription(binderPropertiesList)
					binderPropertiesList["description"] = strDescription
					
					breakPoints = json.ConfiguratorFinishResult.PriceBreaks;
					if(strDiscountPerUnit != '')
					{
						strBreakPointText = "Order " + quantity + " for &pound;" + parseFloat(strDiscountPerUnit).toFixed(2) + "<br>";
					}
					else
					{	
						strBreakPointText = "Order " + quantity + " for &pound;" + parseFloat(strPricePerUnit).toFixed(2) + "<br>";
					}
					$.each(breakPoints.PriceBreak, function(key, values) {
															if(values.Discounted != undefined)
															{
																strBreakPointText = strBreakPointText + "Order " + values.Quantity + " for &pound;" + parseFloat(values.Discounted).toFixed(2) + " (&pound;" + (parseFloat(values.Discounted) /  values.Quantity).toFixed(2) + " per unit) <br>"; 	
															}
															else
															{
																strBreakPointText = strBreakPointText + "Order " + values.Quantity + " for &pound;" + parseFloat(values.Price).toFixed(2) + " (&pound;" + (parseFloat(values.Price) /  values.Quantity).toFixed(2) + " per unit) <br>"; 	
															}
													 
												 
												 })
					$('.breakpointText').html(strBreakPointText)
						//$('#BasketProperties').val(description)						
					binderPropertiesList['fullDescription'] = fullDescription;
					$encodedString = $.toJSON(binderPropertiesList);
					$('#BasketProperties, #BasketProperties2').val($encodedString.replace(/undefined/gi,'"None selected"'))
					$('#next_step').hide();
				}
			},
			unbindMenuClicks: function()
			{
				$.each(steps, function(key, values) { $('#'+values.id).unbind("click") })
			},
			findNumberById: function(id)
			{
				$.each(steps, function(e,values) { 
									 
									   if(values.id == id)
									   {
											retunedID= e;   
											return false;
									   }
									   })
			
				return retunedID;
			},
			setUpHelpLink: function(questionText)
			{
				$('#help_me').unbind('click')
				$('#help_me').bind('click', function() { $.display.help(questionText); })
		
			},
			setUpDescriptionLink: function(description)
			{
				$('img', $('.fullDescription')).unbind('click');
				$('img', $('.fullDescription')).bind('click', function() { $.display.fullDescription(description); });
			},	
			bindMenuClicks: function()
			{
				$.configurator.unbindMenuClicks();
				if($stepNumber > 0)
				{
					for(i = 0; i < $stepNumber; i++)
					{
						$('#'+steps[i].id).css({'cursor':'pointer'})
						$('#'+steps[i].id).bind("click", function() { 
																		
																		theID = $.configurator.findNumberById($(this).attr("id"))
																		$stepNumber = parseInt(theID)
																		$.configurator.loadMenu(steps[theID]);
															} )
					}
				
				}
			},
			loadMenu: function(stepOptions)
			{
				if($stepNumber == 4)
				{
					$('.overlays').hide();
					$('.pockets').hide();					
					$('.print').hide();	
					$answers = {};
					$.configurator.setUpHelpLink('encapoverlay')
					
					$('#overlays').bind('click', function() { $.configurator.changeOptions('overlays'); } )
					$('#pockets').bind('click', function() { $.configurator.changeOptions('pockets'); } )
					$('#print').bind('click', function() { $.configurator.changeOptions('printing'); } )
					
					
					
					$.configurator.bindMenuClicks();
					$.display.makeStepActive(stepOptions.id);
					$.configurator.getOptions(stepOptions);		
					$('.overlays').show();
					$('#overlays').css({'background-color':'#CCC'});
					$('.pockets').hide();					
					$('.print').hide();	
				}
				else
				{
					if(stepOptions.stepOptions[0].questionText == 'capacity')
					{
						if(steps[1].stepOptions[0].answerText == 'lever_arch_mechanism')
						{
							extraText = '-leverArch';
						}
						else
						{
							extraText = '';
						}
						$('li',$('#config_optionsSpine')).each(function() { 
																id = $(this).attr('id')
																$('img',$(this)).attr({'src': '/img/configImgs/'+ id +'mm'+extraText+'.png' })
																		
											})
						
					}
					$.configurator.setUpHelpLink(stepOptions.stepOptions[0].questionText)
					$.configurator.bindMenuClicks();
					$.display.makeStepActive(stepOptions.id);
					$.configurator.getOptions(stepOptions);		
				}
				
				
			},
			changeOptions: function(buttonClicked)
			{
				$.display.showLoader();
				setTimeout(function(){$.configurator.doChangeOptions(buttonClicked)},200)
			},
			doChangeOptions: function(buttonClicked)
			{
				if(buttonClicked == "overlays")
				{
					$.configurator.setUpHelpLink('encapoverlay');
					$.display.showOutside();
					$('#overlays').css({'background-color':'#CCC'});
					$('#pockets').css({'background-color':'#FFF'});
					$('#print').css({'background-color':'#FFF'});
					
					$('.overlays').show();
					$('.pockets').hide();
					$('.print').hide();
				}
				else if(buttonClicked == "pockets")
				{
					$.configurator.setUpHelpLink('pockets');
					$.display.showInside();
					$('#overlays').css({'background-color':'#FFF'});
					$('#pockets').css({'background-color':'#CCC'});
					$('#print').css({'background-color':'#FFF'});
					
					$('.overlays').hide();
					$('.pockets').show();
					$('.print').hide();
					$.configurator.submitAnswers()
					$.each(steps[$stepNumber].stepOptions[1].stepOptions, function(key,values)
																		 {
																			questionlist = $.winman.returnVisibleOptions(values.id);
																			$.configurator.hideShowOptions(questionlist,values.questionText) 
																		 })
					//submit answers from overlays.
				}
				else
				{
					$.configurator.setUpHelpLink('print');
					$.display.showInside();
					
					$('#overlays').css({'background-color':'#FFF'});
					$('#pockets').css({'background-color':'#FFF'});
					$('#print').css({'background-color':'#CCC'});
					
					$('.overlays').hide();
					$('.pockets').hide();
					$('.print').show();
					
					
					
					
					$.configurator.submitAnswers()
					//submit answers from pockets.
					$.each(steps[$stepNumber].stepOptions[2].stepOptions, function(key,values)
																		 {
																			questionlist = $.winman.returnVisibleOptions(values.id);
																			$.configurator.hideShowOptions(questionlist,values.questionText) 
																		 })
					
						fileUploader = new AjaxUpload('#fileBrower', {
	  
						  action: '/configurator/uploadImage',					
						  name: 'File',					
						  autoSubmit: false,					
						  responseType: false,					
						  onChange: function(file, extension){
							  $('#fileName').val(file)
							  },
					
						  onSubmit: function(file, extension) {},
						
						  onComplete: function(file, response)
						  {  
							eval("imageDims = " + response);
							
							if(imageDims.error == undefined)
							{
								if(extraAnswer == true)
								{
									$.winman.answer(5124);
									extraAnswer = false;
								}
								$originalFile = imageDims.originalFilename
								$uploadeFile = imageDims.newFilename;
								$('#uploadMessage').html("<strong style='font-size: 12px'>File Uploaded</strong>");
								$('#no_print').hide();
							}
							else
							{
								if(imageDims.error == "ext")
								{
									$('#uploadMessage').html("The upload as failed as the file uploaded must be a pdf document.");
								}
								else
								{
									$('#uploadMessage').html("There has been a problem uploading the file.  Please try again.");	
								}
							}
						  }
						});
					
					if($uploadeFile != null && $uploadeFile != "")
					{
						$('#no_print').hide();
					}
					
				}
				$.display.hideLoader();
			},
			doChangeOptions1: function(buttonClicked)
			{
				if(buttonClicked == "overlays")
				{
					$.configurator.setUpHelpLink('encapoverlay')
					$.display.showOutside();
					$('#overlays').css({'background-color':'#CCC'});
					$('#pockets').css({'background-color':'#FFF'});
					$('#print').css({'background-color':'#FFF'});
					
					//$.configurator.makeOpacity($('#overlays'), true);
					$('#overlays').parent().css({'background-color': '#CCC'});
					$('#pockets').parent().css({'background-color': '#FFF'});
					$('#print').parent().css({'background-color':'#FFF'});
					
					$('.config_pockets').hide()
					$('.config_overlays').show()
					
					$('.config_print').hide();
					$('.pockets').hide()
					$('#printing').hide()
					
					$('.encapsulation_clear_overlay').show();
					
					$('.print').hide()
					
				}
				else if(buttonClicked == "printing")
				{
					$.configurator.setUpHelpLink('print')
					$.display.showInside();
					$('#print').css({'background-color':'#CCC'});
					$('#pockets').css({'background-color':'#FFF'});
					$('#overlays').css({'background-color':'#FFF'});
					
					//$.configurator.makeOpacity($('#overlays'), true);
					$('#overlays').parent().css({'background-color': '#FFF'});
					$('#pockets').parent().css({'background-color': '#FFF'});
					$('#print').parent().css({'background-color':'#CCC'});
						
					
					$('.config_pockets').hide()
					$('.config_overlays').hide()
					$('.config_print').show();
					$('#printing').show()
					
					
				
					fileUploader = new AjaxUpload('#fileBrower', {
  
					  action: '/configurator/uploadImage',					
					  name: 'File',					
					  autoSubmit: false,					
					  responseType: false,					
					  onChange: function(file, extension){
						  $('#fileName').val(file)
						  },
					
					  onSubmit: function(file, extension) {},
					
					  onComplete: function(file, response)
					  {
						eval("imageDims = " + response)
						if(imageDims.error == undefined)
						{
							if(extraAnswer == true)
							{
								$.winman.answer(5124);
								extraAnswer = false;
							}
							$originalFile = imageDims.originalFilename
							$uploadeFile = imageDims.newFilename;
							$('#uploadMessage').html("<strong style='font-size: 12px'>File Uploaded</strong>");
							$('#no_print').hide();
						}
						else
						{
							if(imageDims.error == "ext")
							{
								$('#uploadMessage').html("The upload as failed as the file uploaded must be a pdf document.");
							}
							else
							{
								$('#uploadMessage').html("There has been a problem uploading the file.  Please try again.");	
							}
						}
					  }
					});
					$('#fileName').bind('click', function() { $('#fileBrower').trigger('click') } )
					
					
					
					
					$('.pockets').hide()
					$('.encapsulation_clear_overlay').hide();
					
							
					$.configurator.submitAnswers()
					//todo need to get the question from the steps object
				
					$.each(steps[$stepNumber].stepOptions[2].stepOptions, function(key,values)
																		 {
																			questionlist = $.winman.returnVisibleOptions(values.id);
																			$.configurator.hideShowOptions(questionlist,values.questionText) 
																		 })
					
					if($uploadeFile != null && $uploadeFile != "")
					{
						$('#no_print').hide();
					}
				}
				else
				{
					$.configurator.setUpHelpLink('pockets')
					
					$.display.showInside();
					$('#overlays').css({'background-color':'#FFF'});
					$('#pockets').css({'background-color':'#CCC'});					
					$('#print').css({'background-color':'#FFF'});
					
					$('.config_pockets').show()
					$('.config_overlays').hide()
					$('.config_print').hide();
					$('#printing').hide()
					$('.pockets').show()
					$('.encapsulation_clear_overlay').hide()
					
					//$.configurator.makeOpacity($('#pockets'), true);
					$('#overlays').parent().css({'background-color': '#FFF'});
					$('#pockets').parent().css({'background-color': '#CCC'});
					$('#print').parent().css({'background-color':'#FFF'});
					$('.print').hide();
					$.configurator.submitAnswers()
					//todo need to get the question from the steps object

					$.each(steps[$stepNumber].stepOptions[1].stepOptions, function(key,values)
																		 {
																			questionlist = $.winman.returnVisibleOptions(values.id);
																			$.configurator.hideShowOptions(questionlist,values.questionText) 
																		 })
				}
				$.display.hideLoader();
			
			},	
			getObjectSize: function(object)
			{
				counter = 0
				$.each(object,function() {counter = counter+1 })
				return counter;
			},
			hideMenus: function()
			{
				$('.menuContent').hide();	
			},
			showMenu: function(menuID)
			{				
				$('#'+menuID).show();
			},			
			getOptions: function(theOptions)
			{
				
				theSize = $.configurator.getObjectSize(theOptions.stepOptions)
				$.configurator.hideMenus()
				if(theSize == 1)
				{
					if(theOptions.stepOptions[0].type == "question")
					{
						$.configurator.showMenu(theOptions.stepOptions[0].id);
						optionsToShow = $.winman.returnVisibleOptions(theOptions.stepOptions[0].id);
						$.configurator.hideShowOptions(optionsToShow, theOptions.stepOptions[0].questionText)
					}
				}
				else
				{
				
					$.configurator.showMenu(theOptions.id + "Menu");					
					$.each(theOptions.stepOptions, function(key, values) { 
															if(values.type != "group")
															{
																optionsToShow = $.winman.returnVisibleOptions(values.id);
														
																$.configurator.hideShowOptions(optionsToShow, values.questionText);
																
																	if(values.defaultOption != undefined)
																	{
																		status = $.winman.answer(values.defaultOption);
																		$('.'+values.defaultOption , $('#preOptionBar')).parent().css({'background-color': '#CCC'});
																		// $('.'+values.defaultOption , $('#preOptionBar')).parent().addClass("liCurrent");
																	}
																
																
															}
															else
															{																
																$.each(values.stepOptions, function(subKeys, subValues) { 
																optionsToShow = $.winman.returnVisibleOptions(subValues.id);
														
																$.configurator.hideShowOptions(optionsToShow, subValues.questionText);															
																
																								})
															}
															});
				} 
				if(theOptions.id == "options")
				{
					$.display.showOutside();
				}
			},
			makeOpacity: function(theItem, full)
			{
				
				if($(theItem).length > 0)
				{
					if(full == true)
					{
						$(theItem).css({"-ms-filter":"progid:DXImageTransform.Microsoft.Alpha(opacity=100)","opacity":1 ,"filter": "alpha(opacity=100)","ZOOM":"normal", "-moz-opacity": 10 })
						$('p', $(theItem)).css({"-ms-filter":"progid:DXImageTransform.Microsoft.Alpha(opacity=100)","opacity":1 ,"filter": "alpha(opacity=100)","ZOOM":"normal", "-moz-opacity": 10 })
					}
					else
					{
						$(theItem).css({"-ms-filter":"progid:DXImageTransform.Microsoft.Alpha(opacity=60)","opacity":.60 ,"filter": "alpha(opacity=60)","ZOOM":"normal","-moz-opacity": 0.60 })		
						$('p', $(theItem)).css({"-ms-filter":"progid:DXImageTransform.Microsoft.Alpha(opacity=60)","opacity":.60 ,"filter": "alpha(opacity=60)","ZOOM":"normal","-moz-opacity": 0.60 })		
					}
				}
			},			
			hideShowOptions: function(answerList, questionText)
			{
				$.display.showInside();
				
				if(answerList.length >0)
				{
					if(questionText == "material_outer_type")
					{
						$.display.showColours(questionText, answerList);
					}
					else
					{
					
						if(questionText == "encapsulationclear_overlay")
						{
							$areaToConfigure = "outside"
						}
						else
						{
							
							if(questionText.indexOf("outer") > -1)
							{
								$areaToConfigure = "outside"
							}
							else
							{
								$areaToConfigure = "inside"
							}
						}

						
						if($('#' + questionText).length)
						{
							
							$('#' + questionText).show();
						
							$('li',$('#' + questionText)).hide();
							
							$('span', $('li',$('#' + questionText))).unbind('click');
						
							if(answerList.length > 0)
							{	
								
								$.each(answerList, function(key, value)
								{
									
									if(questionText == "capacity")
									{
										fullId = "";
										if(value.AnswerText.indexOf(" ") > -1)
										{
											tempInfo = value.AnswerText.split(" ");
											fullId = tempInfo[0]
										}
										else
										{
											fullId = value.AnswerText
										}									
										listID = fullId.substring(2,4) 									
									}
									else
									{
										listID = value.AnswerText.toLowerCase().replace(/,/gi,"").replace(/\)/gi,"").replace(/\(/gi,"").replace(/ - /gi,"_").replace(/ & /gi,"_").replace(/ /gi,"_");
									}

									if(questionText == "spine_pocket")
									{
									 	if(value.AnswerText != "None")
										{
											listID = value.AnswerText.toLowerCase().replace(/,/gi,"").replace(/\)/gi,"").replace(/\(/gi,"").replace(/ - /gi,"_").replace(/ & /gi,"_").replace(/ /gi,"_");
										}	
										answer = value.AnswerId
										$('li',$('#' + questionText)).attr({'id' : listID })
										$('img',$('#' + questionText)).attr({'alt' :  value.AnswerText , 'title' : value.AnswerText })
										
										$('span',$('#'+listID, $('#' + questionText))).attr({"title": value.AnswerText });
										$('span',$('#'+listID, $('#' + questionText))).addClass(answer.toString());
										$('#'+listID, $('#' + questionText)).show();
									}
									else 
									{
										if($('#'+listID, $('#' + questionText)).length)
										{
											$('#'+listID, $('#' + questionText)).show();
										}
										else
										{
											$('ul',$('#' + questionText)).append('<li id="'+listID+'"><span>'+value.AnswerText+'</span></li>');
										}
										answer = value.AnswerId
										$('span',$('#'+listID, $('#' + questionText))).attr({"title": value.AnswerText });
										$('span',$('#'+listID, $('#' + questionText))).addClass(answer.toString());
									}
								})	
								$.configurator.makeOpacity($('span:not(.headerOption)', $('li')), false);
								$('span', $('li', $('#'+questionText))).bind('click', function() { $.display.changeDisplay($(this), questionText) });
								$('span:not(.headerOption)', $('li', $('#'+questionText))).hover(function() { if($(this).is('.current')) {} else{ $.configurator.makeOpacity($(this), true) }}, function() {  if($(this).is('.current')) {}else{ $.configurator.makeOpacity($(this), false) }} ) 
							}							
						}
					}
				}
				else
				{
					//submitAnswers
					$('li',$('#' + questionText)).hide();
				}

				if($areaToConfigure == "outside" && $currentArea != "outside")
				{

					$.display.showOutside();
				}
				else if($areaToConfigure == "outside" && $currentArea == "outside")
				{
					
				}
				else
				{

					$.display.showInside();
				}
			},
			createStepList: function()
			{
				//needs to be softcoded
			/*	steps[0] = {0:{"questionID":262,"name":"binder_size","defaultAnswer":""}};
				steps[1] = {0:{"questionID":264,"name":"mechanism","defaultAnswer":""}};
				steps[2] = {0:{"questionID":263,"name":"capacity","defaultAnswer":""}};
				steps[3] = {0:{"questionID":273,"name":"material_outer_range","defaultAnswer":""},1:{"questionID":274,"name":"material_outer_type","defaultAnswer":""}};
				
				steps[4] = {0:{"questionID":271,"name":"encapsulation_clear_overlay","defaultAnswer":""},1:{"questionID":284,"name":"encap_printing","defaultAnswer":""}};
				steps[6] = {0:{"questionID":268,"name":"spine_pocket","defaultAnswer":""},1:{"questionID":269,"name":"inside_front_pocket","defaultAnswer":""},2:{"questionID":270,"name":"inside_back_pocket","defaultAnswer":""}};
				steps[7] = {0:{"questionID":266,"name":"printing","defaultAnswer":""}};*/
				steps = {}
				/*
				steps[0] = { "id":"step1", "stepOptions":{0: {"type": "question", "id":262,"questionText":"binder_size"} } }
				steps[1] = { "id":"step2", "stepOptions":{0: {"type": "question", "id":264,"questionText":"mechanism"} } }
				steps[2] = { "id":"step3", "stepOptions":{0: {"type": "question", "id":263,"questionText":"capacity"} } }
				steps[3] = { "id":"step4", "stepOptions":{0: {"type": "question", "id":273,"questionText":"material_outer_range", "defaultOption":"2321"},1: {"type": "question", "id":274,"questionText":"material_outer_type"} } }
				steps[4] = { "id":"options", "stepOptions": {0: {"type": "group", "name": "Overlays", "stepOptions" : { 0: {"type": "question", "id":271,"questionText":"encapsulation_clear_overlay"}, 1: {"type": "question", "id":284,"questionText":"encap_printing"} } }, 1: {"type": "group", "name": "Pockets", "stepOptions" : { 0: {"type": "question", "id":268,"questionText":"spine_pocket"}, 1: {"type": "question", "id":269,"questionText":"inside_front_pocket"}, 2: {"type": "question", "id":270,"questionText":"inside_back_pocket"} } }, 2: {"type": "group", "name": "Print", "stepOptions" : { 0: {"type": "question", "id":266,"questionText":"printing"} } } } }
				steps[5] = { "id":"qty", "stepOptions": {0: {"type": "question", "id":null,"questionText":"qty"} } }
				*/
				steps[0] = { "id":"step1", "stepOptions":{0: {"type": "question", "id":538,"questionText":"binder_size"} } }
				steps[1] = { "id":"step2", "stepOptions":{0: {"type": "question", "id":540,"questionText":"mechanism"} } }
				steps[2] = { "id":"step3", "stepOptions":{0: {"type": "question", "id":539,"questionText":"capacity"} } }
				steps[3] = { "id":"step4", "stepOptions":{0: {"type": "question", "id":546,"questionText":"material_outer_range", "defaultOption":"5101"},1: {"type": "question", "id":547,"questionText":"material_outer_type"} } }
				steps[4] = { "id":"options", "stepOptions": {0: {"type": "group", "name": "Overlays", "stepOptions" : { 0: {"type": "question", "id":545,"questionText":"encapsulation_clear_overlay"}, 1: {"type": "question", "id":548,"questionText":"encap_printing"} } }, 1: {"type": "group", "name": "Pockets", "stepOptions" : { 0: {"type": "question", "id":542,"questionText":"spine_pocket"}, 1: {"type": "question", "id":543,"questionText":"inside_front_pocket"}, 2: {"type": "question", "id":544,"questionText":"inside_back_pocket"} } }, 2: {"type": "group", "name": "Print", "stepOptions" : { 0: {"type": "question", "id":541,"questionText":"printing"} } } } }
				steps[5] = { "id":"qty", "stepOptions": {0: {"type": "question", "id":null,"questionText":"qty"} } }
				
			},
			getQuestionsList: function()
			{				
				json = $.winman.getQuestions();
				if(json != "error")
				{
					configQuestions = {};
					configQuestionOrder = {};
				
					if(json.ConfiguratorStartResult != undefined)
					{
						$configuration = json.ConfiguratorStartResult.Configuration;					
						$.each(json.ConfiguratorStartResult.Questions.Question, function(key, value) { 						
							questionText = value.QuestionText.replace(/\//gi,"").replace(/,/gi,"").replace(/\(/gi,"").replace(/\)/gi,"").replace(/, /gi," ").replace(/ - /gi,"_").replace(/ & /gi,"_").replace(/ /gi,"_").toLowerCase();
							configQuestionOrder[key] = questionText;						
							configQuestions[questionText] = value;
						})
					}
					else
					{
						$error = true;
					}
				}
				else
				{
					$error = true;	
				}
			}
		}
	})
})(jQuery);