var loop = 1;
var step = 1;
var stepBack = 0;
var idString = '#';
var dontStartLoop = 'true';
var nextStep = '';
var commonProcess = false;
var forCommonBlock = '';
var forDiffBlock = Array();
var forDiffBlockStr = '';
var forCommonShelves = '';
var forDiffShelves = Array();
var loopStep = 0;
var oldimagename = '';
var mainLoop = '';
var forBlock2 = ''; //which choices to hide in block2, delimited with #
var modelNum='';
var quesText = Array();
var stepArr = Array(); //used for multi-zone units, indicates which blocks need to be configured
quesText[2] = ' for third zone';
quesText[1] = ' for second zone';
quesText[0] = ' for first zone';


var commonQuesText = Array();
commonQuesText[2] = ' for both zones';
commonQuesText[3] = ' for all three zones';





//This is the main logic for this app. This figures how to move to a next step. It looks a lot at the parts of the JSON that relates to the actual blocks,commonshelves,diffblock
//This function does some rendering to the screen ,but it's not the main point of this function. It's here to figure out what goes where. 
function showStep(thisObj) {


	var stepList = $(thisObj).attr('stepList');
	var currModel='';
	//the 'stepno' attribute is not set via JSON
	//it is set equal to the global 'step' var later in this function
	if ($(thisObj).attr('stepno') == '2' || $(thisObj).attr('stepno') == '1') {
		stepBack = 0;
		idString = '#';
		dontStartLoop = 'false';
		nextStep = '';
		commonProcess = false;
		forCommonBlock = '';
		forDiffBlock = Array();
		forDiffBlockStr = '';
		forCommonShelves = '';
		forDiffShelves = Array();
		loopStep = 0;
		stepArr = Array();
		mainLoop = $(thisObj).attr('loop');
		loop = $(thisObj).attr('loop');
		
	}
	
	
	
	
	currModel=modelNum;
	
	

	
	
	
	
	
	//if we don't have a stepList defined, but we do have a value
	//queued in the stepArr global array, load it as the current stepList
	//and decrement the loop counter
	if (stepList == undefined && stepArr[loop-1] != undefined) {
		loop--;
		stepList = stepArr[loop-1];
	}
	
	//if we have a valid object to operate on and a valid stepList to execute
	//and if the loop counter isn't negative, then execute the main logic block
	//to show the next step in the flow based on the user's selection
	if (thisObj != '' && stepList != '' && stepList != undefined && $(thisObj).attr('loop') >= 0) {
		
		//build an array to store the individual blocks that need to be called
		var blockArr = stepList.split('#');
		
		//load several attribues, if present
		//otherwise default to a safe value in some cases
		if ($(thisObj).attr('forBlock2')) {
			forBlock2 = $(thisObj).attr('forBlock2');
		}
		
		
		
		
		if ($(thisObj).attr('stepArr')) {
			stepArr = $(thisObj).attr('stepArr').split(',');
		}
		if ($(thisObj).attr('common')) {
			dontStartLoop = $(thisObj).attr('common');
		} else if (blockArr[0] == 'block2') {
			dontStartLoop = 'true';
		}
		if ($(thisObj).attr('nextStep') != undefined ) {
			nextStep = $(thisObj).attr('nextStep');
		} else if (nextStep != '' && blockArr[0] == 'block2') {
		//	nextStep = '';
		} else {
			nextStep = '';
		}
		if ($(thisObj).attr('loop')) {
			loop = $(thisObj).attr('loop');
		}
		if (stepArr[loop-1] != undefined) {
			nextStep = stepArr[loop-1];
		}
		if ($(thisObj).attr('loopStep')) {
			loopStep = $(thisObj).attr('loopStep');
		}
		if ($(thisObj).attr('forCommonBlock')) {
			forCommonBlock = $(thisObj).attr('forCommonBlock');
		}
		if ($(thisObj).attr('forDiffBlock') != undefined && $(thisObj).attr('forDiffBlock') =='test') {
			$(thisObj).attr('forDiffBlock', forDiffBlockStr+',');
		} else {
			forDiffBlockStr = $(thisObj).attr('forDiffBlock');
		}
		if ($(thisObj).attr('forDiffBlock') != undefined) {
			var temp = $(thisObj).attr('forDiffBlock').split(',');
			var j=0;
			for (i=temp.length-1; i>-1 ;i-- )	{
				forDiffBlock[j] = temp[i];
				j++;
			}
		}
		if (forCommonShelves == 'blockBlank') {

		} else if ($(thisObj).attr('forCommonShelves') != undefined) {
			forCommonShelves = String($(thisObj).attr('forCommonShelves'));
		}
		if ($(thisObj).attr('forDiffShelves')) {
			var temp = $(thisObj).attr('forDiffShelves').split(',');
			var j=0;
			for (i=temp.length-1; i>-1 ;i-- )	{
				forDiffShelves[j] = temp[i];
				j++;
			}
		}
		
		//get the ID of the block that the currently selected choice is from
		var id = $(thisObj).parents('.step').attr('id');


		clearTail(id);
		step++;
		if (blockArr[0] == 'block6' && forCommonShelves == ' ') {
			if (stepArr[loop-1] != undefined) {
				blockArr[0] == stepArr[loop-1];
			} else if (loop == 1) {
				blockArr[0] = 'blockBlank';
			}
		} else if (blockArr[0] == 'block6' && forCommonShelves == 'blockBlank') {
			blockArr[0] = 'blockBlank';
		} else if (blockArr[0] == 'block3') {
			blockArr[0] == stepArr[loop-2];
		}
		

		
		//grab this block's table content from the hidden element already on the page
		var html = $('#step'+blockArr[0]).attr('innerHTML');
		//normalize the name attribute to match the block's current position in flow (and not it's JSON name)
		html = html.replace(/name=[a-zA-Z0-9]+/gi,'name=step'+step);
		//pad the content in a new table wrapper and ID it with the current step number
		html = '<table width="100%" border="0" cellpadding="0" cellspacing="0" class="step" id="step'+step+'" >'+html+'</table>';
		//drop it on the page after the current block
		$('#'+id).after(html);
		//write out the step number inside the bullet graphic
		$('#step'+step).children().children().children().children().children().children(':first').children('.bullet').html(step);
		
		
		if (blockArr[0] == 'block3' && loop && dontStartLoop == 'false') {
			loopStep++;
		}
		
		//rewrite the step/block label as needed for multiple zones (adds language like first/second/third)
		var quesTempText = String($('#step'+step).children().children().children().children().children().children(':first').children('.txt11').html());
		if (blockArr[0] == 'block4') {
			quesTempText = quesTempText.replace('(for)', commonQuesText[loop]);
		} else if (dontStartLoop == 'false') {
			quesTempText = quesTempText.replace('(for)', quesText[parseInt(mainLoop)-loop]);
		} else if (dontStartLoop == 'true') {
			quesTempText = quesTempText.replace('(for)', '');
		}
		$('#step'+step).children().children().children().children().children().children(':first').children('.txt11').html(quesTempText);
		
		var loop1 = loop;
		if (loop == 0) {
			loop1 = 1;
		}
		var allChoices = $('#step'+step).children().children('.choices');
		var length = allChoices.length;
		for (i=0;i<length;i++) {
			if (blockArr[0] == 'block3' && forCommonBlock != '' && forCommonBlock.match('#'+(i+1)+'#') && dontStartLoop == 'true') {
				$(allChoices[i]).hide();
			} else if (blockArr[0] == 'block3' && forDiffBlock.length && forDiffBlock[loop1-1].match('#'+(i+1)+'#') && dontStartLoop == 'false') {
				$(allChoices[i]).hide();
			} else if (blockArr[0] == 'block3' && forDiffBlock.length && forDiffBlock[loop1].match('#'+(i+1)+'#') && dontStartLoop == 'true') {
				$(allChoices[i]).hide();
			} else if (blockArr[0] == 'block2' && forBlock2.length && forBlock2.match('#'+(i+1)+'#')) {
				//hide the current choice if we're in block2 and this choice's index is inside the forBlock2 variable, delimited by #
				$(allChoices[i]).hide();
			} else if (blockArr[0] == 'block6' && forCommonShelves != '' && forCommonShelves.match('#'+(i+1)+'#') && dontStartLoop == 'true') {
				$(allChoices[i]).hide();
			} else if (blockArr[0] == 'block6' && forDiffShelves.length && forDiffShelves[loop1-1].match('#'+(i+1)+'#') && dontStartLoop == 'false') {
				$(allChoices[i]).hide();
			} 
			
			
			//This is added so I can short circuit and get around block6's rules. This gives me the same behavior of hiding all the other options I am not using and allows
			//me to move beyond that final limit of moving beyond block6. This behaves the same on the block that tells us what shelving will be used.
			//There seems to be special functionality here that hides the other shelves, perhaps because it's not something that is offered as a build option.
			//Either way, my new block,SCblock6, behaves like block 6, and hides the shelves that aren't availble, while letting me get past that limit of adding steps past step 6.
			else if (blockArr[0] == 'SCblock6' && forCommonShelves != '' && forCommonShelves.match('#'+(i+1)+'#') && dontStartLoop == 'true') {
				$(allChoices[i]).hide();
			} else if (blockArr[0] == 'SCblock6' && forDiffShelves.length && forDiffShelves[loop1-1].match('#'+(i+1)+'#') && dontStartLoop == 'false') {
				$(allChoices[i]).hide();
			} 
			//New addition complete here. Continuing.
			
			
			else if (stepList.match('#'+(i+1)+'#')) {
				$(allChoices[i]).hide();
			}
			var optObj = $(allChoices[i]).children(':first').next().children('input');
			$(allChoices[i]).children(':first').next().children('input').attr('name', 'step'+step);
			if ($(allChoices[i]).children(':first').next().children('input').attr('stepList') == 'blockBlank' && stepArr[loop-2] != undefined) {
				$(allChoices[i]).children(':first').next().children('input').attr('stepList', stepArr[loop-2]);
				$(allChoices[i]).children(':first').next().children('input').attr('loop', loop-1);
			}
			if ($(allChoices[i]).children(':first').next().children('input').attr('stepList') != undefined && $(allChoices[i]).children(':first').next().children('input').attr('stepList').match(blockArr[0]) && loop && dontStartLoop == 'true') {
				$(allChoices[i]).children(':first').next().children('input').attr('stepList', 'blockBlank');
				$(allChoices[i]).children(':first').next().children('input').attr('cleartail', '1');
			}
			if (nextStep != '' && blockArr[0] == 'block2') {
				$(allChoices[i]).children(':first').next().children('input').attr('stepList', nextStep);
			} else if (blockArr[0] == 'block2') {
				if (stepArr[loop-2] != undefined) {
					$(allChoices[i]).children(':first').next().children('input').attr('stepList', stepArr[loop-2]);
				}
			}
			if (blockArr[0] == 'block6') {
				if (stepArr[loop-2] != undefined) {
					$(allChoices[i]).children(':first').next().children('input').attr('stepList', stepArr[loop-2]);
				} else {
					$(allChoices[i]).children(':first').next().children('input').attr('stepList', '');
				}

				
			}
		}
		
		
		if (blockArr[0] == 'block6' && loop && dontStartLoop == 'false') {
			loop--;
		} else if (blockArr[0] == 'block3' && loop && dontStartLoop == 'false' && forCommonShelves == ' ') {
			loop--;
		}
		
		
		allChoices = $('#step'+step).children().children('.choices');
		for (i=0;i<allChoices.length;i++) {
			var trChildren = null;
			trChildren = $(allChoices[i]).children('.txt11');
			var trChildrenTemp = $(allChoices[i]).html();
			if (trChildren.length > 1) {
				var tdChildren = $(trChildren[1]).children();
			}
			if (blockArr[0] == 'block3' && ((i==7 || i==6) )) {
				$(tdChildren[0]).attr('stepList', "");
				$(tdChildren[0]).attr('clearTail', "1");
			} else if (blockArr[0] == 'block6' && loop=='0') {
				$(tdChildren[0]).attr('clearTail', "1");
			}

			if (blockArr[0] == 'block6' && dontStartLoop == 'true') {
				$(tdChildren[0]).attr('stepList', "");
				$(tdChildren[0]).attr('clearTail', "1");
			} else if (blockArr[0] == 'block3' && dontStartLoop == 'true') {
				//$(tdChildren[0]).attr('showModelNo', loop);
			} else if (blockArr[0] == 'block5' && dontStartLoop == 'true') {
				//$(tdChildren[0]).attr('showModelNo', loop);
				$(tdChildren[0]).attr('clearTail', "1");
			}
			if ($(tdChildren[0]).attr('loop') == undefined || $(tdChildren[0]).attr('loop') == '0') {
				$(tdChildren[0]).attr('loop', loop);
			}
			$(tdChildren[0]).attr('loopStep', loopStep);
			$(tdChildren[0]).attr('name', 'step'+step);
			$(tdChildren[0]).attr('stepNo', step);
		}
		if ($(thisObj).attr('nextStep') != undefined ) {
			nextStep = $(thisObj).attr('nextStep');
		} else if (nextStep != '' && blockArr[0] == 'block2') {
			nextStep = '';
		}
		else {
			nextStep = '';
		}
	}

	showModelNo($(thisObj).attr('showModelNo'));
	if ($(thisObj).attr('clearTail') != '0' && stepList == undefined ) {
		clearTail('step'+$(thisObj).attr('stepno'));
	} else if ($(thisObj).attr('clearTail') != '0') {
		clearTail('step'+step);
	}
	if ($('#step'+step)) {
		var count = 0;
		var allChoices = $('#step'+step).children().children('.choices');
		for (i=0;i<allChoices.length;i++) {
			if ($(allChoices[i]).css('display') != 'none') {
				count++;
			}
		}
		if (count==1) {
			for (i=0;i<allChoices.length;i++) {
				if ($(allChoices[i]).css('display') != 'none') {
					var temp = $(allChoices[i]).children();
					var temp = $(temp[1]).children();
					temp[0].checked = true;
					$(temp[0]).click();
				}
			}
		}
	}
	return true;
}





