﻿/// <reference path="jquery-1.3.2-vsdoc2.js"/>

// init app
$(function()
{
    bindEventHandlers();
    getLocationStates("locationState");
    getAllStates("customerState");
});

function bindEventHandlers()
{
    populateTimeOfVisitSelectBox();

    $("#dateOfVisit").datepick({ defaultDate: 0, showDefault: true });
    $("#btnStep3Back").click(function() { loadStep(2); });
    $("#btnStep4Back").click(function() { loadStep(3); });
    $("#btnStep5Back").click(function() { loadStep(4); });

    $("#btnStep2Next").click(function()
    {
        if ($("#dateOfVisit").val() == "")
        {
            $("#dateOfVisit").focus();
            return;
        }

        getLocations($("#locationState").val(), $("input[name=serviceType]:checked").val());

        submitStep2(
            $("#locationState").val(),
            $("input[name=serviceType]:checked").val(),
            $("#dateOfVisit").val(),
            $("#hourOfVisit").val(),
            $("#minuteOfVisit").val(),
            $("#amPmOfVisit").val()
        );

        $("#chosenStateName").html($("#locationState :selected").text());

        loadStep(3);
    });

    $("#btnStep4Next").click(function()
    {
        var stepValidated = validateStep4(
            $("#firstName").val(),
            $("#lastName").val(),
            $("#phone").val(),
            $("#zip").val(),
            $("#email").val(),
            (($('#iAgree:checked').val() != null) ? "true" : "false")
        );

        if (stepValidated)
        {
            submitStep4(
                $("#firstName").val(),
                $("#lastName").val(),
                $("#address").val(),
                $("#city").val(),
                $("#customerState").val(),
                $("#zip").val(),
                $("#phone").val(),
                $("#email").val(),
                (($('#iAgree:checked').val() != null) ? "true" : "false")
            );

            loadStep(5);
        }
    });

    $("#btnStep5Next").click(function()
    {
        var stepValidated = validateStep5(
            $("input[name=experience]:checked").val(),
            $("input[name=overallValue]:checked").val(),
            $("input[name=willReturn]:checked").val(),
            $("input[name=recommend]:checked").val(),
            $("input[name=timeliness]:checked").val(),
            $("input[name=cleanliness]:checked").val(),
            $("input[name=foodTemp]:checked").val(),
            $("input[name=freshness]:checked").val(),
            $("input[name=taste]:checked").val()
        );

        if (stepValidated)
        {
            submitStep5(
                $("input[name=experience]:checked").val(),
                $("input[name=overallValue]:checked").val(),
                $("input[name=willReturn]:checked").val(),
                $("input[name=recommend]:checked").val(),
                $("input[name=timeliness]:checked").val(),
                $("input[name=cleanliness]:checked").val(),
                $("input[name=foodTemp]:checked").val(),
                $("input[name=freshness]:checked").val(),
                $("input[name=taste]:checked").val(),
                $("#comments").val()
            );
        }
    });
}

function populateTimeOfVisitSelectBox()
{
    for (var i = 1; i < 13; i++)
    {
        $('#hourOfVisit').append($("<option></option>").attr("value", i.toString()).text(i.toString()));
        
        if (i == 12)
            $('#hourOfVisit :last-child').attr("selected", "selected");
    }
    
    for (var i = 0; i < 60; i += 15)
    {
        if (i.toString().length == 1)
            min = "0" + i;
        else
            min = i;

        $('#minuteOfVisit').append($("<option></option>").attr("value", min).text(min));
    }

    $('#amPmOfVisit').append($("<option></option>").attr("value", "AM").text("AM"));
    $('#amPmOfVisit').append($("<option></option>").attr("value", "PM").text("PM").attr("selected", "selected"));
}

function loadStep(stepNumber)
{
    for (var i = 1; i < 6; i++)
        $("#step" + i).css("display", "none");

    $("#step" + stepNumber).css("display", "block");
}

function getLocationStates(ddlId)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/GetLocationStates",
        data: "{}",
        dataType: "json",
        success: function(data) { parseStatesForDDL(data, ddlId); },
        error: function(req, msg, err) { alert(msg); }
    });
}

function getAllStates(ddlId)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/GetAllStates",
        data: "{}",
        dataType: "json",
        success: function(data) { parseStatesForDDL(data, ddlId); },
        error: function(req, msg, err) { alert(msg); }
    });
}

function parseStatesForDDL(data, ddlId)
{
    var html = "";

    $.each(data.d, function(index, state) {
        html += "<option value='" + state.Abbr + "'>" + state.Name + "</option>";
    });

    $("#" + ddlId).html(html);
}

function getLocations(stateAbbr, serviceType)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/GetLocations",
        data: "{stateAbbr:'" + stateAbbr + "', serviceType:'" + serviceType + "'}",
        dataType: "json",
        success: function(data) { parseLocations(data); },
        error: function(req, msg, err) { alert(msg); }
    });
}

function parseLocations(data)
{
    var html = "";

    $.each(data.d, function(index, loc) {

        //console.log("lawson: " + loc.Lawson + " / resturant: " + loc.Restaurant);
        var resturantID = "";

        if (loc.Lawson != "")
            resturantID = loc.Lawson;
        else if (loc.Resturant != "")
            resturantID = loc.Restaurant;
        

        var js =
            "javascript: " +
            "submitStep3(" + loc.LocationId + ", \"" + ((resturantID != "") ? resturantID + ", " : "") + loc.Address + ", " + loc.City + ", " + loc.State + " " + loc.Zip + "\"); " +
            "loadStep(4); " +
            "selectCustomerState();";

        html +=
            "<tr><td>" +
            "<a href='" + js + "'>" + loc.City + ", " + loc.State + " &nbsp;" + loc.Zip + "</a><br />" +
            loc.Address + "<br />" +
            loc.Phone + "" +
            "</td></tr>";
    });

    $("#locations").html("<table>" + html + "</table>");
}

