/**
 * @author sandy trinh
 */

//Define new class SelectAnOwner
function SelectAnOwner() {

	//Time interval for changing the start screen images and breed label, this value is in seconds
	var STARTSCREENINTERVAL = 5;
	//Timeout interval for inactive screen
	var INACTIVETIMEINTERVAL = 300;
	var NUMOFMAXINCORRECTCHOICE = 4;	
	//Set up the required labels that are displays in the result page.
	var REQUIREMENTLABELS = new Array(10);	
	REQUIREMENTLABELS[0] = 'Backyard.';
	REQUIREMENTLABELS[1] = 'Fencing.';
	REQUIREMENTLABELS[2] = 'Indoors.';
	REQUIREMENTLABELS[3] = 'Exercise.';
	REQUIREMENTLABELS[4] = 'Training.';
	REQUIREMENTLABELS[5] = '';
	REQUIREMENTLABELS[6] = 'Energy.';
	REQUIREMENTLABELS[7] = 'Company.';
	REQUIREMENTLABELS[8] = 'Tolerance.';
	REQUIREMENTLABELS[9] = '';
	REQUIREMENTLABELS[10] = 'Food Cost.';
	REQUIREMENTLABELS[11] = 'Grooming.';
		
	var containerOne = '#screen1';
	var containerTwo = '#screen2';
	var containerInView = containerOne;	
	var containerNotInView = containerTwo;
	var owner = new Owner();
	var questions = null;
	var breeds = null;
	var numOfQuestions = 0;
	var currentQuestionNum = 0;			//0 represent question one.
	var slidingDirection = 'forward';
	var bCTRLKey = 0;
	var bLetterQ = 0;
	var bAssignBreedSelectionNext = 0;
	var resultLog = new Array();
	//var timeoutObj = null;
		
	this.init = init;
	// this.loadStartScreen = loadStartScreen;
	//this.handleClick = handleClick;
	//this.resetTimeout = resetTimeout;
	//this.randomStartScreen = randomStartScreen;
	this.loadBreedSizeSelectionScreen = loadBreedSizeSelectionScreen;
	this.loadBreedSelectionScreen = loadBreedSelectionScreen;
	this.loadQuestionsScreen = loadQuestionsScreen;
	this.loadResultScreen = loadResultScreen;
	this.checkQuestionDependency = checkQuestionDependency;
	this.setUpQuestionStructure = setUpQuestionStructure;
	this.displayResult = displayResult;
	this.displayQuestion = displayQuestion;
	this.assignEventListener = assignEventListener;
	this.assignQuestionPagination = assignQuestionPagination;
	this.rotateContainers = rotateContainers;
	this.listBreeds = listBreeds;
	this.determineNumTiles = determineNumTiles;
	this.layoutBreeds = layoutBreeds;
	this.outputBreeds = outputBreeds;
	this.dectectLetterQ = dectectLetterQ;
	this.detectCTRLKey = detectCTRLKey;
	this.checkKeyPress = checkKeyPress;
	
	this.dependencyIndex = 0;
	
	
	
	function init() {
		//Set up event listeners for key presses, CTRL + q will exit the application
		document.onkeydown = detectCTRLKey;
        document.onkeyup = dectectLetterQ;
		// loadStartScreen(containerInView);
		getBreeds();
		loadBreedSizeSelectionScreen(containerInView);
		
	
	
		
		/*	
		//Need to re-order the window in the stage in order to activate the mouse hide in MAC
		var stage = htmlLoader.stage;	
		stage.nativeWindow.activate();
		stage.nativeWindow.orderToBack();
		stage.nativeWindow.orderToFront();
		//Hide mouse cursor	
		window.runtime.flash.ui.Mouse.hide();
		*/				
	}
	
	/*function loadStartScreen(container){
		if(timeoutObj)
			clearTimeout(timeoutObj);	
			
		$(container).load('com/gooddog/selectanowner/views/startScreen.html', {}, function (){
			// var breeds = getDataFromDB('SELECT id, breedname FROM breed ORDER BY breedname ASC');
			
			// To optimize this, we can make a webservice that only grabs the id and breedname
			$.getJSON("/ajax/ajaxGetBreeds.cfm?",{}, function(breeds){
	          	if (breeds.data && breeds.data.length > 0) 
				randomStartScreen(breeds.data, container);
	        });
			
			$('html').click(function () { 
		      handleClick(); 
		    });
				
			//window.addEventListener('click', handleClick);			
		});
	}
	
	function handleClick(){	
		$('html').unbind('click');
		
		loadBreedSizeSelectionScreen(containerInView);
		resetTimeout();
	}

	function resetTimeout(){
		clearTimeout(timeoutObj);
		timeoutObj = setTimeout(function(){loadStartScreen(containerInView)}, INACTIVETIMEINTERVAL * 1000);
	}

	function randomStartScreen(breeds, divId){
		var i = Math.floor(Math.random() * breeds.length);	
		$(divId + ' .left h1 em').html(breeds[i].breedname);
		$(divId + ' .right').html('<img src="/src/assets/images/breeds/' + breeds[i].id + '_feature.jpg" alt="' + breeds[i].breedname + '" />');
		timeoutObj = setTimeout(function(){randomStartScreen(breeds, divId)}, STARTSCREENINTERVAL * 1000);
	}*/
	
	function clearLoadCache () {
		return Math.random()*Math.random();
	}
	
	function loadBreedSizeSelectionScreen(container){
		
		resultLog = new Array ();
		//Set up blank properties for owner object
	
		owner.init(new Array(), new Breed(), '');	
		
		$(container).load('com/gooddog/selectanowner/views/breedSizeSelection.html?' + clearLoadCache(), function (html,textStatus){
			var bEventAssigned = 0;

			$('.sizeSelection').click(function(){
				$('.sizeSelection').removeClass('selected');
				$(this).addClass('selected');
				
				//Show breed size info
				$(container + ' .hightlighInfoWrap').show();
				//Change opacity of the size selections to almost invisible
				$(container + ' .dogSizes').css('opacity','0.1');
				$(container + ' .breedsExample').css('opacity','0.1');
				//Unbind events attached to size selection buttons
				$(container + ' .sizeSelection').unbind();
				
				owner.breedSize = getRelativeUrl($(this).attr('href'));

				if (bEventAssigned == 0) {
					assignEventListener('.next');
					bEventAssigned = 1;	
				}
				
				loadBreedSelectionScreen(containerNotInView);
				
				//resetTimeout();
				return false;				
			});
		});		
	}
	
	function getBreeds () {
		$.getJSON("/ajax/ajaxGetBreeds.cfm?",{}, function(data){
					
			breeds = data;
	    });
	}
	
	function loadBreedSelectionScreen(container){
		$(container).load('com/gooddog/selectanowner/views/breedSelections.html?' + clearLoadCache(), function (){
			bAssignBreedSelectionNext = 0;
			assignEventListener('.prev');
			// var breeds = getDataFromDB('SELECT * FROM breed ORDER BY breedname ASC');
			var divName = '.group1';
			
			if(breeds == null) {
		
				$.getJSON("/ajax/ajaxGetBreeds.cfm?",{}, function(data){
					
					breeds = data;
		          	if(breeds.data && breeds.data.length > 0){
						outputBreeds(breeds.data, 0, breeds.data.length, container + ' ' + divName, 1);
						listBreeds(container, divName, owner.breedSize);					
					}	
		        });
			} else {
				outputBreeds(breeds.data, 0, breeds.data.length, container + ' ' + divName, 1);
				listBreeds(container, divName, owner.breedSize);
			}
				
		});
	}
	
	function loadQuestionsScreen(container) {		

		$.getJSON("/ajax/ajaxGetQuestions.cfm?",{}, function(data){
			
			questions = data;
          	numOfQuestions = questions.data.length;
          	currentQuestionNum = 0;
          	
          	//Load html structure into display div
			$(container).load('com/gooddog/selectanowner/views/questions.html?' + clearLoadCache(), function (){
				assignEventListener(container+' .start');	
				if(numOfQuestions > 0)
					displayQuestion(containerNotInView, currentQuestionNum, setUpQuestionStructure);														
			});
          	
        });
			
			
	}
		
	function loadResultScreen(container){
		$(container).load('com/gooddog/selectanowner/views/result.html?' + clearLoadCache(), function (){
			
			//Compile result log that stores the result for each answer			
			// var breedAnswer = getDataFromDB('SELECT * FROM answer WHERE breedid="' + owner.selectedBreed.id + '"');
			
			$.getJSON("/ajax/ajaxGetBreedAnswer.cfm?",{breedid:owner.selectedBreed.id}, function(breedAnswer){
   				
   				if(breedAnswer && breedAnswer.data && breedAnswer.data.length > 0 && owner.answers.length > 0){
					// var resultLog = new Array(owner.answers.length);
					var requiredChoice = '';
					var ownerChoice = '';	
					var i = 0;
						
					jsonDependancy (i, owner.answers.length - 1, breedAnswer,container);  		
				}
				
				//Assign event for start button
				assignEventListener('.prev');	
	        });
			

					
		});
	}
	
	function jsonDependancy (index, total, breedAnswer,container) {	

		ownerChoice = owner.answers[index].answer;
		requiredChoice = breedAnswer.data[index].requiredchoice;
		
		// checkQuestionDependency(breedAnswer.data[i].id, ownerChoice, owner.answers);
		$.getJSON("/ajax/ajaxGetChoiceDependancy.cfm?",{answerid:breedAnswer.data[index].id,answerchoice:ownerChoice}, function(choiceDependency){
			
			var bDependancy = false;
			
			if(requiredChoice.indexOf(ownerChoice) >= 0 || requiredChoice == 'all')	 {										

				if (choiceDependency.data && choiceDependency.data.length > 0){
					resultLog[index] = checkQuestionDependency(choiceDependency,breedAnswer.data[index].id, ownerChoice, owner.answers);
					
				} else {
					resultLog[index] = 1;
				}	
				
			} else {
				resultLog[index] = 0;
			}

			if(index == total) {
				displayResult(breedAnswer,resultLog, container + ' .result');				
			} else {
				index++;
				jsonDependancy(index,total,breedAnswer,container)
			}
			
		});
	}
	

	function checkQuestionDependency(choiceDependency, answerId, selectedChoice, answers ) {		
	
		if (choiceDependency.data && choiceDependency.data.length > 0){
			for(var j=0; j<choiceDependency.data.length; j++ ){
				//Since owner's choice is the same as the dependency answer, then let's check if the answer for correlated question is the same
				for(var k=0; k<answers.length; k++){
					
					if(answers[k].questionId == choiceDependency.data[j].correlatequestionid && answers[k].answer == choiceDependency.data[j].requiredchoice)
					return 1;																								
				}										
			}
			//If correlated answer doesn't match the required answer, flag result as incorrect 
			return 0;
		}
		return 1;
	}

	function setUpQuestionStructure(){
		//load html structure for the hidden container
		$(containerNotInView).load('com/gooddog/selectanowner/views/questions.html?' + clearLoadCache(), function (){
			assignEventListener(containerNotInView+' .start');
		});
	}

	function displayResult(answers, results, divId){
		//Output requirement details
		if(answers.data.length > 0 && results.length > 0){
			var numOfIncorrectAnswer = 0;
			var str = '';
			
			//Output the correct answer for selected breed
			for(var i=0; i<results.length; i++){
				if (i != 5 && i != 9)				
					str += '<p><strong>' + REQUIREMENTLABELS[i] + '</strong><em> ' + answers.data[i].dogcomment + '</em></p>';						
			}
			
			$(divId + ' .breedAnswer .details').html(str);	
			
			//Clear str value
			str = '';	
			
			//Output user result
			for(var i=0; i<results.length; i++){
				if (i != 5 && i != 9) {		
					if (results[i] == 1)
						str += '<p>';
					else {
						str += '<p class="error">';
						//Calculate the number of incorrect answers
						numOfIncorrectAnswer++;
					}					
					str += '<strong>' + REQUIREMENTLABELS[i] + '</strong><em> ' + owner.answers[i].answerText + '</em></p>';
				}							
			}
			$(divId + ' .myResult .details').html(str);					
				
		}
		
		//Display breed photo
		$(divId + ' .mugshot').html('<img src="/src/assets/images/breeds/' + owner.selectedBreed.id + '_mugshot.jpg" alt="' + owner.selectedBreed.name + '" border="0" />');
		//Remove click and drag event
		$(divId + ' .mugshot').click(function (){
			return false;
		});
		
		//Assign event to go to 'About Me' page
		assignEventListener(divId + ' #aboutMe');
		
		//Check if weighted questions has the correct answer
		
		$.getJSON("/ajax/ajaxGetBreedWeightedQuestions.cfm?",{breedid:owner.selectedBreed.id}, function(breedWeightedQuestions){
			
			var bIncorrectWeightedQuestion = checkWeightQuestions(divId, results,breedWeightedQuestions);
		
			//air.trace(numOfIncorrectAnswer);					
			//Output selected breed details and result		
			if(bIncorrectWeightedQuestion) {
			
				$(divId + ' .heading p').html("<p>Oh No! I don't think we are compatible.</p>");				
			} else if (numOfIncorrectAnswer >= NUMOFMAXINCORRECTCHOICE){
				$(divId + ' .heading p').html("<p>Oh No! I don't think we are compatible.</p>");	
				$(divId + ' .conclusion').hide();
				$(divId + ' .advice').show();
			}
			else
				$(divId + ' .heading p').html('<h3>Excellent! I think we could be great friends. </h3>');
			
			$(divId + ' .heading h1').html('<h1>'+ owner.selectedBreed.name +'</h1>');
		});

	}

	function checkWeightQuestions(divId, results, breedWeightedQuestions){
		var iTmp = 0;
		// var breedWeightedQuestions = getDataFromDB('SELECT * FROM breed INNER JOIN weightedquestion ON breed.id = weightedquestion.breedid WHERE breed.id="' + owner.selectedBreed.id + '"');
		
		if(breedWeightedQuestions.data && breedWeightedQuestions.data.length){
			if(breedWeightedQuestions.data[0].first.toString() > 0){
				//Check the first weighted question be retrieving the question number minus 1 because array index always starts at 0.
				iTmp = parseInt(breedWeightedQuestions.data[0].first) - 1;

				if(results[iTmp] == 0){
					$(divId + ' .conclusion span').html(breedWeightedQuestions.data[0].firstcomment);
					return true;
				}				
			}
			if(breedWeightedQuestions.data[0].second.toString().length > 0){
				//Check the second weighted question be retrieving the question number minus 1 because array index always starts at 0.
				iTmp = parseInt(breedWeightedQuestions.data[0].second) - 1;
				
				if(results[iTmp] == 0){
					$(divId + ' .conclusion span').html(breedWeightedQuestions.data[0].secondcomment);
					return true;
				}				
			}			
		}
		return false;
	
	}

	function displayQuestion(divId, i, callback){		
		var bQuestionAnswered = false;
		
		if(numOfQuestions > 0 && i >= 0 && i < numOfQuestions){
		
			var bEventAssigned = 0;
			var str = '';					//Container for the question		
	
			//Update progress bar		
			var progressBar = $(divId+' .progressBar').children('em');			
			progressBar.removeClass();
			for(var k=0; k<i+1; k++)
				$(progressBar[k]).addClass('active');
			
			$(divId+' .footer').html('<a href="loadBreedSelectionScreen" class="prev">Previous Question</a>');

			//If i is question one, prev link to should to breed selection screen
			if(i == 0)
				assignEventListener(divId+' .prev');				
			else
				assignQuestionPagination(divId+' .prev');	

			str += '<div class="questionWrap"><div class="currentQuestion"><h1>' + questions.data[i].question + '</h1></div></div>';
			
			/*Air has some issue dynamically loading images from CSS file when we add the class 'selected' to the anchor.
				By loading the class in a blank anchor that is hidden seems to fix this problem. */
			str += '<div class="choices"><a href="#" class="questionChoice selected blank"></a>';

			if(questions.data[i].choicea && questions.data[i].choicea.length > 0 )
				str += '<a href="' + questions.data[i].id + '" class="questionChoice" title="a">' + questions.data[i].choicea + '</a>';
			if(questions.data[i].choiceb && questions.data[i].choiceb.length > 0 )
				str += '<a href="' + questions.data[i].id + '" class="questionChoice" title="b">' + questions.data[i].choiceb + '</a>';		
			if(questions.data[i].choicec && questions.data[i].choicec.length > 0 )
				str += '<a href="' + questions.data[i].id + '" class="questionChoice" title="c">' + questions.data[i].choicec + '</a>';
			if(questions.data[i].choiced && questions.data[i].choiced.length > 0 )
				str += '<a href="' + questions.data[i].id + '" class="questionChoice" title="d">' + questions.data[i].choiced + '</a>';
			
			str += '</div>';
			
			$(divId + ' .questions').html(str);	

			$(divId + ' .questionChoice').click(function (){
				
				if(bQuestionAnswered == false) {
					bQuestionAnswered = true;
					//Record user's selected choice
					owner.setAnswer(i, getRelativeUrl($(this).attr('href')), $(this).attr('title'), $(this).text());
					
					$(divId + ' .questionChoice').removeClass('selected');
					$(this).addClass('selected');
					
					//Highlight question and display comment accompanied with the next button to the next question
					$(divId+ ' .questionWrap').after('<div class="hightlighInfoWrap"><div class="hightlighInfo"><h1>' + questions.data[i].question + '</h1><p>'+questions.data[i].comment +'</p><a href="rotateContainers" class="next">Next Question</a></div></div>');
					
					//Change opacity of the question choices to almost invisible		
					$(divId + ' .choices').css('opacity', '0.1');
					//Unbind all event listener that were assigned to questionChoice link after use has made a selection so that only one choice can be selected on each screen	
					//$(divId + ' .questionChoice').unbind();
			
					if(bEventAssigned == 0){
						bEventAssigned = 1;				
						if(i == numOfQuestions - 1){
							//If i is the last question, the next link should go to Result page
							assignEventListener(divId+' .next');	
							loadResultScreen(containerNotInView);
						}
						else if (i == 0){
							//Next link should go to start of the first question
							assignQuestionPagination(divId+' .next');
						}	
						else{
							//Otherwise assign onClick event for going to the next question
							assignQuestionPagination(divId+' .next');	
						}	
					}
					//resetTimeout();
				}
				
				return false;				
			});
					
			rotateContainers(callback);							
		}							
	}

	function displayBreedInfo(container){
		$(container).load('com/gooddog/selectanowner/views/breedInfo.html?' + clearLoadCache(), function (){
			var obj = $(container + ' .description');
			obj.children('h1').html(owner.selectedBreed.name);
			$(container + ' .mugshot').html('<img src="/src/assets/images/breeds/' + owner.selectedBreed.id + '_mugshot.jpg" alt="' + owner.selectedBreed.name + '" border="0" />');
			
			// var breedInfo = getDataFromDB('SELECT description, idealowner FROM breed WHERE  ="' + owner.selectedBreed.id + '"');
			
			$.getJSON("/ajax/ajaxGetBreedInfo.cfm?",{breedid:owner.selectedBreed.id}, function(breedInfo){
				
				if(breedInfo.data && breedInfo.data.length > 0){
					obj.children('.myInfo').html(breedInfo.data[0].description);
					obj.children('.myOwner').html(breedInfo.data[0].idealowner);
				}	
				
				//Assign event for start button
				assignEventListener('.prev');
			});				
		});		
	}
	
	function getRelativeUrl (url) {
		var re = new RegExp('(.+)(/)(.+)');
		var relativeUrl = url.replace(re,'$3');
		
		return relativeUrl
	}
	
	function assignEventListener(className){
		

		$(className).click(function (){		
			//Configure sliding direction
			if(className.indexOf('next') > 0 || className.indexOf('aboutMe') > 0)
				slidingDirection = 'forward';	
			else 
				slidingDirection = 'backward';
			
	
			
			switch (getRelativeUrl($(this).attr('href'))){				
				case 'loadBreedSizeSelectionScreen' :
					loadBreedSizeSelectionScreen(containerNotInView);
					rotateContainers();
					break;

				case 'loadBreedSelectionScreen' :
					loadBreedSelectionScreen(containerNotInView);
					rotateContainers();
					break;
				
				case 'loadQuestionsScreen' : 
					loadQuestionsScreen(containerNotInView);
					break;
					
				case 'loadResultScreen' :
					loadResultScreen(containerNotInView);
					rotateContainers();
					break;	
					
				case 'breedInfo' :
					displayBreedInfo(containerNotInView);	
					rotateContainers();
					break;	
					
				case 'rotateContainers' :
					rotateContainers();
						
			}
			
			//resetTimeout();
			return false;
		});			
	}
	
	function assignQuestionPagination(className){
		$(className).click(function (){	
			if(className.indexOf('next') > 0){
				slidingDirection = 'forward';
				currentQuestionNum++;
			}				
			else{
				slidingDirection = 'backward';
				currentQuestionNum--;
			}					
			displayQuestion(containerNotInView, currentQuestionNum);
			//resetTimeout();
			return false;
		});					
	}
	
	function rotateContainers(callback){
		//set up default sliding widths for each screen to slide forward
		var containerNotInViewSlidingWidth = '986px';
		var containerInViewSlidingWidth = '-986px';
		
		if (slidingDirection == 'backward') {
			containerNotInViewSlidingWidth = '-986px';
			containerInViewSlidingWidth = '986px';		
		}
					
		//position containerNotInView to be next to the containerInView
		$(containerNotInView).css('left', containerNotInViewSlidingWidth);
		//slide the containers
		$(containerInView).animate({left: containerInViewSlidingWidth}, 'slow');
		$(containerNotInView).animate({left: '0px'}, 'slow', callback);			
		
		//Reconfigure which container is in view
		var temp = containerInView;
		containerInView = containerNotInView;
		containerNotInView = temp;			
	}
	
	function listBreeds(divId, targeDiv, breedSize) {

		// var breedsBySize = getDataFromDB('SELECT * FROM breed WHERE size="' + breedSize +'" ORDER BY breedname ASC');
		var str = '';
		var slideInView = targeDiv;
		var NUMPERSLIDE = 10;
		
		//Update size text and background images by changing the class name of the div
		$(divId + ' .sizeOptions h3').html('<img src="/src/assets/images/' + breedSize + 'Breeds.gif"/>');
		$(divId + ' .sizeOptions').removeClass('small medium large');
		$(divId + ' .sizeOptions').addClass(breedSize);
		
		$(divId + ' .sizeOptions a').click(function (){
			//Unbind onclick event for selectors below so they will be only bind once through out the execution of each function
			$(this).unbind();
			$(divId + ' .prevBreedSelections').unbind();
			$(divId + ' .nextBreedSelections').unbind();
			//Reset the pagination buttons to be inactive
			$(divId + ' .prevBreedSelections').addClass('inActive');
			$(divId + ' .nextBreedSelections').addClass('inActive');	
			
			owner.breedSize = getRelativeUrl($(this).attr('href'));
			
			listBreeds(divId, targeDiv, owner.breedSize);
			//resetTimeout();
			return false;
		});
		
		$.getJSON("/ajax/ajaxGetBreedsBySize.cfm?",{size:breedSize}, function(breedsBySize){
      		if(breedsBySize.data && breedsBySize.data.length){

				var iStartRow = 0;
				var iEndRow = breedsBySize.data.length;
				
				if(iEndRow > NUMPERSLIDE){
					iEndRow = NUMPERSLIDE;
				}
	
				// function layoutBreeds (breeds, pagePosition, start, numTiles, size) {
				var newNUMPERSLIDE = numTilesToDisplay(breedsBySize,iStartRow);
				iEndRow = layoutBreeds(breedsBySize.data, iStartRow, newNUMPERSLIDE, breedsBySize.data.length - NUMPERSLIDE, breedsBySize.data.length - 1, breedSize, divId + ' ' + slideInView);

				$(divId + ' .prevBreedSelections').click(function (){
					if (!$(this).hasClass('inActive')) {					
						iStartRow = iStartRow - determineNumTiles(iStartRow, NUMPERSLIDE, breedsBySize.data.length - NUMPERSLIDE + iStartRow, 'prev');													
						var newNUMPERSLIDE = numTilesToDisplay(breedsBySize,iStartRow);
						iEndRow = layoutBreeds(breedsBySize.data, iStartRow, newNUMPERSLIDE, breedsBySize.data.length - (iStartRow), breedsBySize.data.length - 1, breedSize, divId + ' ' + slideInView);				
		
					}					
					//resetTimeout();
					return false;				
				});
				
				$(divId + ' .nextBreedSelections').click(function (){
					if(!$(this).hasClass('inActive')){
								
						iStartRow = iEndRow;
						var newNUMPERSLIDE = numTilesToDisplay(breedsBySize,iStartRow);
						iEndRow = layoutBreeds(breedsBySize.data, iStartRow, newNUMPERSLIDE, breedsBySize.data.length - (iStartRow), breedsBySize.data.length - 1, breedSize, divId + ' ' + slideInView);					
					}
					//resetTimeout();
					return false;				
				});					
			}
			else
				$(divId + ' ' + slideInView).html('Oh no, it seems there is no breed selections for your selected size.');
	      		
	        });
	}
	
	function numTilesToDisplay (breedsBySize,startRow) {
		var tilesPerSlide = 10; 
		var tilesToDisplay = 10;
		var remainingTiles = breedsBySize.data.length - (startRow);

		if(startRow !=0) tilesToDisplay--; // there's a prev button;
		if(remainingTiles > tilesToDisplay) tilesToDisplay--; //there's a next button
		
		return tilesToDisplay;
	}
	

	function determineNumTiles (start, numTiles, numRemainingTiles, direction) {	
		var tmp = numTiles;
		if (numRemainingTiles > 0) tmp--;
			
		if (direction.length > 0 && start != 0 && start > numTiles) tmp--;		 
		else if(direction.length <= 0 && start != 0 ) tmp--;
					
		return tmp;		
	}

	function layoutBreeds (breeds, start, numTiles, numRemainingTiles, total, size, divId) {
		
		/* start: first tile num */
		/* numTiles: number of tiles to layout */
		/* size: small, medium, large */
		
		var height = 225;
		var width = 186;
		var obj;
		var bHasNext = false;
		var bHasPrevious = false;
		var placementFactor = (bHasPrevious) ? 1 : 0;
		var verticalIndex = 0;
		var horizontalIndex = 5
		var tileIndex = 0;
		var end = start;
		var obj;
		
		//numTiles = determineNumTiles(start, numTiles, numRemainingTiles, '');		
		var pos = numTiles + start;

		if (pos < (total + 1)) bHasNext = true;  
		if (start != 0) bHasPrevious = true;
		
		// make all breed tiles offscreen to start with
		$(divId + ' ' +' .breedSelection').css('left', '-9999px');

		end = start + (numTiles - 1);	
		if(end > total) end = total;
		
		// display previous or next as required
		if (bHasPrevious) {
			$('.prevBreedSelections').removeClass('inActive');	
			$('.prevBreedSelections em').html(((end + 1) - numTiles) + ' of ' + (total + 1) + ' breeds');
		} 
		else {
			$('.prevBreedSelections').addClass('inActive');
		}
		
		if (bHasNext) {
			$('.nextBreedSelections').removeClass('inActive');	
			$('.nextBreedSelections em').html((start + 1 + numTiles) + ' of ' + (total + 1) + ' breeds');
		} 
		else {
			$('.nextBreedSelections').addClass('inActive');
		}
				
		// loop through and position those on screen as required
		for (var i = start; i <= end; i++) {

			//If we are on first row and previous link is required, skip the first tile so this tile can be used to display prev link
			if (tileIndex == 0 && verticalIndex == 0 && bHasPrevious) tileIndex = 1;		
			if (verticalIndex == 1 && bHasNext) horizontalIndex = 4;
			
			obj = $('#'+ breeds[i].id, divId);			
			obj.css('left', tileIndex*width);
			obj.css('top', verticalIndex*height);
			
			tileIndex++;
			if (tileIndex >= horizontalIndex) {
				tileIndex = 0;
				verticalIndex++;
			}		
		}

		return end + 1;

	}
	
	function outputBreeds(breeds, start, end, divId, bAssignNext){
		var str = '';

		for (var i=start; i<end; i++){
			str += '<a href="#" id="' + breeds[i].id + '" class="breedSelection ' + breeds[i].size;			
			str += '" title="' + breeds[i].id + '"><img src="/src/assets/images/breeds/' + breeds[i].id + '_thumb.jpg?' + clearLoadCache() + '" alt="" border="0" />';
			
			if(breeds[i].breedname.length > 14)
				str += '<em class="long">';
			else
				str += '<em>' 
			
			str += breeds[i].breedname + '</em></a>';							
		}	
		
		$(divId).html(str);
		
		//Assign click event to each breed link		
		$(divId + ' .breedSelection').click(function (){
			$(divId + ' .breedSelection').removeClass('selected');
			$(this).addClass('selected');
			
			//Add info for user breed selection
			owner.selectedBreed.init($(this).text(), $(this).attr('title'));
										
			if(bAssignNext == 1){
				if(bAssignBreedSelectionNext == 0){
					$('.next').removeClass('inActive');
					assignEventListener('.next');
					//flag this variable, so the next button on the breed selection screen will be assigned just once.			
					bAssignBreedSelectionNext = 1;		
				}				
			}
			else{
				slidingDirection = 'forward';
				loadResultScreen(containerNotInView);
				rotateContainers();				
			}
			
			loadQuestionsScreen(containerNotInView);
			//resetTimeout();
			return false;							
		});			
	}		

	function dectectLetterQ(e){
		var eventObj = window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
		
		var unicode = eventObj.charCode? eventObj.charCode : eventObj.keyCode;
		var actualkey = String.fromCharCode(unicode);

		if (actualkey=="q" || actualkey=="Q"){
			bLetterQ = 1;
			checkKeyPress();
		}
	}

	function detectCTRLKey (e){
		var eventObj=window.event? event : e
		if (eventObj.ctrlKey){
			bCTRLKey = 1;					
		}					
	}
	
	function checkKeyPress(){
		if(bCTRLKey && bLetterQ ){
			if (confirm("Are you sure you want to exit?")) { 
				quitApp();	
			}
		}		
	}



}