jQuery.noConflict();
(function($) {
$.fn.replaceWith = function(replacement) {
  return this.each(function(){
    element = $(this);
    $(this)
      .after(replacement).next()
      .attr('class', element.attr('class')).attr('id',element.attr('id'))
      .html(element.html())
      .prev().remove();
  });
};

// use publist to make a slider on homepage. only is done on publist with list-to-slider class and adds content to a div with list-to-orbit class
var items = $('.list-to-slider.t-publist li');
var items_per_frame = 4;

if (items.length>0) {
	$('.slick-carousel').html('');
	for (var i=0;i<items.length;i++) {
		var slick_item = $("<div class = 'orbit-item'>");
		var slick_title = $("<div class='orbit-title'>");
		var list_item = $(items).eq(i);
		$(slick_title).html($(list_item).find('.orbit-title').html());
		var slick_img = $("<div class='orbit-img'>");
		$(slick_img).html($(list_item).find('.orbit-img').html());
		$(slick_item).append(slick_title).append(slick_img);
		$('.slick-carousel').append(slick_item);
	}
}

var items = $('.list-to-grid.t-publist li');

var items = $('.list-to-grid.t-publist li');
if (items.length>0) {
	$('.list-to-grid ul.grid-holder').html('');
	for (var i=0;i<items.length;i++) {
		var orbit_slide = $("<li>");
		var this_index = i;
		buildListItem(items,this_index,orbit_slide)
		$('.list-to-grid  ul.grid-holder').append(orbit_slide);
	}
}

function buildListItem(items,this_index,orbit_slide){
  var orbit_item = $("<div class='orbit-item'>");
  var orbit_title = $("<div class='orbit-title'>");
  var list_item = $(items).eq(this_index);
  $(orbit_title).html($(list_item).find('.orbit-title').html());
  var orbit_img = $("<div class='orbit-img'>");
  $(orbit_img).html($(list_item).find('.orbit-img').html());
  $(orbit_item).append(orbit_title).append(orbit_img);
  $(orbit_slide).append(orbit_item);
}

//console.log($(window).width());

if($(window).width()>900){
  //console.log($(window).width())
$('.slick-carousel').slick({
  slidesToShow: 4,
  slidesToScroll: 4,
  autoplay:false,
  adaptiveHeight: true,
  nextArrow: '<a href="#" class="slick-next orbit-next" style = "height:47px; width:47px; content:none">Next <span></span></a>'

});
}else{
$('.slick-carousel').slick({
  slidesToShow: 3,
  slidesToScroll: 3,
  autoplay:false,
  adaptiveHeight: true,
  nextArrow: '<a href="#" class="slick-next orbit-next" style = "height:47px; width:47px; content:none">Next <span></span></a>'

});

}



// set columns
var grid = $('.main-content-grid');
var cols = $(grid).find('.columns');
if (cols.length==2) {
    $(cols).eq(0).addClass("large-9 push-3");
    $(cols).eq(1).addClass("large-3 pull-9");
}
else if (cols.length==3) {
    $(cols).eq(0).addClass("large-6 push-3");
    $(cols).eq(1).addClass("large-3 pull-6");
    $(cols).eq(2).addClass("large-3");
}

//set tab index on checkout forms
$('.t-commercestep form').find('input,select').each(function(i,v) {
   $(v).attr("tabindex",i);
});


// Add placeholder text to the quicksearch box since there's no label
// otherwise.
$('#quickSearchForm-1-searchText').attr('placeholder', 'Search')


$('#help-verification-number').addClass('reveal-modal').append('<a class="close-reveal-modal">&#215;</a>');
$('#t-cart-item-counter').insertAfter('.top-bar-section .carticon').show();
$('input.t-submit,p.t-logout a,.t-submit-acceptfree').addClass('button');
$('.t-remember,.t-latest-publist li,ul.t-items,.t-register .t-field,.t-contact-us .t-field,div.t-collectionindex li,.t-login .t-field').addClass('container');
$('.t-userdetails .t-subscriptions, .t-userdetails .t-accountinfo').addClass('panel').addClass('center');
$('.t-offers').addClass('panel');
$('.search-results .t-nav').attr('data-magellan-expedition','fixed');
var loginhtml = $('.t-login.panel h2.t-loginbox-logged-on').html();
$('.t-login.panel h2.t-loginbox-logged-on').html('<small>'+loginhtml+'</small>').replaceWith('<h4>');
$('h1.t-offers-none').parent().parent().addClass('t-offers-none');
$('.t-toc-range-free').addClass('button').addClass('free');
$('.t-toc-range-buy').addClass('button').addClass('buy');
$('.t-submit-buynow-cart').addClass('button').addClass('buy');
$('.t-toc ul li').each(function() {
    $(this).find('.t-toc-range-download:first').show();
});
$('.t-toc-logical-pageno:first').parents('.t-toc').addClass('t-logical-on');
$('.t-logical-pageno:first').parents('ol.container').addClass('t-logical-on');
$('.t-commercestep.t-cvv2 a').each(function(i,v) {
   $(v).attr("onclick","");
   $(v).attr("href","whatsthis");
   $(v).addClass('hide-for-small');
   $(v).on("click",function() {
       $('#help-verification-number').foundation('reveal', 'open');
       return false;
   });
   return false;
});
$('input[value="Revise purchase details"]').removeClass('button').addClass('revise-purchase');
$('.row.main-content-grid').show();
$(document).foundation();
})(jQuery);


