﻿/*!
* jQuery Flight PlugIn. 
* Author: Shlomi Levi.
* Company: Netwise LTD.
*/
(function(jQuery) {
    var now = new Date();

    methods = {
        settings: {
            disabledDays: [],
            tabs: null,
            startTab: 0,
            url: '',
            title: '',
            range: [0, 1, 2, 3, 4, 5, 6],
            department: [{ "id": 0, "Name": "תיירים" }, { "id": 1, "Name": "עסקים"}],
            buttonImage: '/App_Themes/Default/images/calendar-icon.gif',
            cookie: null,
            airlines: null
        },
        init: function(options) {
            return this.each(function() {
                // If options exist, lets merge them with our default settings
                if (options) { $.extend(methods.settings, options); }

                // flight plugin code here
                var flight = $(this);

                // title
                if (methods.settings.title != '')
                    $('<div>').addClass('flight-title')
                              .html(methods.settings.title)
                              .insertBefore($('.flight-pass'));
                // tabs
                var contents = $('<div/>', { id: 'flight-content' });
                var tabs = $('<div/>', { id: 'flight-tabs' });

                contents.insertBefore($('.flight-pass'))
                        .before(tabs);

                var index = 0;
                $.each(methods.settings.tabs, function(name, value) { // tab
                    ++index;

                    $("<input>", {
                        'type': 'radio',
                        'name': 'rdio',
                        'value': value.id,
                        'id': 'rdio',
                        'click': function() {
                            $('div#flight-content > .selected').removeClass('selected').hide();
                            $('div#flight-content > :eq(' + $(this).parent().index() + ')').addClass('selected').show();

                            $('#flight-tabs :radio').prop('checked', false);
                            $(this).prop('checked', true);
                        }
                    }).appendTo(tabs);


                    $("<label/>", {
                        'for': 'rdio' + value.id,
                        'html': name
                    }).appendTo(tabs);

                    tabs.find("> input, > label")
                        .wrapAll('<span>');

                    // content
                    $.each($(value.flightBox), function(i, v) {
                        methods.RenderFlightBox(v.title, v.withReturnField, v.withAdd, v.defaultFrom).appendTo(contents);
                    });

                    //wrap
                    $('#flight-content > fieldset.flight-box').wrapAll($('<div/>', { 'class': 'tab' + index }).hide());
                });

                // set default values in dropdownlist on flight-pass
                var ddloptions = '';
                $.each(methods.settings.range, function(index, value) {
                    if (index == 0) { ddloptions += '<option selected value="' + value + '">' + value + '</option>'; }
                    else { ddloptions += '<option value="' + value + '">' + value + '</option>'; }
                });

                $('fieldset.flight-pass select').each(function(index) {
                    $(this).html(ddloptions);
                });

                // Set Airline Company List and department
                $('select#AirlineCompany').html(methods.fillOptions(methods.settings.airlines));
                $('select#AirlineDepartment').html(methods.fillOptions(methods.settings.department));

                $('a.search-by').click(function() { $('div#search-by').toggle(); return false; });
                //$('a.flight-toggle').click(function() { $('div.in-search').toggle(); return false; });
                $('a.search-button').click(methods.Search);
                flight.find('input.to, input.from')
                      .live('click', function() { flightModal.show($(this)); return false; });

                methods.SetDatepicker();

                $('select#adult').find("option[value='1']").attr("selected", "selected"); //default pass

                $('div#flight-tabs :radio')[methods.settings.startTab].click();
            });

        },
        RenderFlightBox: function(title, withReturnField, withAdd, defaultFrom) {
            var flightbox = $('<fieldset>').addClass("flight-box")
                                       .append($('<p>').html(title));

            $('<span>').append($('<label>').html('מ:'),
                               $('<input readonly="readonly" type="text" class="from textbox" />')).appendTo(flightbox);

            $('<span>').append($('<label>').html('אל:'),
                           $('<input readonly="readonly" type="text" class="to textbox" />')).appendTo(flightbox);

            $('<span>').append($('<label>').html('תאריך יציאה:'),
                               $('<input headerTitle="בחר תאריך הלוך" readonly="readonly" type="text" class="datepicker datetarget textbox" />')
                                .val(now.format("dd/mm/yyyy"))).appendTo(flightbox);

            if (withReturnField) {
                var week = new Date();
                week.setDate(week.getDate() + 7);

                $('<span>').append($('<label>').html('תאריך חזרה:'),
                                   $('<input headerTitle="בחר תאריך חזור" readonly="readonly" type="text" class="datepicker dateback textbox" />')
                                        .val(week.format("dd/mm/yyyy"))).appendTo(flightbox);
            }

            if (withAdd) {
                flightbox.append($('<a>').attr("href", "#")
                                     .addClass('add-flight')
                                     .html("להוספת טיסה")
                                     .click(methods.addFlight));
            }

            if (defaultFrom) {
                flightbox.find('input.from').val(defaultFrom[0].val)
                                            .data('info', defaultFrom[0].info);
            }

            return flightbox;
        },
        addFlight: function() {
            var flightBoxes = $('fieldset.flight-box:visible');

            methods.RenderFlightBox('טיסה ' + (flightBoxes.length + 1), false, (flightBoxes.length != 3))
                    .appendTo($(this).parent().parent());

            methods.SetDatepicker();

            $(this).replaceWith($('<a>').attr("href", "#")
                                    .addClass('remove-flight')
                                    .html("להסרת טיסה")
                                    .click(methods.removeFlight));
            return false;
        },
        removeFlight: function() {
            var flightBox = $(this).parent();

            flightBox.nextAll().remove();

            $(this).replaceWith($('<a>').attr("href", "#")
                                    .addClass('add-flight')
                                    .html("להוספת טיסה")
                                    .click(methods.addFlight));
            return false;
        },
        fillOptions: function(collection) {
            var options = '';
            $.each(collection, function(index, value) {
                if (index == 0) { options += '<option selected value="' + value.id + '">' + value.Name + '</option>'; }
                else { options += '<option value="' + value.id + '">' + value.Name + '</option>'; }
            });

            return options;
        },
        noWeekendsOrHolidays: function(date) {
            var noWeekend = jQuery.datepicker.noWeekends(date);
            return noWeekend[0] ? jQuery.datepicker.SetDisabledDays(date, methods.settings.disabledDays) : noWeekend;
        },
        customRange: function(input) {
            var min = new Date(); //Set this to your absolute minimum date
            var dateMin = min;
            var dateMax = null;
            var dayRange = 6; // Set this to the range of days you want to restrict to

            if ($(input).hasClass("IsraelDateBack")) {
                dayRange = 3;
            }

            if ($(input).hasClass("datetarget")) {
                dateMin = new Date();
            }
            else if ($(input).hasClass("dateback")) {
                var dateTarget = $(input).parent().prev().find('input.datetarget');

                dateMax = new Date(); //Set this to your absolute maximum date
                if (dateTarget.datepicker("getDate") != null) {
                    dateMin = dateTarget.datepicker("getDate");
                    dateMin.setDate(dateMin.getDate() + 1);
                    var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(), dateMin.getDate() + dayRange);

                    if (rangeMax < dateMax) {
                        dateMax = rangeMax;
                    }

                    dateMax = null;
                }
            }
            return {
                minDate: dateMin,
                maxDate: dateMax
            };
        },
        SetDatepicker: function() {
            $('.datepicker').datepicker({
                numberOfMonths: 2,
                isRTL: true,
                showOn: 'both',
                buttonImage: methods.settings.buttonImage,
                buttonImageOnly: true,
                constrainInput: true,
                onSelect: function() {
                    if ($(this).hasClass('datetarget')) {
                        var flightbox = $(this).parent().parent();
                        var dateback = new Date($.datepicker.parseDate('dd/mm/yy', $(this).val()));
                        dateback.setDate(dateback.getDate() + 6);
                        $('input.dateback', flightbox).val(dateback.format('dd/mm/yyyy'))
                    }
                },
                beforeShow: methods.customRange
                // beforeShowDay: methods.beforeDatepickerShow
            });

        },
        CurrentTabIndex: function() {
            return parseInt($('#flight-tabs :checked').val());
        },
        Validate: function() {
            // remove the errors
            $('.error', $(this)).removeClass('error');

            var emptys = $('input.from:text[value=""]:visible, input.to:text[value=""]:visible');
            //var selectors = $('.flight-pass > span > #ddlAdult[val=="0"]: , .flight-pass > span > #ddlPensioner[val=="0"], .flight-pass > span > #ddlYoung[val=="0"]');

            if (emptys.length > 0) {
                emptys.addClass('error');
                return false;
            }

            //            if (selectors.length == 3)
            //            {
            //                selectors.addClass('error');
            //                return false;
            //            }

            return true;
        },
        AddToCookie: function(field, info, limit) {

            // save the to field
            methods.settings.cookie.items.push({
                'field': field.getPath(limit),
                'info': info,
                'val': field.val()
            });

        },
        Search: function() {
            if (!methods.Validate())
                return;
            methods.settings.cookie = { items: [], startTab: $('#flight-tabs :checked').parent().index() };
            var dateDiffFlights = 0;
            $('fieldset.flight-box:visible').each(function(index, value) {
                var cIndex = index + 1;

                var from = $(this).find('input.from').data('info');
                var to = $(this).find('input.to').data('info');

                methods.settings.url += "fcid" + cIndex + "=" + from.CityID + "&";
                methods.settings.url += "tcid" + cIndex + "=" + to.CityID + "&";
                methods.settings.url += "faid" + cIndex + "=" + from.AirportID + "&";
                methods.settings.url += "taid" + cIndex + "=" + to.AirportID + "&";
                methods.settings.url += "fccd" + cIndex + "=" + from.CountryID + "&";
                methods.settings.url += "tccd" + cIndex + "=" + to.CountryID + "&";

                methods.settings.url += "fd" + cIndex + "=" + $(this).find('input.datepicker').val() + "%2000:00:00&";

                var dateTargetArr = $(this).find('input.datepicker').val().split('/');
                var dateTarget = new Date(dateTargetArr[2], dateTargetArr[1] - 1, dateTargetArr[0]).getTime();
                dateDiffFlights = parseInt((dateTarget - new Date()) / (24 * 3600 * 1000)) + 1;

                methods.AddToCookie($(this).find('input.from'), from, 'flight-content');
                methods.AddToCookie($(this).find('input.to'), to, 'flight-content');
                methods.AddToCookie($(this).find('input.datetarget'), '', 'flight-content');

                if ($(this).find('input.dateback').length > 0) {
                    cIndex++;

                    methods.settings.url += "fcid" + cIndex + "=" + to.CityID + "&";
                    methods.settings.url += "tcid" + cIndex + "=" + from.CityID + "&";
                    methods.settings.url += "faid" + cIndex + "=" + to.AirportID + "&";
                    methods.settings.url += "taid" + cIndex + "=" + from.AirportID + "&";
                    methods.settings.url += "fccd" + cIndex + "=" + to.CountryID + "&";
                    methods.settings.url += "tccd" + cIndex + "=" + from.CountryID + "&";

                    methods.settings.url += "fd" + cIndex + "=" + $(this).find('input.dateback').val() + "%2000:00:00&";

                    methods.AddToCookie($(this).find('input.dateback'), '', 'flight-content');
                }
            });

            if ($('div#search-by').css("display") == 'block') {
                if ($('#AirlineCompany').val() != 0) {
                    methods.settings.url += "acid=" + $('#AirlineCompany').val() + "&";
                    methods.settings.url += "fclid=" + $('#AirlineDepartment').val() + "&";
                }
            }

            methods.settings.url += "babn=" + $('.flight-pass > span > #baby').val() + "&";
            methods.settings.url += "chin=" + $('.flight-pass > span > #child').val() + "&";
            methods.settings.url += "youn=" + $('.flight-pass > span > #young').val() + "&";
            methods.settings.url += "adun=" + $('.flight-pass > span > #adult').val() + "&";
            methods.settings.url += "penn=" + $('.flight-pass > span > #pensioner').val() + "&";

            methods.AddToCookie($('.flight-pass > span > #baby'), '', 'flight-pass');
            methods.AddToCookie($('.flight-pass > span > #child'), '', 'flight-pass');
            methods.AddToCookie($('.flight-pass > span > #young'), '', 'flight-pass');
            methods.AddToCookie($('.flight-pass > span > #adult'), '', 'flight-pass');
            methods.AddToCookie($('.flight-pass > span > #pensioner'), '', 'flight-pass');

            methods.settings.url += "fdt=" + methods.CurrentTabIndex() + "&";
            methods.settings.url += "fisd=False&fisch=False&fisr=False";
            methods.settings.url += "&DateDelta=" + dateDiffFlights;
            
            $.JSONCookie('flights', methods.settings.cookie);

             top.location.href = methods.settings.url;
        }
    };

    $.fn.flight = function(method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.flight');
        }

    };

})(jQuery);

