﻿/// <reference path="jquery-1.3.2.js" />

var secondsElapsed = 0;
var allowFeedback = false;
var rootDir = "~/";

function displayElapsed() {
    secondsElapsed++;
    var tmpDate = new Date(0, 0, 0, 0, 0, secondsElapsed, 0);
    $("#elapsedTimeDisplay").text(displayNum(tmpDate.getMinutes()) + ":" + displayNum(tmpDate.getSeconds()));
}
function loadDonorList(donorArray, listId) {
    /// <summary>
    /// Load the array of donors into the given list box
    /// <summary>
    var htmlList = '';
    $.each(donorArray, function(i, val) {
        if (i > 20) return false;
        htmlList += '<option value="' + i + '"' +
                     (i == 0 ? ' selected' : '') + '>'
                     + val.LastName + ', ' + val.FirstName + ' '
                     + formatPhone(val.HomePhone) + ' - '
                     + val.AddressLine1 + ', ' + val.City + ' ' + val.Zip
                     + '</option>';
    });
    $(listId).html(htmlList);
}
function loadImages() {
    var preload = new Array();
    $(".hover").each(function() {
        s = $(this).attr("src").replace(/\.gif$/, "rollover.gif");
        preload.push(s);
    });

    var img = document.createElement('img');
    $(img).bind('load', function() {
        if (preload[0]) {
            this.src = preload.shift();
        }
    }).trigger('load');
}

function initHover() {
    $(".hover").each(function() {
        if ($(this).attr("src").match(/rollover\.gif$/)) {
            $(this).removeClass("hover");
        }
    });

    $(".hover").hover(
                function() {
                    s = $(this).attr("src").replace(/\.gif$/, "rollover.gif");
                    s = s.replace(/\.png$/, "rollover.png");
                    $(this).attr("src", s);
                },
                function() {
                    s = $(this).attr("src").replace(/rollover\.gif$/, ".gif");
                    s = s.replace(/rollover\.png$/, ".png");
                    $(this).attr("src", s);
                }
            );
    $(".ui-state-default").hover(
	            function() {
	                $(this).addClass("ui-state-hover");
	            },
	            function() {
	                $(this).removeClass("ui-state-hover");
	            }
	        );
    $(".ui-state-default").focus(function() { $(this).addClass("ui-state-focus"); });
    $(".ui-state-default").blur(function() { $(this).removeClass("ui-state-focus"); });
}
function displayNum(numVal) {
    return (numVal > 9 ? numVal.toString() : "0" + numVal.toString());
}

// function taken from http://www.redips.net/javascript/date-validation/
// and then reworked to allow for format like m/d/yyyy
function isDate(txtDate) {
    var objDate;  // date object initialized from the txtDate string
    var mSeconds; // milliseconds from txtDate
   
    // date length should be 8-10 characters
    if (txtDate.length > 10 | txtDate.length < 8) return false;
    var sep1 = txtDate.indexOf("/");
    if (sep1 < 1) return false;
    var sep2 = txtDate.indexOf("/", sep1 + 1);
    if (sep2 < sep1) return false;
    
    // extract day, month and year from the txtDate string
    // subtraction will cast variables to integer implicitly
    var month = txtDate.substring(0, sep1) - 1; // because months in JS start with 0
    var day = txtDate.substring(sep1 + 1, sep2) - 0;
    var year = txtDate.substring(sep2 + 1) - 0;

    // test year range
    if (year < 999 || year > 3000) return false;

    // convert txtDate to the milliseconds
    mSeconds = (new Date(year, month, day)).getTime();

    // set the date object from milliseconds
    objDate = new Date();
    objDate.setTime(mSeconds);

    // if there exists difference then date isn't valid
    if (objDate.getFullYear() != year) return false;
    if (objDate.getMonth() != month) return false;
    if (objDate.getDate() != day) return false;

    // otherwise return true
    return true;
}
function isFieldMissing(fieldid) {
    if ($("#" + fieldid).val().length == 0) {
        $("#" + fieldid + " + span").css("display", "inline");
        return true;
    } else {
        return false;
    }
}
function unFormatPhone(val) {
    if (val != null) {
        if (val.length > 0 && val[0] == "1") val = val.substring(1, val.length);
        return (new String(val)).replace(/[^0-9]/g, "");
    } else {
        return "";
    }
}

function isValidPhone(val) {
    return (unFormatPhone(val).length == 10);
}

function isValidZip(val) {
    if (val != null) {
        var numOnly;
        numOnly = (new String(val)).replace(/[^0-9]/g, "");
        return (numOnly.length == 5);
    }
    else {
        return false;
    }
}

