﻿(function($) {
    $.ZipCodeFinder = function(options) {
        var settings = $.extend({
            panel: '.ZipCodeFinderPanel',                   // Must resolve the the popup panel, so the popup can be closed (hidden)
            panelBackground: '.ZipCodeFinderPanelBG',       // Must resolve to the background panel, so popup can be closed (hidden)
            title: 'F I N D &nbsp;&nbsp; Z I P &nbsp;&nbsp; C O D E S<br />', // The title displayed in popup
            city: '#City',                                  // Must resolve to a textbox, i.e., <input type="text" />
            state: '#State',                                // Must resolve to a dropdown list, i.e., <select></select>
            target: '#Target',                              // Must resolve to a textbox, i.e., <input type="text" />
            zipDisplay: '#ZipDiv',                          // The container for the table of zipcodes.  Works best as <div></div>
            answerDisplay: '#AnsDiv',                       // The container for the "City, State Zip" answer field
            mapCanvas: '#MapCanvas',                        // The "canvas" (container) for the google map.  Usually a <div></div>
            okButton: '#btnOK',                             // The OK button - copies selected zip code to target and closes popup
            cancelButton: '#btnCancel',                     // The Cancel button - closes the popup without any selection
            mapButton: '#MapButton',                        // The button that shows/hides the google map
            zipCodeTableID: 'ZipCodeSelection',             // The id of for the zip code table.
            defaultZipClass: 'PickMe',                      // The CSS class used for the default zip code in the table of zip codes
            answerSelectableClass: 'Selectable',            // The CSS class that indicates the the "anser" is now selectable
            hoverClass: 'hover',                            // The CSS class supplied when hovering over a zip code in the table
            errorClass: 'error',                            // The CSS class for the error message.
            noZipCodeFoundMessage: 'Sorry.&nbsp; No zip code found.',  // The message to display in "answer", if no match is found
            errorMessage: 'Error.&nbsp; Try again.&nbsp; If the error persists, call support.', // The error message.
            columns: 6,                                     // The number of columns in the zip code table
            showMap: false,
            onSuccess: null,                                // Callback function to call on successful completion
            onCancel: null                                  // Callback function to call, if the action is cancelled
        }, options || {});


        var $panel = $(settings.panel);
        var $panelBackground = $(settings.panelBackground);
        var $city = $(settings.city);
        var $state = $(settings.state);
        var $target = $(settings.target);
        var $zip = $(settings.zipDisplay);
        var $answer = $(settings.answerDisplay);
        var $map = $(settings.mapCanvas);
        var $okButton = $(settings.okButton);
        var $cancelButton = $(settings.cancelButton);
        var $mapButton = $(settings.mapButton);
        if (!settings.showMap) $mapButton.hide();

        $city.focus();
        $city.val('');
        $state.html('<option></option>');
        $state.val('');
        $state.attr('disabled', true);
        $(settings.panel + ' th').html(settings.title);
        $answer.text('');
        $zip.text('');
        $answer.removeClass(settings.answerSelectableClass);
        $city.keyup(txtCityKey);
        $state.change(ddSelect);
        $okButton.click(clickAnswer);
        $okButton.attr('disabled', true);
        $mapButton.click(toggleMap);
        $mapButton.attr('disabled', true);
        setTargetTitle($target.val());
        $map.hide(); $zip.show();
        $city.focus();

        function txtCityKey(event) {
            if ($city.val().replace(/^\s+|\s+$/g, "") != '') {
                GetAllZips();
                GetStates();
            }
            else {
                $answer.html('&nbsp;');
                $zip.html('&nbsp;');
                $answer.removeClass(settings.answerSelectableClass);
                $answer.unbind('click');
                $okButton.attr('disabled', true);
                $state.unbind('change');
                $state.html('<option></option>');
                $state.val('');
                $state.attr('disabled', true);
            }
            if (event.which == 13 && $answer.html().length > 0) {
                clickAnswer();
            }
        }

        function ddSelect() {
            GetAllZips();
        }

        function clickAnswer() {
            var answer = $answer.html();
            var title = '';
            if (answer.match(/\d{5}$/)) {
                var zip = answer.substring(answer.length - 5);
                var title = answer.length > 6 ? answer.substring(0, answer.length - 6) : '';
                $target.val(zip);
                $target.focus();
                $target.attr('title', title);
            }
            if (settings.onSuccess != null) settings.onSucces();
            $city.unbind('keyup');
            $state.unbind('change');
            $answer.unbind('click');
            $okButton.unbind('click');
            $('#' + settings.zipCodeTableID + ' td').unbind('click');
            $('#' + settings.zipCodeTableID + ' td').unbind('dblclick');
            $panel.hide();
            $panelBackground.hide();
        }


        function setTargetTitle(zip) {
            zip = zip.replace(/^\s+|\s+$/g, "");
            if (zip.match(/^\d{5}$/)) {
                $.ajax({
                    type: "POST",
                    url: "http://www.movingconnections.com/Service.asmx/sGetCityState",
                    data: 'zip=' + zip,
                    success: function(data, textStatus, jqXHR) {
                        $target.attr('title', $('string', data).text());
                    },
                    error: function(date, textStatus, jqXHR) {
                        $target.attr('title', '');
                    }
                });
            }
        }

        function SelectZipAndState(z) {
            ShowSelectionString(z);
            SelectState(z);
        }

        function GetStates() {
            $.ajax({
                type: "POST",
                url: "http://www.movingconnections.com/Service.asmx/sGetAllStatesFull",
                data: 'city=' + $city.val(),
                success: function(data, textStatus, jqXHR) {
                    var cnt = 0;
                    $state.html('<option></option>');
                    $('ArrayOfString string', data).each(function(n) {
                        if ($(this).text().replace(/^\s+|\s+$/g, "") != '') {
                            $state.append('<option>' + $(this).text() + '</option>');
                            cnt++;
                        }
                    });
                    if ($zip.is(':hidden')) toggleMap();
                    if (cnt >= 1) {
                        $state.attr('disabled', false);
                        $mapButton.attr('disabled', false);
                    }
                    else {
                        $state.val('');
                        $state.attr('disabled', true);
                        $mapButton.attr('disabled', true);
                    }
                    if (cnt == 1) $('option:last', $state).attr('selected', 'selected');
                    else $('option:first', $state).attr('selected', 'selected');
                },
                error: function(data, textStatus, jqXHR) {
                    $state.html('<option></option>');
                    $state.val('');
                    $state.attr('disabled', true);
                    $mapButton.attr('disabled', true);
                }
            });
        }

        function GetAllZips() {
            var defaultZip = '';
            $.ajax({
                type: "POST",
                url: "http://www.movingconnections.com/Service.asmx/sGetDefaultZip",
                data: 'city=' + $city.val(),
                success: function(data, textStatus, jqXHR) {
                    defaultZip = $('string', data).text();
                    GetAllZipsGivenDefault(defaultZip);
                },
                error: function(data, textStatus, jqXHR) {
                    GetAllZipsGivenDefault('');
                }
            });
        }

        function ShowSelectionString(z) {
            $.ajax({
                type: "POST",
                url: "http://www.movingconnections.com/Service.asmx/sCorrectCSZ",
                data: 'city=' + $city.val() + '&state=' + $('option:selected', $state).val() + '&zip=' + z,
                success: function(data, textStatus, jqXHR) {
                    $answer.text($('string', data).text());
                    $answer.addClass(settings.answerSelectableClass);
                    $answer.click(clickAnswer);
                    $okButton.attr('disabled', false);
                },
                error: function(data, textStatus, jqXHR) {
                    $answer.text(z);
                    $answer.addClass(settings.answerSelectableClass);
                    $answer.click(clickAnswer);
                    $okButton.attr('disabled', false);
                }
            });
        }

        function GetAllZipsGivenDefault(defaultZip) {
            $.ajax({
                type: "POST",
                url: "http://www.movingconnections.com/Service.asmx/sGetAllZipsAndStateFull",
                data: 'city=' + $city.val() + '&state=' + $('option:selected', $state).text(),
                success: function(data, textStatus, jqXHR) {
                    var default_found = false;
                    var cnt = 0;
                    var s = '';
                    var line = '';
                    var zipCode = '';
                    var state = '';
                    var lastZip = '';
                    $('ArrayOfString string', data).each(function(n) {
                        line = $(this).text().replace(/^\s+|\s+$/g, "");
                        if (line.length > 0) {
                            zipCode = line.substring(0, 5);
                            if (zipCode != lastZip) {
                                lastZip = zipCode;
                                state = line.substring(6);
                                if (cnt == 0 || cnt % settings.columns == 0) s += '  <tr>\n';
                                var css_class = '';
                                if (!default_found) {
                                    if (zipCode.substring(0, 2) == "84") {
                                        default_found = true;
                                        css_class = ' class="' + settings.defaultZipClass + '"';
                                    }
                                    else if (defaultZip != '' && zipCode == defaultZip) {
                                        default_found = true;
                                        css_class = ' class="' + settings.defaultZipClass + '"';
                                    }
                                }
                                s += '    <td title="'
                                + state + '"' + css_class + '>' + zipCode + '</td>\n';
                                if ((cnt % settings.columns) == (settings.columns - 1)) s += '  </tr>\n';
                                cnt++;
                            }
                        }
                    });
                    if (cnt == 0) {
                        $zip.html('&nbsp;');
                        $answer.html(settings.noZipCodeFoundMessage);
                        $answer.removeClass(settings.answerSelectableClass);
                        $answer.unbind('click');
                        $okButton.attr('disabled', true);
                    }
                    else if (cnt == 1) {
                        var s2 = $('ArrayOfString string', data).text().substring(0, 5);
                        $zip.html('&nbsp;');
                        ShowSelectionString(s2);
                    }
                    else {
                        $zip.html('<table id="' + settings.zipCodeTableID + '" align="center">\n' + s + '</table>\n');
                        var $defaultTD = default_found
                            ? $('#' + settings.zipCodeTableID + ' td.' + settings.defaultZipClass)
                            : $('#' + settings.zipCodeTableID + ' td:first');
                        ShowSelectionString($defaultTD.text());
                        $('td.' + settings.defaultZipClass, $zip).removeClass(settings.defaultZipClass);
                        $defaultTD.addClass(settings.defaultZipClass);
                    }
                    $('#' + settings.zipCodeTableID + ' td').hover(
                            function() { $(this).addClass(settings.hoverClass); },
                            function() { $(this).removeClass(settings.hoverClass); });
                    $('#' + settings.zipCodeTableID + ' td').click(function() {
                        $('td.' + settings.defaultZipClass, $zip).removeClass(settings.defaultZipClass);
                        $(this).addClass(settings.defaultZipClass);
                        ShowSelectionString($(this).text());
                    });
                    $('#' + settings.zipCodeTableID + ' td').dblclick(clickAnswer);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $zip.html("<span class='" + settings.errorClass + "'>" + settings.errorMessage + "</span>");
                }
            });
        }

        function SelectState(z) {
            $.ajax({
                type: "POST",
                url: "http://www.movingconnections.com/Service.asmx/sGetAStateFromZip",
                data: 'zip=' + z,
                success: function(data, textStatus, jqXHR) {
                    var state = $('string', data).text();
                    $state.val(state);
                }
            });
        }

        function toggleMap() {
            $zip.toggle();
            if ($map.is(':hidden')) ShowMap();
            else $map.hide();
        }

        function ShowMap() {
            $.ajax({
                type: "POST",
                url: "http://www.movingconnections.com/Service.asmx/sGetAllZipsLatLngAndStateFull",
                data: 'city=' + $city.val() + '&state=' + $('option:selected', $state).text(),
                success: function(data, textStatus, jqXHR) {
                    var markers = '';
                    $('ArrayOfString string', data).each(function(n) {
                        line = $(this).text().replace(/^\s+|\s+$/g, "");
                        if (line.length > 0) {
                            markers += line.substring(0, line.indexOf(';') + 1);
                        }
                    });
                    var url = 'map.html';
                    if (markers.length > 0) url += '?' + markers.substr(0, markers.length-1);
                    $('#ViewLargerMapLink').attr('href', url);
                    $map.height($zip.height()).width($zip.width());
                    $('iframe', $map).height($zip.height()).width($zip.width()).attr('src', url);
                    $map.show();
                },
                error: function(data, textStatus, jqXHR) {
                    $map.height($zip.height()).width($zip.width());
                    $('iframe', $map).height($zip.height()).width($zip.width()).attr('src', 'map.html');
                    $map.show();
                }
            });
        }
    }
})(jQuery);

