﻿var TIME_DELAY = 500;
var PADDING_BOTTOM = 140;
$(document).keypress(function(event){
    if(event.which === 13){
        if($("#quiz .last").is(":visible")){
            if($("#loginPass").val() && $("#loginEmail").val()){
                FlavorMatch.authenicate();
            } else {
                FlavorMatch.save();
            }
            return false;
        }
    }
});
$(document).ready(function(){
    if(document.location.href.match(/.aspx/ig) === null){
	    FlavorMatch.isHomePage = true;
    } else {
        if(document.location.href.match(/default/ig) !== null){
			FlavorMatch.isHomePage = true;
		} else {
	        FlavorMatch.isHomePage = false;
		}
    }

	Bookmark.load();
    if($(".welcome").length > 0){
        $("#quiz .last").remove();
    }
    $("#login").click(function(){
        FlavorMatch.authenicate();
    });
    $("#register").click(function(){
        FlavorMatch.save();
    });
    
    $("#quiz a").hover(function(){
       $(this).children(".imgWrap").css("border-color", "#faa605");
    }, function(){
        $(this).children(".imgWrap").css("border-color", "#e0e2d4");
    });
    $(".panel a").click(function(event){
        if($(this).parents("#flavorResults").length === 0 ) {
            if($(this).attr("class") !== "lostPass" ){
                event.preventDefault();

                var whatClicked = $(this).attr("class");
                var panel = $(this).parents(".panel");
                var panelClasses = panel.attr("class");
                var panelType = "";
                if(panelClasses.match(/diggerType/gi) !== null || panelClasses.match(/cuisines/gi)){
                    panelType = "preference";
                } else if(panelClasses.match(/question/gi) !== null ){
                    panelType = "question";
                }
                var preference = panel.attr("id");
                
                if(whatClicked === "back"){
                    FlavorMatch.back(panel);
                } else if(panelType === "preference"){
                    var goNext = true;
                    
                    if(FlavorMatch.preferences.firstDigger === whatClicked){
                        goNext = false;
                    } else if(FlavorMatch.preferences.firstCuisine === whatClicked ){
                        goNext = false;
                    }
                    if(goNext){
                        FlavorMatch.savePreference(whatClicked, preference);
                        FlavorMatch.next(panel);
                    }
               } else if(panelType === "question"){
                    FlavorMatch.saveAnswer($(this).attr("choiceid"), panel.attr("questionid"));
                    FlavorMatch.next(panel);
               }
           }
        }
    });
});