//This is the function that by process of elimination we deduce what the model number is. Fun stuff.

function showModelNo(cnt) {
	var allSteps = $('#main_content').children().children().children().children('.step');
    var startHiding = false;
	var html = '';
	var modelNo = 'H';
	var imgName = 'H';
	var removeUnderscore = 0;
	var firstCommon = 0;
	var lastCommon = 0;
	var actLoop = 0;
	var fortyEightSearch="P48";  //I need to search for P48 items here. All Model numbers apparently start with H. I just need to search for the temporary string that has the other half.
	var seventyTwoSearch="P72";  //I need to search for P48 items here. All Model numbers apparently start with H. I just need to search for the temporary string that has the other half.
	var indoor ="S";    //This is the letter so I can do searches for the indoor letter.
	var outdoor= "O";	//This is the letter so I can do outdoor searches for the outdoor letter.
	var built= "B";		//This is the letter so I can do built-in searches for the built-in letter.
	var searchFortyEight=""; //I am attaching my search for 48in. Perlick devices here.
	var searchSeventyTwo=""; //I am attaching my search for 72in. Perlick devices here.
	var repText=""; //This is so I can store the temp value of the replaced text.

//This big ol' monster loop goes through and figures out what to deduce for the product name. This is probably pretty useful for changing around the model names and their rules. Really nashtay looking. In order to change the product names we have to not only change these rules
//but we have to change removeUnderscore,firstCommon, and lastCommon.
    for (var i=1;i<=allSteps.length;i++) {
        if (allSteps[i-1].id && allSteps[i-1].id.match('stepblock') ==  null) {
			var allOpts = $('#'+allSteps[i-1].id).children().children();
			for(j=1; j<allOpts.length; j++) {
				var temp = $(allOpts[j]).children();
				var opts = $(temp[1]).children();
				if (opts[0].checked == true) {
					removeUnderscore = ($(opts[0]).attr('removeUnderscore') != undefined ? $(opts[0]).attr('removeUnderscore') : removeUnderscore);
					firstCommon = ($(opts[0]).attr('firstCommon') != undefined ? $(opts[0]).attr('firstCommon') : firstCommon);
					lastCommon = ($(opts[0]).attr('lastCommon') != undefined ? $(opts[0]).attr('lastCommon') : lastCommon);
					actLoop = (i == 14 && $(opts[0]).attr('loop') != undefined ? $(opts[0]).attr('loop') : actLoop);
					var tmp = opts[0].value.split('#');
					if (tmp[1] != undefined) {
						if (tmp[2] != null && tmp[2] != undefined) {
							imgName += tmp[2];
						}
						if (removeUnderscore == '1' && tmp[0].substr(0,1) == '-' && i == 16) {
							tmp[0] = tmp[0].replace('-', '');									//if the removeUnderscore is defined as '1', it is removed. Obviously the removeUnderscore mapping has to be set in the JSON file.
						}
						
						
						//My check for the HP48 or HP72 and how to handle it. What happens here is that the there is a check for HP48 or HP72. Then we make the modification on the model Number.
						//The attribute is stored in tmp[0]-The plan is to check that modelNo is HP48 or HP72. Then check tmp[0] to see if it is S,O, or B. Finally, change S,O, or B to -S,-O, or -B.
						
						searchFortyEight=modelNo.indexOf(fortyEightSearch); //Search for the index of the 48in model. 
						searchSeventyTwo=modelNo.indexOf(seventyTwoSearch); //Search for the index of the 72in model.
						
						
						//Search 48in models here
						if (searchFortyEight != -1){
						 if(tmp[0] == indoor){
						 tmp[0]="-S";						 
						 }
						 
						 
						if(tmp[0] == outdoor){
						 tmp[0]="-O";						 
						 }
						 
						 
						 if(tmp[0] == built){
						 tmp[0]="-B";						 
						 }
						 
						
						}
						//Done searching moving on to 72 in.
						
						
						
						//Search 72in models here.
												
						if (searchSeventyTwo != -1){
						 if(tmp[0] == indoor){
						 tmp[0]="-S";						 
						 }
						 
						 
						if(tmp[0] == outdoor){
						 tmp[0]="-O";						 
						 }
						 
						 
						 if(tmp[0] == built){
						 tmp[0]="-B";						 
						 }
						 
						
						}
						//Done Searching here. Moving on completely out of this filter.
						
						
						 
						
						
						
						// Check complete
						
						
						
						
						
						
						
						
						
						
						modelNo += (tmp[0] != '' && tmp[0] != null ? tmp[0]: '');
						html = ( (html != '' && tmp[1] ? html+', ':'')+tmp[1]);
					}
				}
			}
        } else if (allSteps[i-1].id) {
			var allOpts = $('#'+allSteps[i-1].id+' input');
			for(j=0; j<allOpts.length; j++) {
				allOpts[j].checked = false;
			}
		}
    }
	var tmp = modelNo.split('-');
	if (parseInt(firstCommon) > 0 && tmp.length > 1) {
		modelNo = tmp[0]+'-'+tmp[1];
		for(var i=0; i<parseInt(firstCommon) && tmp[2] != undefined; i++) {
			modelNo += '-'+tmp[2];
		}
		if (actLoop == 3 && tmp[3] != undefined) {
			modelNo += '-'+tmp[3];
		}
	}
	var tmp = modelNo.split('-');
	if (parseInt(lastCommon) > 0 && tmp.length > 1) {
		modelNo = tmp[0]+'-'+tmp[1];
		if (tmp[2] != undefined) {
			modelNo += '-'+tmp[2];
		}
		for(var i=0; i<parseInt(lastCommon) && tmp[3] != undefined; i++) {
			modelNo += '-'+tmp[3];
		}
	}
	if (imgName != '') {
		ajaxRequest(imgName, oldimagename);
	}
	
	//Html outputs that take the calculated function output and set it to screen.
	$('#step31').html('<span class="headmaroon">'+modelNo+'</span>');
	$('#modelLabel2').html('<span class="headmaroon">'+modelNo+'</span>');
	$('#dealerLink').html('<a href="/dealer-locator.php?buildModel='+modelNo+'" target="_blank">Click to find a dealer</a>');
	modelNum=modelNo;
	return true;
}













//hide every step and block after the element
//that matches the id that is passed in
function clearTail(id) {
	var allSteps = $('#main_content').find('.step');
	var startRemoving = false;
	for (i=0;i<allSteps.length;i++) {
		if (startRemoving == true) {
			if (allSteps[i].id) {
				$('#'+allSteps[i].id).remove();
				step--;
			}
		}
		if(allSteps[i].id == id) {
		   startRemoving = true;
		}
	}
}



//this function is called on document load and hides every step and block except step1
function clearAll() {
	//jquery method to find and hide every element underneath the #main_content table
	//  that has a CSS class of 'step'
	$('#main_content').find('.step').hide();
	
	//show only the 'step1' item - this is our starting point
	$('#step1').show();
}