$(function() {
    $('#bookingZipCodeBox .zipCodeInBox1').keyup(function() { setTitle('#bookingZipCodeBox .zipCodeInBox1') });
    $('#bookingZipCodeBox .zipCodeInBox2').keyup(function() { setTitle('#bookingZipCodeBox .zipCodeInBox2') });
    setTitle('#bookingZipCodeBox .zipCodeInBox1');
    setTitle('#bookingZipCodeBox .zipCodeInBox2');
});
function setTitle($target) {
    $target = $($target);
    var zip = $target.val();
    if (zip == null || zip == undefined) zip = '';
    zip = zip.replace(/^\s+|\s+$/g, "");
    if (zip.match(/^\d{5}$/)) {
        $target.css('color', 'Black');
        $.ajax({
            type: "POST",
            url: "http://www.movingconnections.com/Service.asmx/sGetCityState",
            data: 'zip=' + zip,
            success: function(data, textStatus, jqXHR) {
                var title = $('string', data).text();
                if (title.length == 0) title = '?';
                $target.attr('title', title);
            },
            error: function(date, textStatus, jqXHR) {
                $target.attr('title', '???');
            }
        });
    }
    else $target.css('color', '#232323');
}

// New API Key = AIzaSyA28ZcwUtr6uaBwq3iyr_93N5z2CcjYLU8