var Bookmark = {
    currentQuestion : "",
    save : function(panel){
        var panelId = panel.attr("id");
        if(panelId){
            Bookmark.currentQuestion = panelId; 
        } else {
            Bookmark.currentQuestion = panel.attr("questionid");
        }
        Cookie.create("preferences", JSON.stringify(FlavorMatch.preferences), 0.4);
        Cookie.create("bookmark", Bookmark.currentQuestion, 0.4);
        Cookie.create("answers", JSON.stringify(FlavorMatch.answers), 0.4);
    },
    load : function(){
        if( Cookie.read("preferences")){
            FlavorMatch.preferences = JSON.parse(Cookie.read("preferences"));
        }
        if( Cookie.read("answers")){
            FlavorMatch.answers = JSON.parse(Cookie.read("answers"));
        }
        Bookmark.currentQuestion = Cookie.read("bookmark");
        
        if(Bookmark.currentQuestion){
            if(Bookmark.currentQuestion.match(/^\d+$/) !== null){
                $(".panel").hide();
                $(".panel[questionid=" + Bookmark.currentQuestion + "]").show();
            } else if (Bookmark.currentQuestion.match(/lastQuestion/ig) !== null) {
                $(".panel").hide();
                
                if(FlavorMatch.isHomePage){
                    $("#quiz").hide();
                } else {
                    if($("#quiz .last").length === 0){
                        Bookmark.loadFlavorResults();
                    }
                    $("#quiz .last").css("border","none");
                    if(document,location.href.match(/complete=true/ig) !== null){ 
                        $(".header .green").html("Complete");
                        $(".header .orange").html("your FlavorMatch Profile");
                    } else {
                        $(".header .green").html("Sign up now");

                        if(document.location.href.match(/registration.aspx/ig) !== null){
                            $(".header .orange").html("by creating your FlavorMatch Profile");
                        } 
                        
                        



//                        if(document.location.href.match(/registration.aspx/ig) == null){
//                            $(".header .orange").html("to complete your FlavorMatch Profile");
//                        }
//                         else {
//                            $(".header .orange").html("by creating your FlavorMatch Profile");
//                        }
                    }
                    $(".subText").html("It's fast and easy.  Find out who you matched up with and start getting better restaurant recommendations now!");
                    $("#quiz .last").show();
                }
            } else if(Bookmark.currentQuestion === "flavorResults"){
                if(FlavorMatch.isHomePage){
                    $("#quiz").hide();
                } else {
                    $(".panel").hide();
                    Bookmark.loadFlavorResults();
                    $("#quiz").css("margin-bottom", "50px");
                }
           } else {
                $(".panel").hide();
                $("#" + Bookmark.currentQuestion).show();
           }
        } else {
            $("#firstDigger").show();
        }
        $("#quiz").height($(".panel:visible").height() + PADDING_BOTTOM);

    },
    loadFlavorResults : function(){
        Navigationbar.displayLogin("! Welcome!");
        $(".header .green").html("Your");
        $(".header .orange").html("FlavorMatches");
        $(".subText").html("The people with the highest FlavorMatch Scores are listed below to help you find better restaurant recommendations.  Your FlavorMatch results will improve as you rate more restaurants and become an active member of the FoodDigger community.");
        if(Cookie.read("fmResult0")){
            for(var i=0;i<6;i++){
                var result = Cookie.read("fmResult" + i);
                if(result){
                    $("#flavorResults").append(result);
                }
            }
        } else{
            $(".panel").hide();
            $("#flavorResults").show();
            $("#flavorResults").append("<div id=\"loading\"><h1><span class=\"green\">Calculating Your </span><span class=\"orange\">FlavorMatch</span></h1></div>");
            FlavorMatchService.save(FlavorMatch.user,FlavorMatch.UIDtoMatch, FlavorMatch.preferences, FlavorMatch.answers,FlavorMatch.saveCallback);
        }
        $("#flavorResults").show();

    }
};
var FlavorMatch  = {
    preferences : new Object(),
    user : new Object(),
    answers : new Array(),
    savePreference : function(whatClicked, preference){
        FlavorMatch.preferences[preference] = whatClicked;
    },
    authenicate : function(){
        $(".error").remove();
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(reg.test($("#loginEmail").val()) === false) {
            $("#login").after("<div class=\"error\">Please enter a valid email address.</div>");
            return false;
        }
        User.authenticate($("#loginEmail").val(), $("#loginPass").val(), false, function(obj){
            var data = JSON.parse(obj);
            if(data.AuthenticateResult.Status === 0){
                if(data.AuthenticateResult.Message === "LOGIN_FAIL"){
                    $("#login").after("<div class=\"error\">Login Incorrect</div>");
                } else {
                    Tracking.track("flavorMatch/Signin");
                    FlavorMatch.user.emailaddress = $("#loginEmail").val();
                    $(".question").hide();
                    $("#flavorResults").show();
                    $("#flavorResults").append("<div id=\"loading\"><h1><span class=\"green\">Calculating Your </span><span class=\"orange\">FlavorMatch</span></h1></div>");
                    FlavorMatchService.save(FlavorMatch.user, FlavorMatch.UIDtoMatch,  FlavorMatch.preferences, FlavorMatch.answers,FlavorMatch.saveCallback);
                }
            }
        });
    },
    saveAnswer : function(choiceId, questionId){
        var answerObj = new Object();
        answerObj.ChoiceID = choiceId;
        answerObj.QuestionID = questionId;
        FlavorMatch.answers.push(answerObj);
    },
    isHomePage : false,
    nextPanel : null,
    next : function(panel){
        panel.hide();
        var nextpanel = $(panel.next());
        var nextid = nextpanel.attr("id");
        FlavorMatch.initPanel(nextpanel);
        
        FlavorMatch.nextPanel = nextpanel;
        var stop = false;
        if(nextpanel.is(".last")){

            if(FlavorMatch.isHomePage){
                document.location.href = "flavormatch.aspx";
            } else {
                $("#quiz").height(nextpanel.height() + PADDING_BOTTOM);
                setTimeout('FlavorMatch.nextPanel.show();',TIME_DELAY);
            }
        } else if( nextpanel.is("#flavorResults")){
            if(FlavorMatch.isHomePage){
                document.location.href = "flavormatch.aspx";
            } else {
                $("#flavorResults").show();
                $("#quiz").height(nextpanel.height() + PADDING_BOTTOM);
                $("#flavorResults").append("<div id=\"loading\"><h1><span class=\"green\">Calculating Your </span><span class=\"orange\">FlavorMatch</span></h1></div>");
                FlavorMatchService.save(FlavorMatch.user,FlavorMatch.UIDtoMatch, FlavorMatch.preferences, FlavorMatch.answers,FlavorMatch.saveCallback);
            }
        } else {
            $("#quiz").height(nextpanel.height() + PADDING_BOTTOM);
            setTimeout('FlavorMatch.nextPanel.show();',TIME_DELAY);
        }

        //nextpanel.show();        
    },
    back : function(panel){
        $(".diggerType .imgWrap").css("border-color", "#e0e2d4");
        $(".diggerType a").css({"opacity" : 1, "cursor" : "pointer"});

        $(".cuisines .imgWrap").css("border-color", "#e0e2d4");
        $(".cuisines a").css({"opacity" : 1, "cursor" : "pointer"});
        $("#quiz a").hover(function(){
           $(this).children(".imgWrap").css("border-color", "#faa605");
        }, function(){
            $(this).children(".imgWrap").css("border-color", "#e0e2d4");
        });
        panel.hide();
        var prevPanel = $(panel.prev());
        if(prevPanel.attr("id") === "firstDigger"){
            FlavorMatch.preferences.firstDigger = "";
        }
        if(prevPanel.attr("id") === "firstCuisine"){
            FlavorMatch.preferences.firstCuisine = "";
        }
        prevPanel.show(); 
       $("#quiz").height($(".panel:visible").height() + PADDING_BOTTOM);

        FlavorMatch.initPanel(prevPanel);
            
    },
    initPanel : function(panel){
        var panelID = panel.attr("id");
        Bookmark.save(panel);
        if(panel.attr("questionid")){
            if(panel.attr("questionid") === "18"){
                Tracking.track("/flavorMatch/BoldZesty"); 
            }
        }
        if(panelID === "secondDigger"){
            $("." + FlavorMatch.preferences.firstDigger + " .imgWrap").css("border-color", "#faa605");
            $("." + FlavorMatch.preferences.firstDigger).css({"opacity" : 0.3, "cursor" : "default"});
            $("." + FlavorMatch.preferences.firstDigger).unbind("mouseleave");
            $("." + FlavorMatch.preferences.firstDigger).mouseleave(function(){$("." + FlavorMatch.firstCuisine).css("border-color", "#faa605");});

        } else if(panelID === "secondCuisine"){
            $("." + FlavorMatch.preferences.firstCuisine + " .imgWrap").css("border-color", "#faa605");
            $("." + FlavorMatch.preferences.firstCuisine).css({"opacity" : 0.3, "cursor" : "default"});
            $("." + FlavorMatch.preferences.firstCuisine).unbind("mouseleave");
            $("." + FlavorMatch.preferences.firstCuisine).mouseleave(function(){$("." + FlavorMatch.firstCuisine).css("border-color", "#faa605");});
        }
        if(document,location.href.match(/registration.aspx/ig) !== null) {
            $(".subText").html("It's fast and easy.  Find out who you matched up with and start getting better restaurant recommendations now!");
            $(".header .green").html("Sign up now");
            $(".header .orange").html("by creating your FlavorMatch Profile");
        } else if(document,location.href.match(/complete=true/ig) !== null){ 
            $(".header .green").html("Complete");
            $(".header .orange").html("your FlavorMatch Profile");
        } else if($("#quiz .last").is(":visible")){
            Tracking.track("/flavormatch/registration"); 
            $("#quiz .last").css("border", "none");
            $(".subText").html("It's fast and easy.  Find out who you matched up with and start getting better restaurant recommendations now!");
            $(".header .green").html("Sign up now");
            $(".header .orange").html("to complete your FlavorMatch Profile");
        } else {
            
            if(document.location.href.match(/registration.aspx/ig) !== null){
               $(".header .green").html("Sign up now");
               $(".subText").html("It's fast and easy.  Find out who you matched up with and start getting better restaurant recommendations now!");
                $(".header .orange").html("by creating your FlavorMatch Profile");
            } 
//            else {
//                $(".header .orange").html("to complete your FlavorMatch Profile");
//            }
        }
    },
    save : function(){
        $(".error").remove();

        if(FlavorMatch.validateRegister()){
            Tracking.track("/flavorMatch/NewSignUp");
            FlavorMatch.user.username = $("#username").val();                  
            FlavorMatch.user.Zip = $("#zipCode").val();                  
            FlavorMatch.user.emailaddress = $("#emailaddress").val();                  
            FlavorMatch.user.loginpassword = $("#registerpassword").val();                  

            $(".question").hide();
            $("#flavorResults").show();
            $("#flavorResults").append("<div id=\"loading\"><h1><span class=\"green\">Calculating Your </span><span class=\"orange\">FlavorMatch</span></h1></div>");
            FlavorMatchService.save(FlavorMatch.user,FlavorMatch.UIDtoMatch, FlavorMatch.preferences, FlavorMatch.answers,FlavorMatch.saveCallback);
        }
    },
    validateRegister : function(){
        var retVal = true;
        $(".error").remove();

        if(!$("#username").val()){
            FlavorMatch.appendError($("#username"), "Please enter a user name.");
            retVal = false;
        }
        if(!$("#zipCode").val()){
            FlavorMatch.appendError($("#zipCode"), "Please enter a zip code.");
            retVal = false;
        }
        if(!$("#emailaddress").val()){
            FlavorMatch.appendError($("#emailaddress"), "Please enter an email address");
            retVal = false;
        }
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(reg.test($("#emailaddress").val()) === false) {
            FlavorMatch.appendError($("#emailaddress"), "Invalid Email Address");
            return false;
       }
        if(!$("#registerpassword").val()){
            FlavorMatch.appendError($("#registerpassword"), "Please enter a password");
             retVal = false;
       }
        if($("#registerpassword").val() !== $("#confirmPass").val()){
            FlavorMatch.appendError($("#confirmPass"), "Passwords do not match.");
            retVal = false;
        }
        if(!$("#confirmPass").val()){
            FlavorMatch.appendError($("#confirmPass"), "Please confirm your password");
            retVal = false;
        }
        return retVal;
    },
    appendError : function(element, errorMessage){
        var parent = $(element.parent());
        parent.prepend("<div class=\"error\">" + errorMessage + "</div>");
    },
    saveCallback : function(obj){
        var data = JSON.parse(obj);
        if(data.SaveFlavorMatchResult.Status === 0){
            if(document.location.href.match("restID=") !== null){
                var reQS = new RegExp("restID=([^&$]*)", "i" );
                var offset = location.search.search( reQS );
                var restID = ( offset >= 0 ) ? RegExp.$1 : null;
                if(restID !== null){
                    document.location.href = "RestaurantDetail.aspx?id=" + restID;
                    return false;
                }
            } else {
                Tracking.track("/flavormatch/flavorResults"); 
                if($(".welcome").length === 0){
                    Navigationbar.displayLogin(" Welcome!");
                }
                Bookmark.save($("#flavorResults"));
                $(".subText").html("");
                if(data.SaveFlavorMatchResult.Scores.length === 0){
                    $("#flavorResults").append("<div id=\"noResults\"><h1>No Results</h1></div>");
                } else {
                    var count = 0;
                    $.each(data.SaveFlavorMatchResult.Scores, function(){
                        var flavorResult = $("<div class=\"flavorResult\"></div>");
                        if(FlavorMatch.UIDtoMatch === this.UID){
                            flavorResult = $("<div class=\"matchFlavorResult\"></div>");
                        } else {
                            var matchLevel = "high";
                            if(this.Score < 80){
                                matchLevel = "med";
                            }
                            if(this.Score > 95 ){
                                matchLevel = "very high";
                            }
                            flavorResult.append("<a class= \"userProfileLink\" href=\"Profile/PublicProfile.aspx?tab=12&id=" + this.UID + "\">" + this.ProfilePic + "</a>");
                            var flavorMatchBox = $("<div class=\"flavorMatchBox\" title=\"" + this.Score + "\"></div>");
                            flavorMatchBox.append("<label>FlavorMatch With You</label>");
                            flavorMatchBox.append("<span class=\"score\">" + matchLevel + "</span>");
                            flavorMatchBox.append("<a class=\"matchDetails\" href=\"Profile/PublicProfile.aspx?tab=12&id=" + this.UID + "\">" + "See Match Details</a>");
                             
                            flavorResult.append(flavorMatchBox);
                            flavorResult.append("<span class = \"username\">" + this.UserName + "</span>");
                            if(this.IsBlogger){
                                flavorResult.append("<span class = \"isBlogger\">Blogger</span>");
                            }
                            if(this.FavoriteCuisines){
                                flavorResult.append("<span class = \"favCusine\">" + this.FavoriteCuisines + "</span>");
                            }
                            flavorResult.append("<a class = \"numOfReviews\" href=\"Profile/PublicProfile.aspx?id=" + this.UID + "\">" + this.NumOfReviews + " Reviews</a>");
                            if(this.RestaurantID !== 0 ){
                                flavorResult.append("<a class=\"favRestaurant\" href=\"/RestaurantDetail.aspx?id=" + this.RestaurantID + "\">" + this.RestaurantName + "</a>");
                            }
                            Cookie.create("fmResult" + count, "<div class=\"flavorResult\">" + flavorResult.html() + "</div>",0.4);
                            count++;
                            $("#flavorResults").append(flavorResult);
                        }
                        $("#quiz").height($("#flavorResults").height());
                        $("#quiz").css("margin-bottom", "50px");
                    });
                }
                $(".header .green").html("Your");
                $(".header .orange").html("FlavorMatches");
                $(".subText").html("The people with the highest FlavorMatch Scores are listed below to help you find better restaurant recommendations.  Your FlavorMatch results will improve as you rate more restaurants and become an active member of the FoodDigger community.");
	        }
        } else {
            $("#flavorResults").hide();
            $("#quiz .last").show();
            if(data.SaveFlavorMatchResult.Message.match("DuplicateEmail") !== null){
                FlavorMatch.appendError($("#emailaddress"), "Email already exists.");
            }
            if(data.SaveFlavorMatchResult.Message.match("DuplicateUserName") !== null){
                FlavorMatch.appendError($("#username"), "User name already exists.");
            }
        }
        $("#loading").remove();
    }
};
var Cookie = {
    create : function (name,value,days) {
	    if (days) {
		    var date = new Date();
		    date.setTime(date.getTime()+(days*24*60*60*1000));
		    var expires = "; expires="+date.toGMTString();
	    }
	    else var expires = "";
	    value = escape(value);
	    document.cookie = name+"="+value+expires+"; path=/";
    },

    read : function (name) {
	    var nameEQ = name + "=";
	    var ca = document.cookie.split(';');
	    for(var i=0;i < ca.length;i++) {
		    var c = ca[i];
		    while (c.charAt(0)==' ') c = c.substring(1,c.length);
		    if (c.indexOf(nameEQ) === 0) {
		        var value = c.substring(nameEQ.length,c.length);
		        return unescape(value);
		    }
	    }
	    return null;
    }
};

var Tracking = {
    track : function(trackstring){
        if(document.location.href.match(/localhost/ig) === null && document.location.href.match(/fd.chrisk.la/ig) === null){
            pageTracker._trackPageview(trackstring); 
        } 
    }
};