function isValidEmail(fld1, fld2) {
    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    var email1 = $(fld1).val();
    var email2 = $(fld2).val();
    if (email1.length + email2.length > 0) {
        if (email1 != email2) {
            alert("Please verify the email address.");
            $(fld2).focus();
            return false;
        }
        if (!emailRegex.test(email1)) {
            alert("Please enter a valid email address, or leave blank if you do not wish to enter an email.");
            $(fld1).focus();
            return false;
        }
    }
    return true;
}
function etaDisplay(ticketObj, isDsr) {
    if (ticketObj) {
        if (ticketObj.EtaStartString && ticketObj.EtaStartString.length > 0
          && ticketObj.EtaEndString && ticketObj.EtaEndString.length > 0) {
            var ret = "ETA Between " + ticketObj.EtaStartString +
              " And " + ticketObj.EtaEndString;
            if (ticketObj.EtaIsAfterRouteEnd) {
                if (isDsr)
                    ret += " (after route end)";
                else
                    ret = "Scheduled: Pickup time unknown";
            }
            return ret;
        } else {
            return "Scheduled";
        }
    } else {
        return "";
    }
}
function formatPhone(val, ext) {
    if (isValidPhone(val)) {
        var tmp = unFormatPhone(val);
        tmp = "(" + tmp.substr(0, 3) + ") " + tmp.substr(3, 3) + "-" + tmp.substr(6, 4);
        
        if (ext && ext != null && ext.length > 0)
            tmp = tmp + ", ext. " + ext;
            
        return tmp;
    }
    else {
        return val;
    }
}

