﻿(function ($) {

    $.widget("ui.newAppointment", {

        _init: function () {
            var self = this;
            self._computeOptions();
            self._loadForm();
        },
        _loadForm: function () {
            var self, $pageHtml;
            self = this;

            self._bookingOptions();
        },


        _createForm: function () {
            var self = this;
            var $mapids = self._mapids();
            var panelHtml = '';
            var fsp;

            for (var i = 0; i < $mapids.length; i++) {
                var $MAP = $mapids[i];
                if ($MAP.beginFs == true) {
                    panelHtml += closeTag('fieldset', panelHtml);
                    panelHtml += '<fieldset class=\'ui-corner-all\' style=\'clear:both;padding-left:5px;\'>';
                }
                panelHtml += createIDiv($MAP.map, $MAP.lSize, $MAP.iSize, $MAP.iType, $MAP.txt, $MAP.bDiv, $MAP.eDiv, $MAP.lClass, $MAP.iClass, $MAP.lType);
            }
            panelHtml += closeTag('fieldset', panelHtml);
            panelHtml += closeTag('div', panelHtml);
            panelHtml += closeTag('div', panelHtml);

            panelHtml = '<div style=\'position:relative;clear:all;\'>' + panelHtml + '</div>';
            //}

            return panelHtml;
        },

        _mapids: function () {
            var $mapids;

            $mapids = [
            { map: 15217, lSize: 0, iSize: 2, iType: 'text', txt: 'Subject', bDiv: true, eDiv: true, lClass: '', iClass: '', lType: 'label', beginFs: true, beginSp: true },
            { map: 15223, lSize: 0, iSize: 2, iType: 'resource', txt: 'Resource:', bDiv: true, eDiv: true, lClass: '', iClass: ' ddchecklist', lType: 'label', beginFs: false, beginSp: false },
            { map: 15214, lSize: 0, iSize: 2, iType: 'appointment', txt: 'Start:', bDiv: true, eDiv: true, lClass: '', iClass: '', lType: 'label', beginFs: true, beginSp: false },
            { map: 15218, lSize: 0, iSize: 2, iType: 'text', txt: 'Duration:', bDiv: true, eDiv: true, lClass: '', iClass: 'adp', lType: 'label', beginFs: true, beginSp: false },
            { map: 15201, lSize: 0, iSize: 2, iType: 'select', txt: 'Category:', bDiv: true, eDiv: true, lClass: '', iClass: '', lType: 'label', beginFs: true, beginSp: false }
            ];
            return $mapids;
        },
        _bookingOptions: function () {
            var self = this;

            var $html = '<div>';
            $html += '<p>To use a pre-defined booking type, select below and cick OK</p>';
            $html += createIDiv(15202, 1, 2, 'select', 'Busy State', true, true, '', '', '', false, false);
            $html += closeTag('div', $html);

            var $bookingOptions = $('body').find('.sd-booking-options');
            if ($bookingOptions.length < 1) {
                $('body').append('<div class=\'sd-booking-options\' title=\'Booking Option\'></div>');
                $('body').find('.sd-booking-options').bind('dialogclose', function (event) {
                    $(this).empty();
                    $(this).dialog('destroy');
                });
            }

            $bookingOptions = $('body').find('.sd-booking-options');
            $bookingOptions.empty();
            $bookingOptions.dialog('destroy');
            $bookingOptions.append($html);

            $bookingOptions.dialog(
            {
                bgiframe: true,
                resizable: false,
                modal: true,
                buttons:
                {
                    Cancel: function () {
                        $(this).dialog('close');
                    },
                    OK: function () {
                        var color = $(this).find('select').val();
                        var subject = $(this).find('select option:selected').text();

                        var jsonData = { 'smartid': $('#usercred').data('sid'), 'color': color };
                        var url = "/Services/DefaultService.svc/GetBusyStateConstraint";
                        $.ajax(
                        {
                            type: "POST",
                            url: url,
                            data: JSON.stringify(jsonData),

                            dataType: "json",
                            success: function (msg) {
                                var minContact = 0;
                                var maxContact = 0;
                                for (var i = 0; i < msg.d.length; i++) {
                                    var con = msg.d[i];
                                    switch (con.ConstraintType) {
                                        case 0:
                                            self.element.data('duration', con.ConstraintValue);
                                            self.options.duration = con.ConstraintValue;
                                            break;
                                        case 5:
                                            self.element.data('category', con.ConstraintValue);
                                            self.options.category = con.ConstraintValue;
                                            break;
                                        case 6:
                                            self.element.data('subject', con.ConstraintText);
                                            break;
                                        case 7:
                                            self.options.maxcontact = con.ConstraintValue;
                                            maxContact = con.ConstraintValue;
                                            break;
                                        case 8:
                                            self.options.mincontact = con.ConstraintValue;
                                            minContact = con.ConstraintValue;
                                            break;
                                    }
                                }
                                self.element.data('busystate', color);
                                self.options.busystate = color;
                                if (self.element.data('subject') == undefined) {
                                    self.element.data('subject', subject);
                                }
                                if (self.element.data('duration') == undefined) {
                                    self.element.data('duration', 30);
                                }
                                if (minContact < maxContact) {
                                    $(this).empty();
                                    $(this).dialog('close');
                                    $(this).dialog('destroy');
                                    self._bookingOptions2();
                                }
                                else {
                                    $(this).empty();
                                    $(this).dialog('close');
                                    $(this).dialog('destroy');
                                    self._newBookingForm();
                                }
                                //$(this).dialog('close');
                            }
                        });
                    }
                }
            });
        },
        _bookingOptions2: function () {
            var self = this;
            var $bookingOptions = $('body').find('.sd-booking-options');

            $bookingOptions.empty();
            $bookingOptions.dialog('destroy');

            var $html = '<div>';
            $html += '<p>To create a new booking select New, to search availability in an existing booking, choose a date below and select Search</p>';
            $html += '<div style=\'clear:both\'><label class=\'sd-label-short\' for=\'\'>Start</label>';
            $html += '<input class=\'dtp sd-input-long\' type=\'text\'/>';

            //$html += createIDiv(15214, 0, 1, 'appointment', 'Start:', true, true, '', '', '', false, false);

            $html += closeTag('div', $html);

            //$('body').append('<div class=\'sd-booking-options\' title=\'Booking Option\'></div>');

            $bookingOptions.append($html);

            $bookingOptions.find('.dtp').val(new Date().toDateString());

            $bookingOptions.find('.dtp').datepicker({ dateFormat: 'D d M yy' });
            $('div.ui-datepicker').css('z-index', '10000');

            $bookingOptions.bind('dialogclose', function (event) {
                $(this).dialog('destroy');
            });

            $bookingOptions.dialog(
            {
                bgiframe: true,
                resizable: false,
                modal: true,
                //width: 450,
                buttons:
                {
                    'New': function () {
                        $(this).dialog('close');
                        self._newBookingForm();
                    },
                    'Search': function () {
                        self.options.searchstart = new Date($bookingOptions.find('input.dtp').val());
                        $(this).dialog('close');
                        self._findBooking();
                    }
                }
            });

        },
        _findBooking: function () {
            var self = this;

            var $availabilityFrm = $('body').find('.sd-booking-availability');
            if ($availabilityFrm.length < 1) {
                $('body').append('<div class=\'sd-booking-availability\' title=\'Booking Availability\'></div>');
                $availabilityFrm = $('body').find('.sd-booking-availability');
            }
            $availabilityFrm.empty();
            $availabilityFrm.dialog('destroy');

            var frm = '<div><p>The next available bookings are listed below. Select an option and click OK, or select Show Avalability to find more alternatives</p>';
            frm += '<button class=\'fg-button ui-state-default ui-corners-all\' style=\'width:92%;height:30px;font-size:.9em;margin-left:10px;margin-bottom:5px;\'>Show Avalability</button>';
            frm += '<div><ul class=\'sd-availability-list\'></ul></div>';
            frm += '</div>';

            $availabilityFrm.append(frm);

            var opt = { modal: true,
                autoOpen: false,
                height: 540,
                width: 340,
                bgiframe: true,
                buttons: { 'Cancel': function () { $(this).dialog("close"); }, 'OK': function () {
                    var selected = $('.sd-availability-item.ui-state-active');
                    var id = selected.attr('id');
                    var sDat = new Date(selected.find('span.sd-availability-itemspan').html());
                    saveAddContactToAppointment(id, self.options.cid, $availabilityFrm, true, sDat);
                }
                }
            };

            $availabilityFrm.dialog(opt);

            $availabilityFrm.dialog('open');

            $availabilityFrm.find('.fg-button').bind('click', function () {
                self._getAppointments();

            });
            self._getAppointments();
        },
        _newBookingForm: function () {
            var self = this;

            var $bookingOptions = $('body').find('.sd-booking-options');

            $bookingOptions.empty();
            $bookingOptions.dialog('destroy');

            var $pageHtml = '';

            $pageHtml += self._createForm();

            self.element.append($pageHtml);

            self.element.find('.dtp').each(function () {
                $(this).datepicker({ dateFormat: 'D d M yy' });
                $('div.ui-datepicker').css('z-index', '10000');
                var value = $(this).val();
                if (value == '') {
                    if (self.options.start != undefined) {
                        value = self.options.start.toDateString();
                    }
                    else {
                        value = new Date().toDateString();
                    }
                    $(this).val(value);
                }
            });
            $('.tpk').each(function () {
                if (self.options.start != undefined) {
                    $(this).val(self.options.start.toTimeString().substr(0, 5));
                }
                $(this).smartTimePicker(); //({ 'secView': false });
            });
            var iDuration = self.element.data('duration');
            var iDay = Math.floor(iDuration / 1440);
            if (iDay > 0) {
                iDuration = iDuration - (iDay * 1440);
            }
            var iHour = Math.floor(iDuration / 60);
            if (iHour > 0) {
                iDuration = iDuration - (iHour * 60);
            }
            iMin = Math.floor(iDuration);

            self.element.find('input.adp').data('day', iDay);
            self.element.find('input.adp').data('hour', iHour);
            self.element.find('input.adp').data('minute', iMin);

            $('.adp').each(function () {
                $(this).smartDurationPicker(); //({ 'secView': false });
            });
            self.element.find('.sd-select-resource').each(function () {
                if (self.options.initialresource != undefined) {
                    $(this).find('option').each(function () {
                        if ($(this).attr('value') == self.options.initialresource)
                            $(this).attr('selected', true);
                    });
                }
                $(this).dropdownchecklist();
                $(this).bind('change', function () {
                    var res = $(this).val();
                    var add = false;
                    var resources = self.element.data('selectedResource');
                    if (resources == undefined) { resources = new Array(); self.element.data('selectedResource', resources); }
                    for (var i = 0; i < res.length; i++) {
                        if ($.inArray(res[i], resources) < -0) {
                            resources.push(res[i]);
                            $('.ui-dropdownchecklist-item input:checkbox').each(function () {
                                if ($(this).val() == res[i]) {
                                    $(this).attr('checked', true);
                                }
                            });
                            $(this).find('option').each(function () {
                                if ($(this).val() == res[i])
                                    $(this).attr('selected', true);
                            });
                        }
                    }
                    $(this).find('option').each(function () {
                        var chck = $(this).attr('selected');
                        var val = $(this).val();
                        if (chck == false) {
                            if ($.inArray(val, resources) > -1) {
                                for (var j = 0; j < resources.length; j++) {
                                    if (resources[j] == val)
                                        resources.splice(j, 1);
                                }
                                $('.ui-dropdownchecklist-item input:checkbox').each(function () {
                                    if ($(this).val() == val) {
                                        $(this).attr('checked', false);
                                    }
                                });
                                $(this).find('option').each(function () {
                                    if ($(this).val() == val)
                                        $(this).attr('selected', false);
                                });
                            }
                        }
                    });

                });
            });
            var subject = self.element.data('subject');
            self.element.find('input.sd-id-15217:text').val(self.element.data('subject'));
            var $cat = self.element.data('category');
            if (self.element.data('category') == undefined) {
                var $val = self.element.find('select.sd-id-15201 option:first').val();
                self.element.data('category', $val);
            }
            self.element.find('select.sd-id-15201').val(self.element.data('category'));
            self.element.find('select.sd-id-15201').bind('change', function () {
                var $cat = $(this).val();
                self.element.data('category', $cat);
            });
            var opt = {
                modal: true,
                autoOpen: true,
                height: 355,
                width: 500,
                bgiframe: true,
                title: 'Quick Booking',
                buttons: { 'Close': function () { $(this).dialog("close"); }, 'Save': function () {

                    //       string smartid, string searchstart, string durationminutes,string anyresources, string allresources

                    var $durrationPicker = self.element.find('input.adp');
                    var d = $durrationPicker.data('day') == null ? 0 : $durrationPicker.data('day');
                    var h = $durrationPicker.data('hour') == null ? 0 : $durrationPicker.data('hour');
                    var m = $durrationPicker.data('minute') == null ? 0 : $durrationPicker.data('minute');
                    var minutes = Math.round((m * 1) + (h * 60) + (d * 24 * 60));

                    self.element.data('subject', self.element.find('input.sd-id-15217').val());

                    var $allresource = [];
                    var $anyresource = [];
                    self.element.find('select.sd-select-resource option:selected').each(function () {
                        $allresource.push($(this).val());
                    });
                    var start = self.element.find('input.dtp').val() + ' ' + self.element.find('input.tpk').val();

                    var $jsonData = serializeTimespanIsAvailable(start, minutes, $anyresource, $allresource);

                    var uri = "/Services/DefaultService.svc/IsTimeSpanAvailable";

                    $.ajax({
                        type: "POST",
                        url: uri,
                        data: JSON.stringify($jsonData),

                        dataType: "json",
                        success: function (msg) {
                            var iAvailable = msg.d;
                            var available = true;
                            var nextStart = new Date(start);
                            for (var i = 0; i < iAvailable.length; i++) {
                                if (iAvailable[i].available == false) {
                                    if (iAvailable[i].nextopenhour != null) {
                                        var nd = JsonToJavaDate(iAvailable[i].nextopenhour);
                                        if (nd > nextStart)
                                            nextStart = nd;
                                    }
                                    if (iAvailable[i].nexttimeslot != null) {
                                        var ns = JsonToJavaDate(iAvailable[i].nexttimeslot);
                                        if (ns > nextStart)
                                            nextStart = ns;
                                    }
                                    available = false;
                                }
                            }
                            if (available == false) {
                                self.options.searchstart = nextStart;
                                self._getAvailability(minutes, $anyresource, $allresource);
                            }
                            else if (available == true) {
                                self.options.appointmentid = jQuery.Guid.New();
                                saveNewAppointment(start, minutes, $anyresource, $allresource, self.element, self.options);
                                self.element.dialog('close');
                                self.element.dialog('destroy');
                            }
                            //                            if (msg.d == true) {
                            //                                self.options.appointmentid = jQuery.Guid.New();
                            //                                saveNewAppointment(start, minutes, $anyresource, $allresource, self.element, self.options);
                            //                                self.element.dialog('close');
                            //                                self.element.dialog('destroy');
                            //                            }
                            //                            else {
                            //                                //alert('The selected date, time and resource combination is not available');
                            //                            }
                        }
                    });
                }
                }
            };
            self.element.dialog(opt);
        },

        _getAvailability: function (minutes, $anyresource, $allresource) {
            var self = this;

            var $availabilityFrm = $('body').find('.sd-booking-availability');
            if ($availabilityFrm.length < 1) {
                $('body').append('<div class=\'sd-booking-availability\' title=\'Booking Availability\'></div>');
                $availabilityFrm = $('body').find('.sd-booking-availability');
            }
            $availabilityFrm.empty();
            $availabilityFrm.dialog('destroy');

            var frm = '<div><p>The selected time resource combination is unavailable. Select Cancel to enter an alternative, or select Show Avalability to find alternatives</p>';
            frm += '<button class=\'fg-button ui-state-default ui-corners-all\' style=\'width:92%;height:30px;font-size:.9em;margin-left:10px;margin-bottom:5px;\'>Show Avalability</button>';
            frm += '<div><ul class=\'sd-availability-list\'></ul></div>';
            frm += '</div>';

            $availabilityFrm.append(frm);

            var opt = { modal: true,
                autoOpen: false,
                height: 540,
                width: 340,
                bgiframe: true,
                buttons: { 'Close': function () { $(this).dialog("close"); }, 'OK': function () {
                    var selected = $('.sd-availability-item.ui-state-active').find('.sd-availability-itemspan').html();
                    var dt = new Date(selected);
                    self.element.find('input.dtp').val(dt.toDateString());
                    self.element.find('input.tpk').val(dt.toTimeString().substr(0, 5));
                    $(this).dialog('close');
                }
                }
            };

            $availabilityFrm.dialog(opt);

            $availabilityFrm.dialog('open');

            $availabilityFrm.find('.fg-button').bind('click', function () {
                self._getDates(minutes, $anyresource, $allresource);

            });

        },
        _getAppointments: function () {
            var self = this;

            var $jsonData = serializeFindAppointmentByBusy(ServiceDate(self.options.searchstart), self.options.busystate, self.options.cid);

            var uri = "/Services/DefaultService.svc/FindAppointmentByBusy";

            $.ajax({
                type: "POST",
                url: uri,
                data: JSON.stringify($jsonData),

                dataType: "json",
                success: function (msg) {
                    var apps = msg.d;
                    if (apps.length > 0) {
                        for (var i = 0; i < apps.length; i++) {
                            var ap = apps[i];
                            var date = JsonToJavaDate(ap.start);
                            $('.sd-availability-list').append('<li class=\'sd-availability-item\' id=\'' + ap.id + '\'><a><span class=\'sd-availability-itemspan\'>' + ServiceDate(date) + '</span></a></li>');
                            date.setMinutes(date.getMinutes() + 1);
                            if (self.options.searchstart < date) {
                                self.options.searchstart = date;
                            }
                        }
                        $('.sd-availability-item').each(function () {
                            $(this).removeClass('ui-state-active');
                            $(this).bind('click', function () {
                                $('.sd-availability-item').each(function () {
                                    $(this).removeClass('ui-state-active');
                                });
                                $(this).addClass('ui-state-active');
                            });
                        });
                    }
                }
            });
        },

        _getDates: function (minutes, $anyresource, $allresource) {
            var self = this;

            var $jsonData = serializeTimespanIsAvailable(ServiceDate(self.options.searchstart), minutes, $anyresource, $allresource);

            var uri = "/Services/DefaultService.svc/IsTimeSpanAvailable";

            $.ajax({
                type: "POST",
                url: uri,
                data: JSON.stringify($jsonData),

                dataType: "json",
                success: function (msg) {

                    var iAvailable = msg.d;
                    var available = true;
                    var nextStart = new Date(self.options.searchstart);
                    for (var i = 0; i < iAvailable.length; i++) {
                        if (iAvailable[i].available == false) {
                            if (iAvailable[i].nextopenhour != null) {
                                var nd = JsonToJavaDate(iAvailable[i].nextopenhour);
                                if (nd > nextStart)
                                    nextStart = nd;
                            }
                            if (iAvailable[i].nexttimeslot != null) {
                                var ns = JsonToJavaDate(iAvailable[i].nexttimeslot);
                                if (ns > nextStart)
                                    nextStart = ns;
                            }
                            available = false;
                        }
                    }
                    if (available) {
                        var dat = self.options.searchstart;
                        $('.sd-availability-list').append('<li class=\'sd-availability-item\'><a><span class=\'sd-availability-itemspan\'>' + ServiceDate(dat) + '</span></a></li>');
                        var $last = $('.sd-availability-list').find('li:last');
                        $last.data('date', dat);
                        self.options.searchstart.setMinutes(self.options.searchstart.getMinutes() + 15);
                        self.options.avdates++;
                        if (self.options.avdates < 3)
                            self._getDates(minutes, $anyresource, $allresource);
                        else {
                            self.options.avdates = 0;
                            $('.sd-availability-item').each(function () {
                                $(this).removeClass('ui-state-active');
                                $(this).bind('click', function () {
                                    $('.sd-availability-item').each(function () {
                                        $(this).removeClass('ui-state-active');
                                    });
                                    $(this).addClass('ui-state-active');
                                });
                            });
                        }
                    }
                    else {
                        self.options.searchstart = new Date(nextStart);
                        self._getDates(minutes, $anyresource, $allresource);
                    }


                    //                    if (msg.d == true) {
                    //                        $('.sd-availability-list').append('<li><a>' + searchStart + '</a></li>');
                    //                        self.options.avdates++;
                    //                        if (self.options.avdates < 3)
                    //                            self._getDates(self.options.searchstart, minutes, $anyresource, $allresource);
                    //                        else
                    //                            self.options.avdates = 0;
                    //                    }
                    //                    else {
                    //                        self._getDates(self.options.searchstart, minutes, $anyresource, $allresource);
                    //                    }
                }
            });
        },

        _computeOptions: function () {
        }


    });

    $.extend($.ui.newAppointment, {
        version: '1.0.1',
        defaults: {
            entity: 'contact',
            cid: '',
            appointmentid: '',
            isNew: false,
            readOnly: false,
            duration: 30,
            mincontact: 0,
            maxcontact: 0,
            category: -1,
            avdates: 0,
            searchstart: '',
            busystate: -1,
            start: undefined,
            end: undefined,
            initialresource: undefined
        }
    });
})(jQuery);
