/**jslint browser:true, devel:true */
/*global jQuery*/
/*global define */
/*global window */
/*jslint this*/
/*global tinymce*/
/*global document*/
/*global wp*/
jQuery(document).ready(function ($) {
    "use strict";
    function changeAdminTab(hash) {
        var mmtmsTable = $('.mmt-eo-ei-admin-table');
        mmtmsTable.attr('data-tab', hash);
        mmtmsTable.find('.mmt-eo-ei-admin-content.active').removeClass('active');
        var ul = mmtmsTable.find('ul.mmt-eo-ei-admin-tab');
        ul.find('li a').removeClass('active');
        $(ul).find('a[href=\\' + hash + ']').addClass('active');
        mmtmsTable.find(hash).addClass('active');
        $("html, body").animate({
            scrollTop: 0
        }, 1000);
    }
    function doNothing() {
        var mmtmsTable = $('.mmt-eo-ei-admin-table');
        mmtmsTable.attr('data-tab', '#mmt-eo-ei-event_card');
        return;
    }
    function init() {
        $("input[name='eb_imports_by_organizer_sd']").datepicker({
            onClose: function( selectedDate , obj) {
				// update end time
				$( "input[name='eb_imports_by_organizer_ed']" ).datepicker( "option", "minDate", selectedDate);
            }
            , numberOfMonths : 2
        });
        $("input[name='eb_imports_by_organizer_ed']").datepicker({
            onClose: function( selectedDate ) {
	        	$( "input[name='eb_imports_by_organizer_sd']" ).datepicker( "option", "maxDate", selectedDate );
            }
            , numberOfMonths : 2
        });
        $("input[name='eb_imports_by_your_events_sd']").datepicker({
            onClose: function( selectedDate , obj) {
				// update end time
				$( "input[name='eb_imports_by_your_events_ed']" ).datepicker( "option", "minDate", selectedDate );
            }
            , numberOfMonths : 2
        });
        $("input[name='eb_imports_by_your_events_ed']").datepicker({
            onClose: function( selectedDate ) {
	        	$( "input[name='eb_imports_by_your_events_sd']" ).datepicker( "option", "maxDate", selectedDate );
              }
              , numberOfMonths : 2
        });
        $("input[name='eb_imports_by_venue_sd']").datepicker({
            onClose: function( selectedDate , obj) {
				// update end time
				$( "input[name='eb_imports_by_venue_ed']" ).datepicker( "option", "minDate", selectedDate );
            }
            , numberOfMonths : 2
        });
        $("input[name='eb_imports_by_venue_ed']").datepicker({
            onClose: function( selectedDate ) {
	        	$( "input[name='eb_imports_by_venue_sd']" ).datepicker( "option", "maxDate", selectedDate );
            }
            , numberOfMonths : 2
        });
        var hash = window.location.hash;
		//console.log(hash);
        var hash = window.location.hash;
        if (hash === '' || hash === 'undefined') {
            doNothing();
        } else {
            changeAdminTab(hash);
        }
        $('#mmt-eo-ei-admin-form .switch-input').each(function () {
            var toggleContainer = $(this).parents('.mmt-eo-ei-admin-toggle-container');
            var afteryes = toggleContainer.attr('afteryes');
            if ($(this).is(":checked")) {
                $('#' + afteryes).addClass('active');
            } else {
                $('#' + afteryes).removeClass('active');
            }
        });
        
        $('body').find('select[name="eb_imports_import_by"]').trigger('change');
    }
    $('body').on('change', 'select[name="eb_imports_import_by"]', function (e){
        e.preventDefault();
        var $select = $(this);
        var $container = $select.closest('#mmt-eo-ei-import');
        switch ( $select.val() ) {
            case 'event_id':
                $container.find('#by_event_id').addClass('show');
                $container.find('#by_organizer_id').removeClass('show');
                $container.find('#by_venue_id').removeClass('show');
                $container.find('#by_your_events').removeClass('show');
            break;
            case 'organizer_id':
                $container.find('#by_event_id').removeClass('show');
                $container.find('#by_organizer_id').addClass('show');
                $container.find('#by_venue_id').removeClass('show');
                $container.find('#by_your_events').removeClass('show');
            break;
            case 'your_events':
                $container.find('#by_event_id').removeClass('show');
                $container.find('#by_organizer_id').removeClass('show');
                $container.find('#by_venue_id').removeClass('show');
                $container.find('#by_your_events').addClass('show');
            break;
            case 'venue_id':
                $container.find('#by_event_id').removeClass('show');
                $container.find('#by_organizer_id').removeClass('show');
                $container.find('#by_venue_id').addClass('show');
                $container.find('#by_your_events').removeClass('show');
        }
    });
    init();
    $('body').on('click', '.eb_search_organizer_id', function (e) {
        e.preventDefault();
        var $form = $(this).closest('#mmt-eo-ei-search');
        var $working = $form.closest('.mmt-eo-ei-admin-tabcontent').find('.mmt_eo_exim_working');
        var $sresult = $form.find('.eb_search_result_block');
        var $eventbrite = $form.find('input[name="eb_id_for_org_id"]');
        var eid = $eventbrite.val();
        if ( "" == eid ) {
            $eventbrite.focus();
            return;
        }
        var ajaxdata = {};
        ajaxdata.security = mmt_eo_exim_admin.mmt_eo_exim_ajax_nonce;
        ajaxdata.action = 'mmt_eo_exim_search_org_ven_id';
        ajaxdata.eid = eid;
        ajaxdata.org_ven = 'org';
        $.ajax({
            beforeSend: function () {
                $eventbrite.prop('disabled', true );
                $working.addClass('show');
            },
            type: 'POST',
            dataType: 'json',
            url: mmt_eo_exim_admin.ajaxurl,
            data: ajaxdata,
            success: function (data) {
                $sresult.html(data.html);
                $sresult.effect('shake');
                $eventbrite.focus();
                $eventbrite.select();
            },
            complete: function () {
                $eventbrite.prop('disabled', false );
                $eventbrite.focus();
                $eventbrite.select();
                $working.removeClass('show');
            }
        });
    });
    $('body').on('click', '.eb_search_venue_id', function (e) {
        e.preventDefault();
        var $form = $(this).closest('#mmt-eo-ei-search');
        var $working = $form.closest('.mmt-eo-ei-admin-tabcontent').find('.mmt_eo_exim_working');
        var $sresult = $form.find('.eb_search_result_block');
        var $eventbrite = $form.find('input[name="eb_id_for_venue_id"]');
        var eid = $eventbrite.val();
        if ( "" == eid ) {
            $eventbrite.focus();
            return;
        }
        var ajaxdata = {};
        ajaxdata.security = mmt_eo_exim_admin.mmt_eo_exim_ajax_nonce;
        ajaxdata.action = 'mmt_eo_exim_search_org_ven_id';
        ajaxdata.eid = eid;
        ajaxdata.org_ven = 'ven';
        $.ajax({
            beforeSend: function () {
                $eventbrite.prop('disabled', true );
                $working.addClass('show');
            },
            type: 'POST',
            dataType: 'json',
            url: mmt_eo_exim_admin.ajaxurl,
            data: ajaxdata,
            success: function (data) {
                $sresult.html(data.html);
                $sresult.effect('shake');
                $eventbrite.focus();
                $eventbrite.select();
            },
            complete: function () {
                $eventbrite.prop('disabled', false );
                $eventbrite.focus();
                $eventbrite.select();
                $working.removeClass('show');
            }
        });
    });
    $('body').on('change', '#mmt-eo-ei-admin-form  .switch-input', function () {
        var toggleContainer = $(this).parents('.mmt-eo-ei-admin-toggle-container');
        var afteryes = toggleContainer.attr('afteryes');
        if ($(this).is(":checked")) {
            $('#' + afteryes).addClass('active');
        } else {
            $('#' + afteryes).removeClass('active');
            $(this).val('off');
        }
    });
    $('.mmt-eo-ei-admin-table').on('click', 'ul.mmt-eo-ei-admin-tab li a', function (e) {
        e.preventDefault();
        var href = $(this).attr('href');
        changeAdminTab(href);
        window.location.hash = href;
    });
    $('body').on('click', '.mmt-eo-exim-cb-ebrite-fetch-more', function (e) {
        e.preventDefault();
        var $form = $(this).closest('#mmt-eo-ei-import');
        var $main_block = $form.find('.eb_imports_main_block');
        var $report_block = $form.find('.eb_imports_report_block');
        var $back_btn = $main_block.find('.mmt-eo-exim-back-to-list-block');
        $report_block.slideUp("slow", function() {
            $back_btn.css('display', 'block');
            $main_block.slideDown().delay('300');
        });
        
    });
    $('body').on('click', '.eb_back_to_fetch_list', function (e) {
        e.preventDefault();
        var $form = $(this).closest('#mmt-eo-ei-import');
        var $main_block = $form.find('.eb_imports_main_block');
        var $report_block = $form.find('.eb_imports_report_block');
        var $back_btn = $main_block.find('.mmt-eo-exim-back-to-list-block');
        $main_block.slideUp("slow", function() {
            $back_btn.css('display', 'none');
            $report_block.slideDown('slow');
        });
        
    });
    $('body').on('click','.eb_fetch_by', function (e) {
        e.preventDefault();
        var $form = $(this).closest('#mmt-eo-ei-import');
        var $block = $(this).closest('.mmt-eo-exim-option-block');
        var $working = $form.closest('.mmt-eo-ei-admin-tabcontent').find('.mmt_eo_exim_working');
        var $main_block = $form.find('.eb_imports_main_block');
        var $report_block = $form.find('.eb_imports_report_block');
        var current_list = $report_block.find('input[name="eb_generated_events"]').val();
        var selectVal = $(this).data('by');
        var ajaxdata = {};
        ajaxdata.security = mmt_eo_exim_admin.mmt_eo_exim_ajax_nonce;
        ajaxdata.current_list = current_list; 
        if( 'event_id' === selectVal ) {
            var eventID = $block.find('input[name="eb_imports_by_event_id_eid"]').val();
            if ( '' === eventID ) {
                $form.find('input[name="eb_imports_by_event_id_eid"]').focus();
                return;
            }
            ajaxdata.action = 'mmt_eo_exim_fetch_by_event_id_eb';
            ajaxdata.event_id = eventID;
            $.ajax({
                beforeSend: function () {
                    $working.addClass('show');
                    $main_block.slideUp();
                },
                type: 'POST',
                dataType: 'json',
                url: mmt_eo_exim_admin.ajaxurl,
                data: ajaxdata,
                success: function (data) {
                    if( 'bad' === data.status ) {
                        $main_block.slideDown();
                        var $msg = $main_block.find('.eb_imports_msg_block');
                        $msg.html(data.msg);
                        $msg.show();
                    }else if('good' === data.status ) {
                        var $container = $form.find('.eb_imports_table');
                        var $tableBody = $container.find('table tbody');
                        var $msgBody = $report_block.find('.eb_imports_msg_block').show();
                        $msgBody.html(data.info);
                        var old = $tableBody.html(); 
                        $tableBody.html(old + data.html);
                        $report_block.find('input[name="eb_generated_events"]').val( data.elist );
                        $container.show();
                        $container.attr('data-eb_sin_eid', data.event_id );
                        $container.show();
                        $report_block.slideDown();
                    }
                },
                complete: function () {
                    $working.removeClass('show');
                }
            });
        } else if( 'organizer_id' === selectVal ) {
            var organizerID = $form.find('input[name="eb_imports_by_organizer_id_oid"]').val();
            var startDate = $form.find('input[name="eb_imports_by_organizer_sd"]').val();
            var endDate = $form.find('input[name="eb_imports_by_organizer_ed"]').val();
            console.log(organizerID);
            if ( '' === organizerID ) {
                $form.find('input[name="eb_imports_by_organizer_id_oid"]').focus();
                return;
            } else if( '' === startDate ) {
                $form.find('input[name="eb_imports_by_organizer_sd"]').focus();
                return;
            } else if( '' === endDate ) {
                $form.find('input[name="eb_imports_by_organizer_ed"]').focus();
                return;
            }
            ajaxdata.action = 'mmt_eo_exim_fetch_by_organizer_id_eb';
            ajaxdata.organizer_id = organizerID;
            ajaxdata.start_date = startDate;
            ajaxdata.end_date = endDate;
            $.ajax({
                beforeSend: function () {
                    $working.addClass('show');
                    $main_block.slideUp();
                },
                type: 'POST',
                dataType: 'json',
                url: mmt_eo_exim_admin.ajaxurl,
                data: ajaxdata,
                success: function (data) {
                    if( 'bad' === data.status ) {
                        $main_block.slideDown();
                        var $msg = $main_block.find('.eb_imports_msg_block');
                        $msg.html(data.msg);
                        $msg.show();
                    }else if('good' === data.status ) {
                        var $container = $form.find('.eb_imports_table');
                        var $tableBody = $container.find('table tbody');
                        var $msgBody = $report_block.find('.eb_imports_msg_block').show();
                        $msgBody.html(data.info);
                        var old = $tableBody.html(); 
                        $tableBody.html(old + data.html);
                        $report_block.find('input[name="eb_generated_events"]').val( data.elist );
                        $container.show();
                        $report_block.slideDown();
                    }
                },
                complete: function () {
                    $working.removeClass('show');
                }
            });
        } else if( 'venue_id' === selectVal ) {
            var venueID = $form.find('input[name="eb_imports_by_venue_id_vid"]').val();
            var startDate = $form.find('input[name="eb_imports_by_venue_sd"]').val();
            var endDate = $form.find('input[name="eb_imports_by_venue_ed"]').val();
            if ( '' === venueID ) {
                $form.find('input[name="eb_imports_by_venue_id_vid"]').focus();
                return;
            } else if( '' === startDate ) {
                $form.find('input[name="eb_imports_by_venue_sd"]').focus();
                return;
            } else if( '' === endDate ) {
                $form.find('input[name="eb_imports_by_venue_ed"]').focus();
                return;
            }
            ajaxdata.action = 'mmt_eo_exim_fetch_by_venue_id_eb';
            ajaxdata.venue_id = venueID;
            ajaxdata.start_date = startDate;
            ajaxdata.end_date = endDate;
            $.ajax({
                beforeSend: function () {
                    $working.addClass('show');
                    $main_block.slideUp();
                },
                type: 'POST',
                dataType: 'json',
                url: mmt_eo_exim_admin.ajaxurl,
                data: ajaxdata,
                success: function (data) {
                    if( 'bad' === data.status ) {
                        $main_block.slideDown();
                        var $msg = $main_block.find('.eb_imports_msg_block');
                        $msg.html(data.msg);
                        $msg.show();
                    }else if('good' === data.status ) {
                        var $container = $form.find('.eb_imports_table');
                        var $tableBody = $container.find('table tbody');
                        var $msgBody = $report_block.find('.eb_imports_msg_block').show();
                        $msgBody.html(data.info);
                        var old = $tableBody.html(); 
                        $tableBody.html(old + data.html);
                        $report_block.find('input[name="eb_generated_events"]').val( data.elist );
                        $container.show();
                        $report_block.slideDown();
                    }
                },
                complete: function () {
                    $working.removeClass('show');
                }
            });
        } else if( 'your_events' === selectVal ) {
            var startDate = $form.find('input[name="evo_eb_imports_by_your_events_sd"]').val();
            var endDate = $form.find('input[name="evo_eb_imports_by_your_events_ed"]').val();
            if( '' === startDate ) {
                $form.find('input[name="evo_eb_imports_by_your_events_sd"]').focus();
                return;
            } else if( '' === endDate ) {
                $form.find('input[name="evo_eb_imports_by_your_events_ed"]').focus();
                return;
            }
            ajaxdata.action = 'mmt_eo_exim_fetch_by_your_event_eb';
            ajaxdata.start_date = startDate;
            ajaxdata.end_date = endDate;
            $.ajax({
                beforeSend: function () {
                    $load.addClass('show');
                    $main_block.slideUp();
                },
                type: 'POST',
                dataType: 'json',
                url: mmt_eo_exim_admin.ajaxurl,
                data: ajaxdata,
                success: function (data) {
                    if( 'bad' === data.status ) {
                        $main_block.slideDown();
                        var $msg = $main_block.find('.evo_eb_imports_msg_block');
                        $msg.html(data.msg);
                        $msg.show();
                    }else if('good' === data.status ) {
                        var $container = $form.find('.evo_eb_imports_table');
                        var $tableBody = $container.find('table tbody');
                        var $msgBody = $report_block.find('.evo_eb_imports_msg_block').show();
                        $msgBody.html(data.info);
                        var old = $tableBody.html(); 
                        $tableBody.html(old + data.html);
                        $report_block.find('input[name="evo_eb_generated_events"]').val( data.elist );
                        $container.show();
                        $report_block.slideDown();
                    }
                },
                complete: function () {
                    $load.removeClass('show');
                }
            });
        }
    });
    $('body').on('click', '.mmt-eo-exim-cb-ebrite-imports', function (e){
        e.preventDefault();
        var $tableContainer = $(this).closest('.eb_imports_table');
        var $table = $tableContainer.find('table');
        var $form = $(this).closest('#mmt-eo-ei-import');
        var $report_block = $form.find('.eb_imports_report_block');
        var $working = $form.closest('.mmt-eo-ei-admin-tabcontent').find('.mmt_eo_exim_working');
        var xhrs = [];
        $table.find('tr').each(function(index, tr) {
            var ebid = $(this).data('eb_eid');
            var status = $(this).data('status');
            var $tr = $(this);
            if ( "imported" != status ) {
                var ajaxdata = {};
                ajaxdata.event_id = ebid;
                ajaxdata.action = 'mmt_eo_exim_import_single_event_eb';
                ajaxdata.security = mmt_eo_exim_admin.mmt_eo_exim_ajax_nonce;
                var xhr = $.ajax({
                    beforeSend: function () {
                        $working.addClass('show');
                    },
                    type: 'POST',
                    dataType: 'json',
                    url: mmt_eo_exim_admin.ajaxurl,
                    data: ajaxdata,
                    success: function (data) {
                        console.log(data);
                        if ( data.status == 'bad' ) {
                            $tr.addClass('bad');
                            $tr.find('.status').html(data.msg);
                        } else if( data.status == 'good' ) {
                            $tr.addClass('good');
                            $tr.data('status', 'Imported');
                            $tr.find('.status').html('imported');
                            
                        }
                    },
                    complete: function () {
                        //$load.removeClass('show');
                    }
                });
                xhrs.push(xhr);
            }
        });
        $.when.apply($, xhrs).done(function(){
            $working.removeClass('show');
        });
    });
    $('body').on('click', '.mmt_eo_exim_save_sttings', function (e) {
        e.preventDefault();
        var $form = $(this).closest('#mmt-eo-ei-eventbrite');
        var $tab = $form.closest('.mmt-eo-ei-admin-tabcontent');
        var $working = $tab.find('.mmt_eo_exim_working');
        var ajaxdata = {};
        ajaxdata.eb_private_token = $form.find('input[name="eb_private_token"]').val();
        ajaxdata.eb_imports_assign_category = $form.find('input[name="eb_imports_assign_category"]').val();
        ajaxdata.eb_imports_category_1 = $form.find('select[name="eb_imports_category_1"]').val();
        ajaxdata.eb_imports_category_2 = $form.find('select[name="eb_imports_category_2"]').val();
        ajaxdata.eb_imports_enable_repeat = $form.find('input[name="eb_imports_enable_repeat"]').val();
        ajaxdata.eb_export_organizer = $form.find('select[name="eb_export_organizer"]').val();
        ajaxdata.eb_exports_enable_custom_repeat = $form.find('input[name="eb_exports_enable_custom_repeat"]').val();
        ajaxdata.eb_default_currency = $form.find('select[name="eb_default_currency"]').val();
        ajaxdata.security = mmt_eo_exim_admin.mmt_eo_exim_ajax_nonce;
        ajaxdata.action = 'mmt_eo_exim_save_eb_settings';
        console.log(ajaxdata);
        $.ajax({
            beforeSend: function () {
                $working.addClass('show');
            },
            type: 'POST',
            dataType: 'json',
            url: mmt_eo_exim_admin.ajaxurl,
            data: ajaxdata,
            success: function (data) {
                if ( data.status == 'good' ) {
                    $working.removeClass('show');
                }
            },
            complete: function() {
                location.reload();
            }
        });
    });
    /**** MetaBox Script */
    $('body').on('change', '#mmt-eo-ei-metabox-form  .switch-input', function () {
        var toggleContainer = $(this).parents('.mmt-eo-ei-admin-toggle-container');
        var afteryes = toggleContainer.attr('afteryes');
        if ($(this).is(":checked")) {
            $('#' + afteryes).addClass('active');
        } else {
            $('#' + afteryes).removeClass('active');
            $(this).val('off');
        }
    });
    $('#mmt-eo-ei-metabox-form .switch-input').each(function () {
        var toggleContainer = $(this).parents('.mmt-eo-ei-admin-toggle-container');
        var afteryes = toggleContainer.attr('afteryes');
        if ($(this).is(":checked")) {
            $('#' + afteryes).addClass('active');
        } else {
            $('#' + afteryes).removeClass('active');
        }
    });
    $('body').on('change', 'select[name="evo_eb_export_export_event_status"]', function () {
        var select = $(this).val();
        var $parent = $(this).closest('#mmt-eo-ei-metabox-form');
        var $ticket = $parent.find('.mmt-eo-ei-block-ticket');
        if ('publish' === select) {
            $ticket.removeClass('mmt-eo-ei-block-hidden');
        } else {
            $ticket.addClass('mmt-eo-ei-block-hidden');
        }
    });
    $('body').on('change', 'select[name="evo_eb_export_export_event_ttype"]', function () {
        var select = $(this).val();
        var $parent = $(this).closest('#mmt-eo-ei-metabox-form');
        var $ticket_price = $parent.find('.mmt-eo-ei-block-ticket-price');
        if ('paid' === select) {
            $ticket_price.removeClass('mmt-eo-ei-block-hidden');
        } else {
            $ticket_price.addClass('mmt-eo-ei-block-hidden');
        }
    });
});