function formatProperCase(fullText) {
    /// <summary>
    ///  Return text formatted as Proper Case
    /// </summary>
    var result = "";
    
    if (fullText && fullText != null && fullText.length > 0) {
        var words = fullText.split(/[,' \.]/);

        $.each(words, function(i, word) {
            if (word.length >= 1) {
                if (result.length > 0) result += " ";
                result += word.substr(0, 1).toUpperCase();
                result += word.substr(1).toLowerCase();
            }
        });
    }
    return result;
}

function formatFieldProperCase() {
    /// <summary>function to format a field on blur event</summary>
    var tmp = new String($(this).val());
    $(this).val(formatProperCase(tmp));
}

function focusNextInput($parentObj) {
    if ($parentObj && $parentObj.length > 0) {
        var $nxt = $parentObj.nextAll();
        if ($nxt && $nxt.length > 0 && $nxt.find(".cr2tab:visible").length > 0) {
            $nxt.find(".cr2tab:visible").get(0).focus();
            return true;
        } else {
            return focusNextInput($parentObj.parent());
        }
    } else {
        return false;
    }
}
function imposeMaxLength(Object, MaxLen) {
    return (Object.value.length <= MaxLen);
}
function crKeyPress(e) {
    if (e.which == 13) {
        if ($(this).nextAll(".cr2tab:visible").length > 0) {
            $(this).nextAll(".cr2tab:visible").get(0).focus();
            return false;
        } else {
            return !focusNextInput($(this).parent());
        }
    }
}

$(window).bind('load', loadImages);

$(function() {
    $.ajaxSetup({ cache: false });
    window.setInterval("displayElapsed()", 1000);
    initHover();
    $(".propercase").blur(formatFieldProperCase);

    $(".cr2tab").keypress(crKeyPress);

    if (allowFeedback) {
        $("#feedbackDiv a").click(function() { $("#feedbackDialog").dialog("open"); $("#feedbackText").focus(); });
        $("#feedbackDialog").dialog({
            autoOpen: false,
            modal: true,
            title: "Online Donation Site Feedback",
            width: 450,
            buttons: {
                "Send": sendFeedback
            }
        });
    }
});
function setStreetAddress(fld, geocodeObj) {
    /// <summary>Set street address based on geocode result 
    /// while preserving street number. Returns false if street # 
    /// did not match</summary>
    var userAddr = $(fld).val();
    var mk = userAddr.indexOf(" ");
    var streetNo = mk > 0 ? userAddr.substring(0, mk) : "";
    var isSameStreetNo = true;
    var fracNo = "";
    
    // check fractional address
    if (mk > 0 && userAddr.length > (mk + 2)
      && userAddr.substring(mk + 1, mk + 3) == "1/") {
        var mk3 = userAddr.substring(mk + 3, userAddr.length).indexOf(" ");
        if (mk3 >= 0) {
            fracNo = " " + userAddr.substring(mk + 1, mk3 + (mk + 3));
        }
    }
    var mk2 = geocodeObj.street.indexOf(" ");
    
    if (mk2 > 0) {
        if (streetNo != geocodeObj.street.substring(0, mk2)) {
            isSameStreetNo = false;
        }
        $(fld).val(streetNo + fracNo + geocodeObj.street.substring(mk2, geocodeObj.street.length));
    } else {
        $(fld).val(streetNo + fracNo + " " + geocodeObj.street);
    }

    return isSameStreetNo; 
}
function sendFeedback() {
    var msg = $("#feedbackText").val();
    var fbType = $("#feedbackType").val();
    var aid = 0;
    
    if (msg.length == 0) {
        alert("Please enter a message to send.");
        return false;
    }
    msg = "Feedback Type: " + $("#feedbackType :selected").text() + "\r\n\r\n" + 
        "Comments:\r\n" + msg + "\r\n\r\n" +
        "Name: " + $("#feedbackName").val() + "\r\n" +
        "Email: " + $("#feedbackEmail").val() + "\r\n" + 
        "Phone: " + $("#feedbackPhone").val() + "\r\n\r\n" + 
        "Page: " + window.location.pathname + "\r\n" + 
        "Date/Time: " + (new Date()).toString();
    var a = getAuditData();
    var s = "";
   
    if (a) {
        if (a.PageAudit && a.PageAudit.length > 0) {
            msg += "\r\n\r\n---- Donor Details ----\r\n" + a.PageAudit;
        }
        if (a.Arc_id) aid = a.Arc_id;
    }
    $.post(feedbackUrl, {
        msg: msg,
        feedbackType: fbType,
        arcId: aid 
    });
    alert("Thank you for your feedback! Your comments will be reviewed as soon as possible and will help make the donation process better.");
    if (allowFeedback) $("#feedbackDialog").dialog("close");
    $("#feedbackText").val("");
    return true;
}
// find zip dialog plugin
// depends on jquery.ui.dialog
(function($) {
    var zipField;
    var findZipUrl;
    var lastContext;
    $.fn.findZip = function(optionsOrCommand) {
    /// <summary>
    /// Displays a dialog box that allows lookup of zip codes by city
    /// </summary>        
        return this.each(function() {
            if (optionsOrCommand && typeof optionsOrCommand == "object") {
                return initDialog(this, optionsOrCommand);
            } else {
                return $(this).dialog('open');
            }
        });
    };
    function selectZip($dlg) {
        if (zipField) {
            var zip = $("select :selected", $dlg).val();
            if (!zip || zip.length != 5) return false;

            $(zipField).val(zip);
            $($dlg).dialog("close");
            $(zipField).focus();
        }
    }

    function findZipByCity($dlg) {
        var city = $("input:text", $dlg).val();
        if (!city || city.length == 0) return;
        lastContext = $dlg;
        $.getJSON(findZipUrl, { city: city }, findZipByCityCallback);
    }

    function findZipByCityCallback(results) {
        if (results == null || results.length == 0) {
            $("select", lastContext).html("");
        } else {
            var resultsHtml = "";
            $.each(results, function(i, val) {
                resultsHtml += "<option value='" + val.Zip + "'" + (i == 0 ? " selected" : "") + ">" + val.Zip + " - " + val.City + ", " + val.State + "</option>";
            });
            $("select", lastContext).html(resultsHtml);
        }
    }
    function initDialog($obj, options) {
        zipField = options.zipField;
        findZipUrl = options.Url;

        $($obj).html('<div style="padding-top:2px;padding-bottom:2px;"><span class="entryLabel"><label>Enter city</label></span><input type="text" style="width:300px;" /></div><select size="10" style="width:368px;"></select>');
        $("select", $obj).dblclick(function() { selectZip($obj); });
        $("input:text", $obj).keyup(function() { findZipByCity($obj); });
        $("input:text", $obj).keypress(function(e) {
            if (e.which == 13) {
                selectZip($obj);
                return false;
            }
        });
        $($obj).dialog({
            autoOpen: false,
            modal: true,
            title: "Enter City for Zip Code Lookup",
            width: 400,
            buttons: {
                "Cancel": function() { $(this).dialog("close"); },
                "Select": function() { selectZip(this); }
            }
        });
    }
})(jQuery);

// function taken from http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
(function($) {

    $.fn.setCursorPosition = function(pos) {
        /// <summary>
        /// Moves the caret position of an input field to the desired position
        /// </summary>
    if ($(this).get(0).setSelectionRange) {
        $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
        var range = $(this).get(0).createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}
})(jQuery);