// **********************************************************************
// **********************************************************************
// **********************************************************************
//
// Remainder extracted from Tizra JavaScript.js in Bootstrap template
//
// **********************************************************************
// **********************************************************************
// **********************************************************************

//==============================================================================
// window.tizra global object
//==============================================================================

;(function (tizra, $) {
    const defaults = {
        /**
         * Check if the user is signed in. SSO sites can override this by
         * setting tizra.loggedIn to an alternate implementation in the
         * global header.
         *
         * @returns true if user is signed in
         */
        loggedIn: function () {
            return !! $('#loginForm-1-logout').length
        },

        /**
         * Check if the user is signed in, otherwise show the login form.
         * SSO sites can override this by setting tizra.requireLogin to an
         * alternate implementation in the global header.
         *
         * @returns true if already signed in
         */
        requireLogin: function () {
            if (tizra.loggedIn()) {
                return true
            }
            $('#myModal').modal('show')  // #myModal really?!?
        },

        /**
         * Promise-based fetcher that sets appropriate options for tizra
         * and attaches parsed JSON as response.data
         */
        fetch: function (url, options) {
            options = Object.assign({
                credentials: 'include',  // send cookies!
                headers: {
                    'content-type': 'application/json',
                },
                // Don't set mode: 'no-cors' because that prevents setting
                // custom headers such as content-type.
            }, options || {})

            // Encode options.data as JSON body.
            if ('data' in options && !('body' in options)) {
                options.body = JSON.stringify(options.data)
            }
            delete options.data

            return fetch(url, options)
                .then(function (response) {
                    // Decode response as json, if possible, and attach as
                    // response.data.
                    return response.json()
                        .then(function (data) {
                            response.data = data
                            return response
                        })
                        .catch(function () {
                            // Note this doesn't catch failed fetches, only
                            // failed JSON decodes.
                            console.warn("couldn't decode JSON response")
                            return response
                        })
                })
        },

        /**
         * Array sorter using localeCompare.
         */
        magicSort: function (arr, key, inPlace) {
            const result = inPlace ? arr : arr.slice()
            const keyString = function (x) {
                x = key ? key(x) : x
                return x === null || x === undefined ? '' : '' + x
            }
            result.sort(function (a, b) {
                a = keyString(a)
                b = keyString(b)
                return a.localeCompare(b, undefined, {
                    sensitivity: 'base',
                    ignorePunctuation: true,
                    numeric: true,
                })
            })
            return result
        },

        /**
         * escapeRegExp ponyfill...
         * https://github.com/benjamingr/RegExp.escape/blob/master/polyfill.js
         * except a simple function rather than a speculative polyfill.
         */
        escapeRegExp: function (s) {
            return String(s).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
        },

        /**
        * Escape quotation marks in addition to ampersand and left
        * angle bracket, so it can be used for attribute values too.
        * https://stackoverflow.com/a/9189067/347386
        */
        escapeHtml: function (s) {
            return String(s)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
        },

        /**
        * Catch form submit and enter key in inputs to invoke handler.
        * Caller is responsible for e.preventDefault()
        */
        onSubmit: function (form, selector, handler) {
            if (! handler) {
                handler = selector
                selector = 'input'
            }
            const $forms = $(form)

            $forms.each(function () {
                const $form = $(this)
                const $inputs = $form.find('input')

                $inputs.on('keydown', function (e) {
                    // isDefaultPrevented checks whether the auto-complete code has
                    // already handled this event.
                    if (e.keyCode === 13 && !e.isDefaultPrevented()) {
                        return handler(e, $form[0])
                    }
                })
            })

            $forms.on('submit', function (e) {
                return handler(e, e.target)
            })
        },

        // Page recognizers.
        isBookshelfPage: function () {
            return !! $('.my-bookshelf').length
        },
        isDetailPage: function () {
            return !! $('div.t-toc').length
        },
        isExcerptDetailPage: function () {
            return !! $('div.t-excerpt-toc').length
        },
        isBookDetailPage: function () {
            return !! $('div.t-document-toc').length
        },
        isSearchResultsPage: function () {
            return !! $('.t-hitcount, .t-nohits').length
        },

        // Form helpers.
        disableForm: function (form) {
            $(form).find('fieldset').prop('disabled', true)
        },
        enableForm: function (form) {
            $(form).find('fieldset').prop('disabled', false)
        },
        resetFeedback: function (formGroup) {
            const $formGroup = $(formGroup)
            $formGroup.find('.form-control-feedback').each(function () {
                const $feedback = $(this)
                // save the first time
                if (!$feedback.is('[data-original]')) {
                    $feedback.attr('data-original', $feedback.html())
                }
                // restore every time
                $feedback.html($feedback.attr('data-original'))
            })
            $formGroup.find('.form-control')
                .removeClass('is-valid is-invalid')
            $formGroup.find('.form-control-feedback')
                .removeClass('valid-feedback invalid-feedback')
        },
        setFeedback: function (formGroup, status, message) {
            const $formGroup = $(formGroup)
            const valid = status === 'success' ? 'valid' : 'invalid'
            tizra.resetFeedback($formGroup)
            if (message) {
                $formGroup.find('.form-control-feedback')
                    .html(message)
            }
            $formGroup.find('.form-control')
                .addClass('is-' + valid)
            $formGroup.find('.form-control-feedback')
                .addClass(valid + '-feedback')
        },
        fillFromQueryString: function (mapQueryInputs, opts) {
            opts = Object.assign({
                blank: false,
            }, opts)
            const search = new URLSearchParams(window.location.search)
            Object.entries(mapQueryInputs).forEach(function (kv) {
                const k = kv[0], $input = $(kv[1]), v = search.get(k) || ''
                if (v || opts.blank) {
                    $input.val(v)
                }
            })
        },

        // Utilities.
        safeSplit: function (str, splitter) {
            return ((str || '')
                    .split(splitter)
                    .map(function (s) { return s.trim() })
                    .filter(function (s) { return s.length })
            )
        },
        fullUrl: function (u) {
            return new URL(u, document.location).href
        },
        sameUrl: function (a, b) {
            const urls = [a, b]
                .map(tizra.fullUrl)
                .map(function (s) { return s.replace(/^https?:/i, '') })
            return urls[0] === urls[1]
        },
    }

    // Overwrite defaults with existing tizra object, then overwrite tizra
    // object with final result.
    Object.assign(tizra, Object.assign(defaults, tizra))
})(window.tizra = window.tizra || {}, jQuery)


