﻿/// <reference path="tacoBell.js" />
/// <reference path="libraries/jquery-1.3.2-vsdoc2.js" />
/// <reference path="libraries/jquery.validate.js" />

if (!tacoBell.contactUs) {
    tacoBell.contactUs = (function () {
        var _storeListingsModalOpens;
        var _jsonUrl = '/storelocatorjson/BsdsJSONHandler.ashx';
        function _setUp() {
            // add open/close form event handlers
            _addFormShowHideHandlers();
            // add store locator handlers
            _storeListingsModalOpens = 0;
            _addStoreLocatorHandlers();
            // Add custom validator methods
            $.validator.addMethod("notFutureDate", function (value, element) {
                var today = new Date();
                // javascript month is 0-based
                var dateOccurred = new Date($('#DateOccuredYear').val(), $('#DateOccuredMonth').val() - 1, $('#DateOccuredDay').val());
                var timeOccurred = $("#DateOccuredTime").val();
                if (timeOccurred != '') {
                    var timeParts = timeOccurred.split(':');
                    var hours = parseInt(timeParts[0]);
                    var minutes = parseInt(timeParts[1]);
                    if (hours === 12) {
                        if ($("#DateOccuredTimeSuffix").val() === "am")
                            hours = 0;
                    }
                    else if ($("#DateOccuredTimeSuffix").val() === "pm")
                        hours = hours + 12;
                    dateOccurred.setHours(hours);
                    dateOccurred.setMinutes(minutes);
                }
                if (dateOccurred > today) {
                    return false;
                    alert(dateOccurred);
                } else {
                    return true;
                }
            }, "Future date not allowed: Please enter a valid date");

            $.validator.addMethod("validTime", function (value, element) {
                if (value !== null && value != '') {
                    if (value.match(/^\d{1}:\d{2}/)) {
                        var hours = value.replace(/(\d{1}):\d{2}/g, "$1");
                        if (hours < 1) {
                            // alert(hours);
                            return false;
                        }
                        var minutes = value.replace(/\d{1}:(\d{2})/g, "$1");
                        if (minutes < 0 || minutes > 59) {
                            return false;
                        }
                    } else if (value.match(/^\d{2}:\d{2}/)) {
                        var _hours = value.replace(/(\d{2}):\d{2}/g, "$1");
                        if (_hours < 1 || _hours > 12) {
                            return false;
                        }
                        var _minutes = value.replace(/\d{2}:(\d{2})/g, "$1");
                        if (_minutes < 0 || _minutes > 59) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                return true;
            }, "Please enter a valid time (i.e. 12:00)");

            $.validator.addMethod("maxCommentLength", function (value, element) {
                if (value !== null && value != '') {
                    if (value.length > 500) {
                        return false;
                    }
                }
                return true;
            }, "Comment is too long");


            // jQuery phone validator
            //TODO: need to update to include:
            // 900, 911, 976, 809,111, 222, 333, 444, 555, 666, 777, 888, 999, 000
            // also phone number cannot start with 1 or 0, but I think this is already covered.
            var _nonValidValues = { '900': 'emergency', '911': 'emergency', '976': 'pay', '809': '', '000': '', '111': '',
                '222': '', '333': '', '444': '', '555': '', '666': '', '777': '', '888': '', '999': ''
            };
            $.validator.addMethod("phoneUS", function (phone_number, element) {
                phone_number = phone_number.replace(/\s+/g, "");
                var first3 = $("#CustomerPrimaryPhone1").val();
                var second3 = $("#CustomerPrimaryPhone2").val();
                if (first3 in _nonValidValues) return false;
                phone_number = first3 + second3 + phone_number;
                return this.optional(element) || phone_number.length > 9 &&
		        phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
            }, "Please specify a valid phone number");

            $.validator.addMethod("phoneUSOther", function (phone_number, element) {
                phone_number = phone_number.replace(/\s+/g, "");
                var first3 = $("#CustomerOtherPhone1").val();
                var second3 = $("#CustomerOtherPhone2").val();
                if (first3 in _nonValidValues) return false;
                phone_number = first3 + second3 + phone_number;
                return this.optional(element) || phone_number.length > 9 &&
		        phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
            }, "Please specify a valid phone number");

            //custom validator for money fields
            $.validator.addMethod("money", function (value, element) {
                return this.optional(element) || value.match(/^\$?\d+(\.(\d{2}))?$/);
            }, "Please provide a valid dollar amount (up to 2 decimal places).");



            $('#btnSubmit').click(function () {
                var amountSpent = $("#AmountSpent").val();
                amountSpent = amountSpent.replace('$', '');
                $("#AmountSpent").val(amountSpent);
                $('#formContactUs').submit();
                return false;
            });

            $('#btnReset').click(function () {
                $(':input', '#formContactUs').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
                $("#DateOccuredMonth").val(0);
                $("#DateOccuredDay").val(0);
                $("#DateOccuredYear").val("[Year]");
                $("#DateOccuredTimeSuffix").val("am");
                $("#StoreState").val(0);
                $("#CustomerState").val(0);
                $("#anonymous").attr("checked", "");
                $('#contactCustInfo').find(':input:not(#anonymous)').attr('disabled', '');
                $("div.error p").html('');
                $("div.error").hide();
                $(".acctFieldError").children("label").remove();
                return false;
            });
        }
        function _addFormShowHideHandlers() {
            $('.acctFormHeaderM > *').bind('click', function () {
                $(this).parent().find('.arrowCollapsed').toggleClass('arrowExpanded');
                $(this).closest('.acctFormHeader').siblings('.acctFormFields, .acctFormFooter').toggle();
                tacoBell.utils.adjustContentHeight();
            });
            $('#addlInfoY').bind('click', function () {
                $('#arrowCustInfo').addClass('arrowExpanded');
                $('#contactCustInfo .acctFormFields, #contactCustInfo .acctFormFooter').show();
                tacoBell.utils.adjustContentHeight();
            });
            $('#addlInfoN').bind('click', function () {
                $('#arrowCustInfo').removeClass('arrowExpanded');
                $('#contactCustInfo .acctFormFields, #contactCustInfo .acctFormFooter').hide();
                tacoBell.utils.adjustContentHeight();
            });
        }
        function _addStoreLocatorHandlers() {
            // open modal w/store locations
            $('#storeLookupBtn').bind('click', _showStoreLocations);
        }

        function _changeLocation() {
            $('#storeLookup').css({ display: 'block' });
            $('#storeSelected').css({ display: 'none' });
            $('#StoreNumber').val("");
        }

        function _showStoreLocations() {
            $("#storeLocError").text("");
            var parmCity = $('#StoreCity').val();
            var parmState = $('#StoreState').val();
            var parmZip = $('#StoreZip').val();
            var credentials = "AqjQIZFdEbh-PWcB747VaIsiot8J9NkXSnBjLDio3Lx2bghfYf-2Rg0rQxq-zYxJ";
            var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/{0}?output=json&jsonp=GeocodeCallback&key=" + credentials;
            if (parmZip != "")
                geocodeRequest = geocodeRequest.replace("{0}", parmZip);
            else if ((parmCity != "") && (parmState != ""))
                geocodeRequest = geocodeRequest.replace("{0}", encodeURI(parmCity + ", " + parmState));
            else {
                $("#storeLocError").append("Please enter either a zip code or a city/state combination. <br />");
                return;
            }

            $.ajax({ url: geocodeRequest,
                dataType: 'jsonp',
                data: ''
            });
        }
        function _geocodeCallback(data) {
            var id = 0;
            var method = 'findNearbyStores';
            var location = { "Latitude": result.resourceSets[0].resources[0].point.coordinates[0], "Longitude": result.resourceSets[0].resources[0].point.coordinates[1] };
            var params = '{ "latitude" : "' + location.Latitude + '", "longitude" : "' + location.Longitude + '", "distance" : ' + 10 + ' }';
            _getStoreData(id, method, params, location);
        }
        function _getStoreData(id, method, params, location) {
            var jsonData = '{\"id\":' + id + ',\"method\":\"' + method + '\",\"params\":' + params + '}';
            // alert("Before AJAX request");
            $.ajax({
                type: 'POST',
                url: _jsonUrl,
                data: jsonData,
                dataType: 'json',
                success: function (jsonObj) {
                    _jsonObj = jsonObj;
                    try {
                        if ((jsonObj.result.length === 0) && (params.indexOf("\"distance\" : 30") < 0)) {
                            params = params.replace("\"distance\" : 10", "\"distance\" : 30");
                            GetStoreData(id, method, params, location);
                            return;
                        }
                        $('#storeListingsTableBody').empty();
                        if (jsonObj.result.length === 0) {
                            var newTr = '<tr><td class="storeLeft"><!-- --></td><td class="storeStreet">No Matches Found</td></tr>';
                            $('#storeListingsTableBody').append(newTr);
                        }
                        else {
                            var count = Math.min(jsonObj.result.length, 10);
                            for (i = 0; i < count; i++) {
                                var thisResult = jsonObj.result[i];
                                var newTr = '<tr><td class="storeLeft"><input type="hidden" id="hiddenStoreNumber" value="' + thisResult.storeNumber + '"/></td><td class="storeStreet"><a href="#">' + thisResult.streetAddress +
                                    '</a></td><td class="storeCity">' + thisResult.city + ',' + thisResult.state + '</td><td class="storeZip">' + thisResult.postalCode + '</td></tr>';
                                $('#storeListingsTableBody').append(newTr);
                            }
                            $('#storeListingsTable tr:even td').addClass('storeListingHighlight');
                            _bindStoreLinks();
                            tacoBell.utils.ModalDialogManager.openModal('storeListings');
                            _storeListingsModalOpens++;
                        }
                    } catch (err) {
                        $("#storeLocError").append("ERROR: Please verify that the ZIP code or the City, State combination are valid. <br />");
                    }
                },
                error: function (err) {
                    $("#storeLocError").append("ERROR: Please verify that the ZIP code or the City, State combination are valid. <br />");
                }
            });
        }
        function _bindStoreLinks() {
            $('#storeListingsModal .storeStreet a').one('click', _selectStore);
        }
        function _selectStore(event) {
            event.preventDefault();
            // get store data
            var target = $(event.target);
            //alert(this, $(this));
            var storeAddr = target.text();
            var storeCity = target.parent().next().text();
            var storeZip = target.parent().next().next().text();
            var storeNumber = target.parent().prev().children()[0].value;
            $.modal.close();
            // show selected store data
            $('#storeSelectedInfo').text(storeAddr + ', ' + storeCity + ' ' + storeZip);
            $('#storeChangeLocBtn').bind('click', _changeLocation);
            $('#storeLookup').css({ display: 'none' });
            $('#storeSelected').css({ display: 'block' });
            $('#StoreUnitNumber').val(storeNumber);
            $('#StoreNumber').val(storeNumber);
        }
        return {
            setUp: function () {
                _setUp();
            },
            selectStore: function (event) {
                _selectStore(event);
            },
            getStoreData: function (id, method, params, location) {
                _getStoreData(id, method, params, location);
            }
        }
    })();
}

if ($('#formContactUs').length) {
    $(function () {
        var zip_error = 'Please enter a valid 5 digit US ZIP code.';
        var store_number_error = 'Store number must be 6 digits. Please enter all leading zeros.';
        var phone1_error = 'Please enter a valid phone number.';
        var phone_error = 'Please enter a valid phone number.';
        var date_error = 'Please enter a valid date';
        var need_store_error = "Please enter a store number";

        $('#addlInfoN').click(function () {
            $('#addlInfoWarning').removeClass("disabled");
            $('#addlInfoWarning').addClass("enabled");
        });

        $('#addlInfoY').click(function () {
            $('#addlInfoWarning').removeClass("enabled");
            $('#addlInfoWarning').addClass("disabled");
        });

        $('#formContactUs').validate({
            debug: true,
            ignoreTitle: true,
            errorPlacement: function (e, el) {
                e.appendTo(el.parents('div.acctFieldSet').find('div.acctFieldError:first'));
                //tacoBell.utils.adjustContentHeight();
            },
            submitHandler: function (form) {
                form.submit();
            },
            invalidHandler: function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = errors == 1
                  ? 'You missed 1 field. It has been highlighted'
                  : 'You missed ' + errors + ' fields. They have been highlighted';
                    $("div.error p").html(message);
                    $("div.error").show();
                } else {
                    $("div.error").hide();
                }
            },
            rules: {
                DateOccuredMonth: {
                    required: true,
                    digits: true,
                    min: 1
                },
                DateOccuredDay: {
                    required: true,
                    digits: true,
                    min: 1
                },
                DateOccuredYear: {
                    required: true,
                    digits: true,
                    notFutureDate: true,
                    min: 1920
                },
                DateOccuredTime: {
                    validTime: true
                },
                AmountSpent: {
                    money: true
                },
                Comments: {
                    maxCommentLength: true
                },
                StoreZip: {
                    minlength: 5,
                    maxlength: 5,
                    digits: true
                },
                StoreNumber: {
                    required: true,
                    minlength: 6,
                    maxlength: 7
                },
                addlInfo: 'required',
                CustomerFirstName: {
                    required: '#addlInfoY:checked'
                },
                CustomerLastName: {
                    required: '#addlInfoY:checked'
                },
                CustomerEmail: {
                    required: false,
                    email: true
                },
                CustomerTitle: {
                    required: '#addlInfoY:checked'
                },
                CustomerZip: {
                    minlength: 5,
                    maxlength: 5,
                    digits: true
                },
                CustomerPrimaryPhone1: {
                    required: '#addlInfoY:checked',
                    digits: true,
                    minlength: 3,
                    maxlength: 3
                },
                CustomerPrimaryPhone2: {
                    required: '#addlInfoY:checked',
                    digits: true,
                    minlength: 3,
                    maxlength: 3
                },
                CustomerPrimaryPhone3: {
                    required: '#addlInfoY:checked',
                    digits: true,
                    minlength: 4,
                    maxlength: 4,
                    phoneUS: true
                },
                CustomerOtherPhone1: {
                    required: false,
                    digits: true,
                    minlength: 3,
                    maxlength: 3,
                    phoneUSOther: true
                },
                CustomerOtherPhone2: {
                    required: false,
                    digits: true,
                    minlength: 3,
                    maxlength: 3,
                    phoneUSOther: true
                },
                CustomerOtherPhone3: {
                    required: false,
                    digits: true,
                    minlength: 4,
                    maxlength: 4,
                    phoneUSOther: true
                },
                CustomerState: {
                    required: '#addlInfoY:checked'
                }
            },
            messages: {
                CustomerZip: {
                    minlength: zip_error,
                    maxlength: zip_error,
                    digits: zip_error
                },
                DateOccuredMonth: {
                    digits: date_error,
                    min: date_error
                },
                DateOccuredDay: {
                    digits: date_error,
                    min: date_error
                },
                DateOccuredYear: {
                    digits: date_error,
                    min: date_error
                },
                StoreNumber: {
                    minlength: store_number_error,
                    maxlength: store_number_error,
                    required: need_store_error
                }


            },
            groups: {
                dob: 'DateOccuredMonth DateOccuredDay DateOccuredYear',
                phone: 'CustomerPrimaryPhone1 CustomerPrimaryPhone2 CustomerPrimaryPhone3',
                phone2: 'CustomerOtherPhone1 CustomerOtherPhone2 CustomerOtherPhone3'
            }
        });


    });
}