//src="http://maps.googleapis.com/maps/api/js?key=ABQIAAAAlSkTbhH-b6R-yRHxqIzlyRQ40-HWsk0h_LlHzSY1fG-qw50YqhQkr5E5GhZrpW_B6R01eAhddJ2YCA&sensor=FALSE">

//Google Maps Tutorial:
//<script type="text/javascript"
//    src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
//</script>
//<script type="text/javascript">
//  function initialize() {
//    var latlng = new google.maps.LatLng(-34.397, 150.644);
//    var myOptions = {
//      zoom: 8,
//      center: latlng,
//      mapTypeId: google.maps.MapTypeId.ROADMAP
//    };
//    var map = new google.maps.Map(document.getElementById("map_canvas"),
//        myOptions);
//  }

//</script>


//        Movers Detail Page (HTML):
//        <iframe width="670" height="630" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" 
//            src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=412+East+Broadway,+Salt+Lake+City,+UT&amp;aq=0&amp;sll=37.0625,-95.677068&amp;sspn=54.533615,114.169922&amp;vpsrc=0&amp;ie=UTF8&amp;hq=&amp;hnear=412+E+Broadway,+Salt+Lake+City,+Utah+84111&amp;z=14&amp;ll=40.762778,-111.879133&amp;output=embed">
//        </iframe>
//        <br />
//        <small>
//        <a href="http://maps.google.com/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=412+East+Broadway,+Salt+Lake+City,+UT&amp;aq=0&amp;sll=37.0625,-95.677068&amp;sspn=54.533615,114.169922&amp;vpsrc=0&amp;ie=UTF8&amp;hq=&amp;hnear=412+E+Broadway,+Salt+Lake+City,+Utah+84111&amp;z=14&amp;ll=40.762778,-111.879133" 
//            style="color:#0000FF;text-align:left">View Larger Map</a>
//        </small>


//        Google Directions (C#):
//        private string _key = "ABQIAAAAlSkTbhH-b6R-yRHxqIzlyRQ40-HWsk0h_LlHzSY1fG-qw50YqhQkr5E5GhZrpW_B6R01eAhddJ2YCA";
//        private string _output = "js";
//        private string _requestFormat = "http://maps.google.com/maps/nav?key={0}&output={1}&q={2}";
//        private Hashtable _data = new Hashtable();


//            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
//                string.Format(_requestFormat, _key, _output, Uri.EscapeUriString(path)));
//            request.Method = "GET";
//            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//            StreamReader reader = new StreamReader(response.GetResponseStream());
//            string json = reader.ReadToEnd();
//            json = parseUnicode(json);
//            _data = readJson(new JsonTextReader(new StringReader(json)));
//            IsValid = _data.ContainsKey("Directions");