//==============================================================================
// SEARCH APP
//
// The react-powered search app runs in its own isolated JS, but needs some
// interaction with other parts of the page. Conditionally hook those up
// here.
//==============================================================================

jQuery(function ($) {
    // Wire the advanced search link to switch screens rather than loading
    // the page from the server, so that search parameters are preserved.
    if (tizra.switchToAdvancedSearch) {
        $('.t-advancedlink a').on('click', function (e) {
            e.preventDefault()
            tizra.switchToAdvancedSearch()
        })
    }
})

jQuery(function ($) {
    // Give the quick search auto-completing powers by calling into the
    // search app.
    if (tizra.autoComplete && $.fn.autoComplete) {
        let $inputs = $('.t-quick-data input[name="searchText"]')
        if (! $('#root.ui').length) {
            // Might as well augment traditional advanced search too.
            $inputs = $inputs.add('.t-advancedsearch .t-input input[name="searchText"]')
        }
        $inputs.each(function (_, elem) {
            const $input = $(elem)
            $input.attr({
                autocapitalize: "none",
                autocomplete: "off",
                autocorrect: "off",
            })
            $input.autoComplete({
                source: function (term, suggest) {
                    tizra.autoComplete(
                        term,
                        $input[0].selectionStart,
                        $input[0].selectionEnd
                    )
                        .then(suggest)
                },
                renderItem: function (completion, search) {
                    const json = JSON.stringify(completion)
                    return (
                        '<div class="autocomplete-suggestion"' +
                        ' data-val="' + tizra.escapeHtml(completion.full) + '"' +
                        ' data-json="' + tizra.escapeHtml(json) + '"' +
                        '>' + (
                            tizra.escapeHtml(completion.before) +
                            '<strong>' + tizra.escapeHtml(completion.suggestion) + '</strong>' +
                            tizra.escapeHtml(completion.after)
                        ) +
                        '</div>'
                    )
                },
                onSelect: function (e, val, $item) {
                    const completion = JSON.parse($item.attr('data-json'))
                    $input[0].focus()
                    $input[0].selectionStart = completion.selectionStart
                    $input[0].selectionEnd = completion.selectionEnd
                    // immediately call for completions based on the
                    // new input
                    $input.trigger('keyup.autocomplete')
                },
                delay: 0,  // handled by tizra.autoComplete
                cache: false,  // handled by tizra.autoComplete
                minChars: 0,  // handled by tizra.autoComplete
                liveValue: false,
                propagateEnter: false,
                propagateTab: false,
            })
        })
    }
})

jQuery(function ($) {
    // Wire the quick search box to update search results while keeping the
    // rest of the filter settings intact.
    if (tizra.quickSearch) {
        function quickUpdate(form, isSubmit) {
            const data = $(form)
                .serializeArray()
                .reduce(function (acc, cur) {
                    acc[cur.name] = cur.value
                    return acc
                }, {})
            tizra.quickSearch({
                terms: data.searchText,
                context: data.context,
            }, isSubmit)
        }
        const $forms = $('.t-quick-data input[name="searchText"]')
            .closest('form')
        tizra.onSubmit($forms, function (e, form) {
            e.preventDefault()
            quickUpdate(form, true)
        })
        // additionally update immediately when the context changes
        $forms.find('select[name="context"]')
            .on('change', function () {
                const $form = $(this).closest('form')
                quickUpdate($form, false)
            })
    } else {
        // The search application isn't available because we're not on the
        // advanced search or search results page. The quick search form
        // will submit normally and the search application will discover
        // the query paramters in document.location
    }
})