function selectCustomerState()
{
    $("#customerState").val($("#locationState").val());
}

function submitStep2(stateAbbr, serviceType, dateOfVisit, hourOfVisit, minuteOfVisit, amPmOfVisit)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/SubmitStep2",
        data: "{stateAbbr:'" + stateAbbr + "', serviceType:'" + serviceType + "', dateOfVisit:'" + dateOfVisit + "', hourOfVisit:'" + hourOfVisit + "', minuteOfVisit:'" + minuteOfVisit + "', amPmOfVisit:'" + amPmOfVisit + "'}",
        dataType: "json",
        success: function(data) { null; },
        error: function(req, msg, err) { alert(msg); }
    });
}

function submitStep3(locationId, locationDesc)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/SubmitStep3",
        data: "{locationId:'" + locationId + "', locationDesc:'" + locationDesc + "'}",
        dataType: "json",
        success: function(data) { $("#firstName").focus(); },
        error: function(req, msg, err) { alert(msg); }
    });
}

function validateStep4(firstName, lastName, phone, zip, email, iAgree)
{
    // validate
    var errorText = "";

    if (firstName == "")
        errorText += "* First name is required\n";

    if (lastName == "")
        errorText += "* Last name is required\n";

    if (phone == "")
        errorText += "* Phone number is required\n";
    else if (isPhoneNumber(phone) == false)
        errorText += "* Phone number is invalid\n";
    else
        $("#phone").val(formatPhoneNumber(phone));

    if (zip != null && zip.length > 0 && isZipCode(zip) == false)
        errorText += "* Zip code is invalid\n";

    if (email == "")
        errorText += "* Email address is required\n";
    else if (isEmail(email) == false)
        errorText += "* Email address is invalid\n";

    if (iAgree == "false")
        errorText += "* You must check \"I Agree\"\n";

    if (errorText.length > 0)
    {
        errorText = "There are one or more problems with the form you must correct before you can continue:\n\n" + errorText;
        alert(errorText);
        return false;
    }
    else
    {
        return true;
    }
}

function submitStep4(firstName, lastName, address, city, customerState, zip, phone, email, iAgree)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/SubmitStep4",
        data:
            "{" +
                "firstName:'" + escChars(firstName) + "', " +
                "lastName:'" + escChars(lastName) + "', " +
                "address:'" + escChars(address) + "', " +
                "city:'" + escChars(city) + "', " +
                "customerState:'" + escChars(customerState) + "', " +
                "zip:'" + escChars(zip) + "', " +
                "phone:'" + escChars(phone) + "', " +
                "email:'" + escChars(email) + "', " +
                "iAgree:'" + iAgree + "'" +
            "}",
        dataType: "json",
        success: function(data) { null; },
        error: function(req, msg, err) { alert(msg); }
    });
}

function validateStep5(experience, overallValue, willReturn, recommend, timeliness, cleanliness, foodTemp, freshness, taste)
{
    var errorText = "";

    if (experience == null)
        errorText += "* Please rate your experience\n";

    if (overallValue == null)
        errorText += "* Please rate our overall value\n";

    if (willReturn == null)
        errorText += "* Please rate your likeliness to return\n";

    if (recommend == null)
        errorText += "* Please rate your likeliness to recommend us\n";

    if (timeliness == null)
        errorText += "* Please rate our timeliness\n";

    if (cleanliness == null)
        errorText += "* Please rate our cleanliness\n";

    if (foodTemp == null)
        errorText += "* Please rate our food temperature\n";

    if (freshness == null)
        errorText += "* Please rate our food freshness\n";

    if (taste == null)
        errorText += "* Please rate our food taste\n";

    if (errorText.length > 0)
    {
        errorText = "There are one or more problems with the form you must correct before you can continue:\n\n" + errorText;
        alert(errorText);
        return false;
    }
    else
    {
        return true;
    }
    
    return true;
}

function submitStep5(experience, overallValue, willReturn, recommend, timeliness, cleanliness, foodTemp, freshness, taste, comments)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "comment_form_service.asmx/SubmitStep5",
        data:
            "{" +
                "experience:'" + experience + "', " +
                "overallValue:'" + overallValue + "', " +
                "willReturn:'" + willReturn + "', " +
                "recommend:'" + recommend + "', " +
                "timeliness:'" + timeliness + "', " +
                "cleanliness:'" + cleanliness + "', " +
                "foodTemp:'" + foodTemp + "', " +
                "freshness:'" + freshness + "', " +
                "taste:'" + taste + "', " +
                "comments:'" + escChars(comments) + "'" +
            "}",
        dataType: "json",
        success: function(data) { window.location = "thanks.html"; },
        error: function(req, msg, err) { alert(msg); }
    });
}


// quick and dirty email validation
function isEmail(email)
{
    var regex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return regex.test(email);
}

// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(phone)
{
    var regex = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
    return regex.test(phone);
}

function formatPhoneNumber(phone)
{
    var raw = phone.replace(/ /g, "").replace(/\(/g, "").replace(/\)/g, "").replace(/-/g, "");
    return "(" + raw.substring(0, 3) + ") " + raw.substring(3, 6) + "-" + raw.substring(6);
}

function isZipCode(zip)
{
    var regex = /^\d{5}$|^\d{5}-\d{4}$/;
    return regex.test(zip);
}

function escChars(str) 
{
    return str.replace(/'/g, "\\'");
}