﻿BenefulMap.ModalAddSpot = BenefulMap.ModalAuthenticatedForm.extend({
    init: function(modalTitle, modalSlug, modalElements, modalOptions, snippetPath, params, formElements, fieldsets, links, continueButtons, categoryButtons, otherCategorySuggestion, categoryFieldsets, categoryFieldsetsParameters,addSpotFieldBehaviors) {
        this._super(modalTitle, modalSlug, modalElements, modalOptions, snippetPath, params, formElements);
        this.fieldsets = fieldsets;
		this.categoryFieldsets = categoryFieldsets;
		this.categoryFieldsetsParameters = categoryFieldsetsParameters;
		this.addSpotFieldBehaviors = addSpotFieldBehaviors;
        this.links = links;
        this.continueButtons = continueButtons;
        this.categoryButtons = modalElements.modalDiv + " " + categoryButtons;
        this.otherCategorySuggestion = modalElements.modalDiv + " " + otherCategorySuggestion;
        this.allowSubmission = true;
        this.redisplayWithErrors = false;
		this.openListener("addspot.open");
		this.validationOnce = false;
		this.categoryFieldsValid = false;
		this.checkDuplicateData = {};
		this.storedSpotData = [];
		this.selectSpotClicked = false;
		this.selectedSpotData = {};
		this.selectedSpotId = 0;
		this.addingReview = false;
    },
	openListener: function(eventName) {
		var self = this;
		$(document).bind(eventName, function(event) {
			self.open();
		});
	},
	close: function() {
		this._super();
	},
    getCategoryButtons: function() {
        return this.categoryButtons;
    },
    getOtherCategorySuggestion: function() {
        return this.otherCategorySuggestion;
    },
    radioButtonListeners: function() {
        var self = this;
        console.log(this.getCategoryButtons());
        console.log(this.getOtherCategorySuggestion());
        $(this.getCategoryButtons()).click(function(event) {
            if ($(this).val() == "5") {
                $(self.getOtherCategorySuggestion()).removeAttr("disabled");
            } else {
                $(self.getOtherCategorySuggestion()).attr("disabled", "disabled");
            }
        });
		this.displayCurrentCategoryExamples();
		this.displayPlayOptions();
		this.clearInstructionListener();
    },
    getCurrentStage: function() {
        return this.currentStage;
    },
    setCurrentStage: function(currentStage) {
        this.currentStage = currentStage;
    },
	setCategoryFields: function(category) {
		console.log("category selector is: ", category);
		this.categoryFieldSelector = category;
	},
	getCurrentCategory: function() {
		var currentCategory = $(this.categoryFieldsetsParameters.selectedCategory + " input:checked").val();
		return currentCategory;
	},
	displayCurrentCategoryExamples: function() {
		var self = this;	
		$("#categoryFields input").click( function() {
			var currentCategoryID = $(this).attr("id");
			if (currentCategoryID) {
				$(".ui-dialog li.spot-category fieldset li.directive").hide();
				$(".ui-dialog li.spot-category fieldset #" + currentCategoryID + "CategoryEg").show();
			};
			self.categoryFieldsValid = true;
			var formValid = self.checkCurrentFormIsValid();
			if (self.categoryFieldsValid && formValid)
			{
				self.enableCurrentContinueButton();
			};
		});	
	},
	displayPlayOptions: function() {
		$("#add-spot-play #categoryQuestion2 input").click( function() {
			var selectedAdventure = $(this).attr("id");
			if(selectedAdventure) {
				$("#add-spot-play #play-options select").attr("id","").hide();		
				var selectedSelectBox = $("#play-options select[name='" + selectedAdventure + "']");
				selectedSelectBox.attr("id","categoryQuestion1").show();
			};
		});
	},
	getHeadlineField: function() {
	   return this.addSpotFieldBehaviors.titleSelector;
	},
	getReviewField: function() {
	   return this.addSpotFieldBehaviors.reviewSelector;
	},
	clearInstructionListener: function() {
	    var self = this;
	    $(this.getHeadlineField())
	    .focus(function()
	    {
	    	if($(this).val() === BenefulMap.Constants.Strings.ADD_SPOT_HEADLINE)
	    		$(this).val('');
	    })
	    .blur(function()
    	{
	    	if($(this).val() === '')
	    		$(this).val(BenefulMap.Constants.Strings.ADD_SPOT_HEADLINE);
	    });
	    $(this.getReviewField())
	    .focus(function()
	    {
	    	if($(this).val() === BenefulMap.Constants.Strings.ADD_SPOT_REVIEW)
	    		$(this).val('');
	    })
	    .blur(function()
    	{
	    	if($(this).val() === '')
	    		$(this).val(BenefulMap.Constants.Strings.ADD_SPOT_REVIEW);
	    });
	},
	showCategoryFieldsets: function() {	
		switch (this.getCurrentCategory()) {
			case "1":
				console.info("Spot category is Play");
				this.showIndividualCategoryFieldsets("play");
				break;
			case "2":
				console.info("Spot category is Eat");
				this.showIndividualCategoryFieldsets("eat");
				break;
			case "3":
				console.info("Spot category is Stay");
				this.showIndividualCategoryFieldsets("stay");
				break;
		    default:
                return false;
		}
	},
    switchStage: function(newStage, disableContinueButton) {
        this.setCurrentStage(newStage);
        this.showFieldset(newStage);
        if (newStage == "checkDuplicate" || newStage == "step1" || newStage == "step2") {
            console.info("setting validation listeners");
			this.validationOnce = false;
            this.validationListeners();
        }
        if (disableContinueButton == true) {
            this.disableCurrentContinueButton();
        }
		else {
			this.enableCurrentContinueButton();
		}
        console.log("Current Stage is now: ", this.getCurrentStage());
    },
    goToNextStage: function() {
        switch (this.getCurrentStage()) {
			case "checkDuplicate":
				this.submitCheckDuplicateData();
				break;
			case "foundDuplicate":
				this.switchStage("duplicateSpots", true);
				this.duplicateSpots();
				break;
			case "noDuplicate":
				this.switchStage("step1", true);
				this.handleCheckDuplicateData(); // injects form data already entered by user during checkDuplicate into fields in step1
				break;
			case "duplicateSpots":
				this.categoryFieldsValid = true; // bypass category field validation in duplicate spot found flow
				this.switchStage("step2", false);
				this.setAddingReview(true);
				this.clearInstructionListener();
				break;
           case "step1":
                this.switchStage("step2", false);
				this.showCategoryFieldsets();
                break;
            case "step2":
				this.processReview();
                this.switchStage("uploadPhoto", false);
				this.setBusinessId();
				this.embedPhotoSwf();
                break;
            case "uploadPhoto":
                this.processForm();
                break;
            default:
                return false;
        }
    },
    goToPrevStage: function() {
        switch (this.getCurrentStage()) {
            case "step2": // This may need to be handled differently
                this.categoryFieldsValid = false; // re-instate category field validation in duplicate spot found flow if user clicks "I don't see my spot" button
				this.switchStage("step1", false);
                break;
            case "uploadPhoto":
                this.switchStage("step2", false);
                break;
            default:
                return false;
        }
    },
    getFieldsets: function() {
        return this.fieldsets;
    },
    setFieldsets: function(fieldsets) {
        this.fieldsets = fieldsets;
    },
    getIndividualFieldset: function(dataKey) {
        return this.fieldsets[dataKey];
    },
    setIndividualFieldset: function(dataKey, dataValue) {
        this.fieldsets[dataKey] = dataValue;
    },
	getCategoryFieldsets: function() {
		return this.categoryFieldsets;
	},
	getIndividualCategoryFieldsets: function(datakey) {
		return this.categoryFieldsets[datakey];
	},
	showIndividualCategoryFieldsets: function(fieldsetKey) {
		var self = this;
        jQuery.each(this.getCategoryFieldsets(), function(key, val) {
            if (key == fieldsetKey) {
                $(val).show();
				self.setCategoryFields(val);
            } else {
                $(val).hide();
            }
        });		
	},
    showFieldset: function(fieldsetKey) {
        jQuery.each(this.getFieldsets(), function(key, val) {
            if (key == fieldsetKey) {
                $(val).show();
            } else {
                $(val).hide();
            }
        });
    },
    getLinks: function() {
        return this.links;
    },
    setLinks: function(links) {
        this.links = links;
    },
    getBackLinks: function() {
        return this.links.back;
    },
    setBackLinks: function(backLinks) {
        this.links.back = backLinks;
    },
    getSkipLinks: function() {
        return this.links.skip;
    },
    setSkipLinks: function(skipLinks) {
        this.links.skip = skipLinks;
    },
    getContinueButtons: function() {
        return this.continueButtons;
    },
    setContinueButtons: function(continueButtons) {
        this.continueButtons = continueButtons;
    },
    populate: function() {
		var self = this;
		jQuery.ajax({
		    type: "GET",
			cache: false,
			url: self.getSnippetPath(),
			data: self.getParams(),
			success: function(data, textStatus) {
				$( self.getModalDiv() ).html(data);
				$( self.getModalDiv() ).dialog('open');
				self.addModalListeners();
			},
			dataType: "html"
		});
	},
    addModalListeners: function(stepName) {
		if (stepName) {
			this.switchStage(stepName, true);
		} else {
			this.switchStage("checkDuplicate", true); //sets initial state of fieldset displayed
		}
		this._super();
		this.backLinksListener();
		this.skipLinksListener();
		this.showFieldset(this.getCurrentStage());
	},
    backLinksListener: function() {
        var self = this;
        $(this.getBackLinks()).click(function() {
            self.goToPrevStage();
        });
    },
    skipLinksListener: function() {
        var self = this;
        $(this.getSkipLinks()).click(function() {
            self.goToNextStage();
        });
    },
    embedPhotoSwf: function() {
    	console.info("embedding swf");
        var swfContainer = "flashcontent";
        var swfPath = root + "_res/swf/TransformTool.swf";
        var expressInstallPath = root + "_res/swf/expressInstall.swf";

        var flashvars = {};
        flashvars.BusinessID = $("#flash-business-id input").val();
        flashvars.PhotoKey = $("#flash-user-id input").val();
        flashvars.endpointURI = $("#FlashEndPointUri").val();
		flashvars.serverLocation = $("#FlashServerLocation").val();
        flashvars.Context = "Admin";
        flashvars.flash_name = "flashcontent";

        var params = {};
        params.quality = "high";
        params.allowScriptAccess = "sameDomain";
        params.wmode = "transparent";
        params.base = root + "_res/swf/";
        params.bgcolor = "#ffffff";

        var attributes = "";

        swfobject.embedSWF(swfPath, swfContainer, "710", "500", "10", expressInstallPath, flashvars, params, attributes);
    },
    continueButtonListener: function() {
        var self = this;
        $(this.getContinueButton()).unbind();
        $(this.getContinueButton()).click(function(event) {
            event.preventDefault();
            if (self.currentContinueButtonIsEnabled()) {
				self.goToNextStage();					
            }
        });
    },
    getCurrentContinueButton: function() {
        return this.continueButtons[this.getCurrentStage()];
    },
    setCurrentContinueButton: function(val) {
        this.continueButtons[this.getCurrentStage()] = val;
    },
    currentContinueButtonIsEnabled: function() {
        if ($(this.getCurrentContinueButton()).hasClass('disabled') == false) {
            return true;
        } else {
            return false;
        }
    },
    disableCurrentContinueButton: function() {
        console.info("Current continue button disabled :(");
        $(this.getCurrentContinueButton()).addClass("disabled");
    },
    enableCurrentContinueButton: function() {
        console.info("Current continue button enabled :)");
        $(this.getCurrentContinueButton()).removeClass("disabled");
    },
    getCurrentFieldsToValidate: function() {
        return this.formElements[this.getCurrentStage()].fieldsToValidate;
    },
    setCurrentFieldsToValidate: function(fields) {
        this.formElements[this.getCurrentStage()].fieldsToValidate = fields;
    },
    getCurrentFieldsToSerialize: function() {
        return this.formElements[this.getCurrentStage()].fieldsToSerialize;
    },
    setCurrentFieldsToSerialize: function(fields) {
        this.formElements[this.getCurrentStage()].fieldsToSerialize = fields;
    },
    getCurrentRequiredFields: function() {
        return this.formElements[this.getCurrentStage()].requiredFields;
    },
    setCurrentRequiredFields: function(fields) {
        this.formElements[this.getCurrentStage()].requiredFields = fields;
    },
    validationListeners: function() {
		if (this.validationOnce == false) {
			var self = this;
	         $(this.getCurrentFieldsToValidate()).blur(function(event) {
	             self.validateField(this);
	         });
			 $(this.getCurrentFieldsToValidate()).change(function(event) {
	             self.validateField(this);
	         });
	         $(this.getCurrentFieldsToSerialize()).filter(":not(:radio)").keyup(function(event) {
				var validStatus = self.checkCurrentFormIsValid();
				self.setFormStatus(validStatus);
			});	
		};
		this.validationOnce = true;
    },
    validateField: function(formItem) {
        var self = this;
        var fieldData = {};
        fieldData.FieldName = $(formItem).attr('name');
        fieldData.FieldAnswer = $(formItem).val();
        var json = JSON.stringify(fieldData);
        var validationFunction = 'Validate' + fieldData.FieldName;
        WagWorld.Web.AjaxValidation[validationFunction](json, function(result) {
            var errorMsg = result.value.ErrorMessage;
            var fieldName = result.value.FieldName;
            if (!errorMsg) {
                console.info(fieldName + " passed validation :)");
                $(formItem).removeClass("invalidField");
            } else {
                console.info(fieldName + " failed validation :(");
                $(formItem).addClass("invalidField");
            };
			var validForm = self.checkCurrentFormIsValid();
			self.setFormStatus(validForm);
        });
    },
	validateRadioGroup: function() {
		var validForm = false;
		var reqFields = $(this.getCurrentRequiredFields());
		var selectedRadio = $(reqFields).filter(":radio:visible:checked");
		console.log("selected radio: ", selectedRadio);
		if (selectedRadio.length > 0) {
			validForm = true;
		};
		return validForm;
	},
    checkCurrentFormIsValid: function() {
        var validForm = true;
		var self = this;
		$(this.getCurrentRequiredFields()).each(function() {
            if ($(this).val() == "" || $(this).val() == '- Choose -') { 
				validForm = false;
            }
        });

		if (this.currentStage == "step1" || this.currentStage == "step2") {
			if (!this.categoryFieldsValid) {
				validForm = false;	
			};
		}

        $(this.getCurrentFieldsToValidate()).each(function() {
            if ($(this).hasClass("invalidField")) {
                validForm = false;
            }
        });
        return validForm;
    },
	setAddingReview: function(addingReviewVal) {
		if (addingReviewVal == true) {
			this.addingReview = true;
		}
	},
	processReview: function() {
		if (this.addingReview == true) {
			this.serializeFormData();
			this.submitReviewData();
		} else {
            this.switchStage("uploadPhoto", false);
		}
	},
	processForm: function() {
		if (this.addingReview == true) {
			this.serializeFormData();
			this.submitNewPhoto();
		} else {
			this.serializeFormData();
			this.submitFormData();
		}
	},
    submitFormData: function() {

        if (this.allowSubmission == true) // prevent hyperactive users from clicking the Send button over and over and submitting duplicate records.  Added per a defect
        {
            this.allowSubmission = false;
            this._super();
            var self = this;
            var output = {};
            this.disableCurrentContinueButton();
            jQuery.each(this.getFormData(), function(key, value) {
                key = key.replace("Optional", "");
                if ((key != "Review") && (key != "Rating") && (key != "Headline")) {
                    output[key] = value;
                }
            });
            var photoKey = $("#flash-user-id input").val();

            output.photoKey = $("#flash-user-id input").val();
			output.SubCategories = this.serializeCategoryFields();
            console.log("output is: ", output);
            console.log("photo key is", photoKey);
            var review = this.getIndividualFormData("Review");
            var rating = parseInt(this.getIndividualFormData("Rating"),10);
            var headline = this.getIndividualFormData("Headline");
            var jsonBusinessObject = JSON.stringify(output); 
			console.log(jsonBusinessObject);
            WagWorld.Web.AjaxUtility.AddSpot(jsonBusinessObject, review, rating, headline, photoKey, function(result) {
                console.log(result);
                self.checkResult(result.value.Pass, result.value.Reason, result.value.AuxiliaryInt, result.value.AuxiliaryNumber);
            });
        }
    },
	submitReviewData: function() {
        if (this.allowSubmission == true) // prevent hyperactive users from clicking the Send button over and over and submitting duplicate records.  Added per a defect
        {
            this.allowSubmission = false;
	        var self = this;
	        var id = this.selectedSpotId;
	        var headline = this.getIndividualFormData('Headline');
	        var body = this.getIndividualFormData('Review');
	        var rating = parseInt(this.getIndividualFormData('Rating'),10);
	        console.log(this.getFormData());
	        WagWorld.Web.AjaxUtility.AddBusinessReview(id, headline, body, rating, function(result) {
                console.log(result);
		    });
		}
	},
	setBusinessId: function() {
        var spotId = this.selectedSpotId;
		var flashvars = $('param[name="flashvar"]').attr("value");
		$("#FlashBusinessId").attr("value", spotId);
	},
	submitNewPhoto: function() {
		var self = this;
		var idNum = parseInt($("#FlashBusinessId").val(),10);
		console.log("id = " + idNum);
		WagWorld.Web.AjaxUtility.ConfirmPhotoAdd(idNum, function(result) {
			console.log("add photo result: " + result);
			self.checkResult(result.value.Pass, result.value.Reason, result.value.AuxiliaryInt, self.selectedSpotId);
		});
	},
    checkResult: function(pass, msg, stageNum, idNum) {
        this.allowSubmission = true;
        if (pass == true) {
            if (msg == "promotion" || msg == " promotion") {
                this.close();
                $(document).trigger("promotion.open", [0, "Spot"]);
            }else if ($("li.other-category #Other").get(0).checked) {
				this.showOtherThankYou();
            }else {
                this.showThankYou(idNum);	
			}
        } else {
            if (msg == "UserNotAuthenticated") {
                this.close();
                $(document).trigger("login.open");
            } else {
                this.redisplayFormWithMessage(msg, stageNum);
            }
        }
    },
    repopulate: function(stageNum) {
        var self = this;
        jQuery.ajax({
            type: "GET",
            url: self.getSnippetPath(),
            data: self.getParams(),
            cache: false,
            success: function(data, textStatus) {
                $(self.getModalDiv()).html(data);
                $(self.getModalDiv()).dialog('open');
				self.embedPhotoSwf();
                self.addModalListeners("step1");
            },
            dataType: "html"
        });
    },
    showThankYou: function(idNum) {
        this.setTitle("Thank You");
        var params = {};
        params.ph = 2;
        params.id = idNum;
        this.setParams(params);
        this.populate();
    },
    showOtherThankYou: function() {
        this.setTitle("Thank You!");
        var params = {};
        params.ph = 3;
        this.setParams(params);
        this.populate();
    },
    redisplayFormWithMessage: function(message, stageNum) {
        var params = {};
        params.ph = 1;
        params.message = message;
        this.setParams(params);
        this.repopulate(stageNum);
    },
    revertToInitialState: function() {
        this._super();
        this.switchStage("step1", true);
    },

	serializeCategoryFields: function() {
		var checkboxGroupsClass = this.categoryFieldSelector + " " + this.categoryFieldsetsParameters.checkboxGroupSelector;
		var radioGroupsClass = this.categoryFieldSelector + " " + this.categoryFieldsetsParameters.radioGroupSelector;
		var questionKey = this.categoryFieldsetsParameters.questionKey;
		var answerKey = this.categoryFieldsetsParameters.answerKey;
		var self = this;
		
		var SubCategories = [];
		$(checkboxGroupsClass).each(function() {
			//Takes checkbox question ids and inserts them as integers into the 
			//checkboxQuestions array as a property on a new unique object
			SubCategory = {};
			var questionStr = $(this).attr("id").replace(questionKey,"");
			SubCategory.FieldID = parseInt(questionStr,10);
			var selectedBoxes = "#" + questionKey + SubCategory.FieldID + "> li > input:checked";
			if ($(selectedBoxes).length > 0) {
				SubCategories.push(SubCategory);	
			}
		});
		
		jQuery.each(SubCategories, function() {
			var subcatSelf = this;
			var serializedCheckboxes = $(checkboxGroupsClass + " input").serializeArray();
			subcatSelf.ValueID = [];
			jQuery.each(serializedCheckboxes, function() {
				//Pulls selected checkboxes from individual checkbox object and
				//adds it as a property to its question object
				var selectorArray = "#" + questionKey + subcatSelf.FieldID + "> li > #" + this.name;
	            if (this.value == "on" && $(selectorArray).length > 0 ) {
					//Finds answer value based off the sibling hidden input field
					var hiddenAnswerID = $("#" + this.name + "~ input:hidden").val();
					var answerID = parseInt(hiddenAnswerID,10);
	                (subcatSelf.ValueID).push(answerID);
	            }
	        });
		});
		
		var serializedRadioQuestions = $(radioGroupsClass + " input").serializeArray();
        jQuery.each(serializedRadioQuestions, function() {
		//Takes each radio button objects and moves the name and value into a new
		//SubCategory object
			SubCategory = {};
			var questionStr = (this.name).replace(questionKey,"");
			SubCategory.FieldID = parseInt(questionStr,10);
			SubCategory.ValueID = [];
			var ValueID = parseInt(this.value, 10);
			(SubCategory.ValueID).push(ValueID);
			SubCategories.push(SubCategory);
        });
		
		var serializedSelectQuestions = $(this.categoryFieldsetsParameters.dropdownGroupSelector);
		serializedSelectQuestions.each(function() {
			SubCategory = {};
			var questionStr = $(this).attr('id').replace(questionKey,"");
			SubCategory.FieldID = parseInt(questionStr,10);
			var selectedBoxes = "#" + questionKey + SubCategory.FieldID + " > option:selected";

			SubCategory.ValueID = [];			
			var selectedOptions = $(selectedBoxes);
			var emptyVal = false;
			selectedOptions.each(function() {
				var ValueID = parseInt(($(this).val()), 10);
				if (isNaN(ValueID)) {
					emptyVal = true;
				}
				else {
					(SubCategory.ValueID).push(ValueID);
				}	
			});
			if ($(selectedBoxes).length > 0 && emptyVal == false) {
				SubCategories.push(SubCategory);	
			};
		});
		

		return SubCategories;
	},

    serializeFormData: function() {
        var self = this;
		//Selects all fields to serialize except radio buttons and category dropdowns for category questions
		var nonCategoryRadioFieldsToSerialize = $(this.getFieldsToSerialize()).not(this.categoryFieldsetsParameters.radioGroupSelector + " > li > input, " + this.categoryFieldsetsParameters.dropdownGroupSelector); 
        var serializedData = (nonCategoryRadioFieldsToSerialize).serializeArray();
        jQuery.each(serializedData, function() {
			if (this.value == self.addSpotFieldBehaviors.titleDefaultText || this.value == self.addSpotFieldBehaviors.reviewDefaultText) {
				this.value = "";
			};
            if (this.value != "on") {
                self.setIndividualFormData(this.name, this.value);
            }
        });
        $(this.getModalDiv() + " input[name=Rating]").each(function() {
            if (this.checked) {
                self.setIndividualFormData("Rating", $(this).val());
            }
        });
		
    },
	getCheckDuplicateData: function() {
		var spotName = $("#NameCheckDupe").val();
		var address = $("#Address1CheckDupe").val();
		var city = $("#CityCheckDupe").val();
		var state = $("#StateCheckDupe").val();
		checkDuplicateData = {
			"Name": spotName,
			"Address1": address,
			"City": city,
			"State": state
		};
	},
	storeReturnedSpotData: function(returnedSpotData) {
		var self = this;
		var i = 0;
		console.log("returnedSpotData.length is " + returnedSpotData.length);
		for (i=0; i<returnedSpotData.length; i++) {
			var spotData = {};
			spotData = {
				"BusId": returnedSpotData[i]["BusinessId"],
				"Name": returnedSpotData[i]["Name"],
				"Address1": returnedSpotData[i]["Address1"],
				"Address2": returnedSpotData[i]["Address2"],
				"City": returnedSpotData[i]["City"],
				"State": returnedSpotData[i]["State"],
				"Zip": returnedSpotData[i]["Zip"]
			};
			self.storedSpotData.push(spotData);
		}
	},
	submitCheckDuplicateData: function() {
		var self = this;
		// try to leverage getCheckDuplicateData here
		var spotName = $("#NameCheckDupe").val();
		var address = $("#Address1CheckDupe").val();
		var city = $("#CityCheckDupe").val();
		var state = $("#StateCheckDupe").val();
		WagWorld.Web.AjaxUtility.GetPotentialSpotDuplicates(spotName, address, city, state, function(result) {
			var returnedSpotData = result.value;
			if (returnedSpotData.length < 1) {
				console.log("no duplicate found");
				self.getCheckDuplicateData();
				self.switchStage("noDuplicate", true);
				self.goToNextStage();
			} else {
				console.log("duplicate found");
				self.storeReturnedSpotData(returnedSpotData);
				self.switchStage("foundDuplicate", true);
				self.goToNextStage();
			}
		});
	},
	getStoredSpotData: function() {
		// re-write this function in jQuery
		console.log("getting stored spot data");
		var spotList = document.getElementById("returned-duplicates");
		for (var i=0; i < this.storedSpotData.length; i++) {
			var spotItem = document.createElement("li");
			var spotName = document.createElement("strong");
			spotName.appendChild(document.createTextNode(this.storedSpotData[i].Name));
			spotItem.setAttribute("id", this.storedSpotData[i].BusId);
			spotItem.appendChild(spotName);
			spotItem.appendChild(document.createElement("br"));
			spotItem.appendChild(document.createTextNode(this.storedSpotData[i].Address1));
			spotItem.appendChild(document.createElement("br"));
			spotItem.appendChild(document.createTextNode(this.storedSpotData[i].City));
			spotItem.appendChild(document.createTextNode(", "));
			spotItem.appendChild(document.createTextNode(this.storedSpotData[i].State));
			spotItem.appendChild(document.createTextNode(" "));
			spotItem.appendChild(document.createTextNode(this.storedSpotData[i].Zip));
			spotList.appendChild(spotItem);
		}
	},
	duplicateSpots: function() {
		var self = this;
		this.getStoredSpotData();
		var returnedDuplicates = $("#returned-duplicates li").length;
		if (returnedDuplicates == 1) {
			$("fieldset#add-spot-duplicate-spots p strong").text("Is this the Spot you're adding?");
		} else {
			$("fieldset#add-spot-duplicate-spots p strong").text("Is your Spot one of these?");
		};
		$("#returned-duplicates li").mouseover(function() {
	        $(this).addClass("hover");
	    });
		$("#returned-duplicates li").mouseout(function() {
	        $(this).removeClass("hover");
	    });
		$("#returned-duplicates li").click(function() {
			$(this).addClass("selected");
			$("#returned-duplicates li").not(this).removeClass("selected");
			self.selectedSpotId = $(this).attr("id");
			self.enableCurrentContinueButton();
		});
		$(".not-shown").click(function() {
			self.getCheckDuplicateData();
			self.switchStage("noDuplicate", true);
			self.goToNextStage();
		});
	},
	handleCheckDuplicateData: function() {
        this.radioButtonListeners();
		$("input#Name").val(checkDuplicateData.Name);
		$("input#Address1").val(checkDuplicateData.Address1);
		$("input#City").val(checkDuplicateData.City);
		$("select#State").val(checkDuplicateData.State);
	}
});

